分享

一步一步学lucene——(第二步:示例篇)

本帖最后由 gefieder 于 2015-4-19 22:40 编辑
问题导读:
1、如何使用lucene对硬盘上的文件建立索引?
2、如何在索引文件中查询一个词?
3、索引过程中的几个核心类是?它们的作用是?




接上篇:一步一步学lucene——(第一步:概念篇)

在上面的篇幅中我们已经了解到了lucene,及lucene到底是做什么的,什么情况下才能够使用lucene,下面我们就结合一个例子来详细说明一下lucene的API,看看lucene是如何工作的。
lucene的下载其实这个很简单了,直接到baidu或者google上搜索一下,一般情况下第一个就是我们要的链接。下边给出lucene下载的链接:
http://lucene.apache.org/
index.png                 图:lucene下载主页面
配置环境我们下面要做很多的测试,会建立很多的测试工程,如果一个一个手动的添加jar包会非常的麻烦,那么我们就需要配置eclipse环境。
打开eclipse,选择windows->preferences->java->build path->user libraries
将我们上边下载后的lucene中的包全部加载到这个用户变量中。
index.png
               图:eclipse中加入的用户变量
建立索引下面这个程序就是读取指定文件夹下的文件并且将文件生成索引的过程,它有两个参数,一个是要索引的文件路径,一个是索引存放的路径。
我们将文件放到我们硬盘的目录上,然后通过程序建立索引。
索引程序如下:
  1. public class Indexer {
  2.     public static void main(String[] args) throws Exception {
  3.         if (args.length != 2) {
  4.             throw new IllegalArgumentException("Usage: java "
  5.                     + Indexer.class.getName() + " <index dir> <data dir>");
  6.         }
  7.         String indexDir = args[0]; // 1
  8.         String dataDir = args[1]; // 2
  9.         long start = System.currentTimeMillis();
  10.         Indexer indexer = new Indexer(indexDir);
  11.         int numIndexed;
  12.         try {
  13.             numIndexed = indexer.index(dataDir, new TextFilesFilter());
  14.         } finally {
  15.             indexer.close();
  16.         }
  17.         long end = System.currentTimeMillis();
  18.         System.out.println("Indexing " + numIndexed + " files took "
  19.                 + (end - start) + " milliseconds");
  20.     }
  21.     private IndexWriter writer;
  22.     public Indexer(String indexDir) throws IOException {
  23.         Directory dir = FSDirectory.open(new File(indexDir));
  24.         writer = new IndexWriter(dir, // 3
  25.                 new StandardAnalyzer( // 3
  26.                         Version.LUCENE_30),// 3
  27.                 true, // 3
  28.                 IndexWriter.MaxFieldLength.UNLIMITED); // 3
  29.     }
  30.     public void close() throws IOException {
  31.         writer.close(); // 4
  32.     }
  33.     public int index(String dataDir, FileFilter filter) throws Exception {
  34.         File[] files = new File(dataDir).listFiles();
  35.         for (File f : files) {
  36.             if (!f.isDirectory() && !f.isHidden() && f.exists() && f.canRead()
  37.                     && (filter == null || filter.accept(f))) {
  38.                 indexFile(f);
  39.             }
  40.         }
  41.         return writer.numDocs(); // 5
  42.     }
  43.     private static class TextFilesFilter implements FileFilter {
  44.         public boolean accept(File path) {
  45.             return path.getName().toLowerCase() // 6
  46.                     .endsWith(".txt"); // 6
  47.         }
  48.     }
  49.     protected Document getDocument(File f) throws Exception {
  50.         Document doc = new Document();
  51.         doc.add(new Field("contents", new FileReader(f))); // 7
  52.         doc.add(new Field("filename", f.getName(), // 8
  53.                 Field.Store.YES, Field.Index.NOT_ANALYZED));// 8
  54.         doc.add(new Field("fullpath", f.getCanonicalPath(), // 9
  55.                 Field.Store.YES, Field.Index.NOT_ANALYZED));// 9
  56.         return doc;
  57.     }
  58.     private void indexFile(File f) throws Exception {
  59.         System.out.println("Indexing " + f.getCanonicalPath());
  60.         Document doc = getDocument(f);
  61.         writer.addDocument(doc); // 10
  62.     }
  63. }
复制代码


然后在工程上点击右键Run->Run configuration,新建一个Java Application,输入两个参数一个是索引目录,一个是文件存放目录
index.png
                    图:配置运行界面
运行后可以行到分析结果,当然目录中索引的内容不同得到的结果也就会不同。
index.png         图:索引txt文件时输出
根据索引查询因为这里边还没涉及到中文的部分,所以我们查询所有文档中包括"RUNNING"的文档。
程序内容如下:
  1. public class Searcher {
  2.     public static void main(String[] args) throws IllegalArgumentException,
  3.             IOException, ParseException {
  4.         if (args.length != 2) {
  5.             throw new IllegalArgumentException("Usage: java "
  6.                     + Searcher.class.getName() + " <index dir> <query>");
  7.         }
  8.         String indexDir = args[0]; // 1
  9.         String q = args[1]; // 2
  10.         search(indexDir, q);
  11.     }
  12.     public static void search(String indexDir, String q) throws IOException,
  13.             ParseException {
  14.         Directory dir = FSDirectory.open(new File(indexDir)); // 3
  15.         IndexSearcher is = new IndexSearcher(dir); // 3
  16.         QueryParser parser = new QueryParser(Version.LUCENE_30, // 4
  17.                 "contents", // 4
  18.                 new StandardAnalyzer( // 4
  19.                         Version.LUCENE_30)); // 4
  20.         Query query = parser.parse(q); // 4
  21.         long start = System.currentTimeMillis();
  22.         TopDocs hits = is.search(query, 10); // 5
  23.         long end = System.currentTimeMillis();
  24.         System.err.println("Found " + hits.totalHits + // 6
  25.                 " document(s) (in " + (end - start) + // 6
  26.                 " milliseconds) that matched query '" + // 6
  27.                 q + "':"); // 6
  28.         for (ScoreDoc scoreDoc : hits.scoreDocs) {
  29.             Document doc = is.doc(scoreDoc.doc); // 7
  30.             System.out.println(doc.get("fullpath")); // 8
  31.         }
  32.         is.close(); // 9
  33.     }
  34. }
复制代码


同上操作,配置新的Java Application,如下图:
index.png
                  图:配置查询参数
点击运行,可以得到运行结果。
index.png 也就是我们上面索引的文件,当然,随着文件的多少及大小,速度会不同,这里只是一个演示程序,你可以根据你本身的程序自行设置查询条件。
索引过程中的几个核心类IndexWriter
IndexWriter是索引过程的核心组件。用于创建一个新的索引并把文档加到已有的索引中去,也可以向索引中添加、删除和更新被索引文档的信息。
Directory
Directory类描述了Lucene索引的存放位置。
Analyzer
Analyzer是分词器接口,文本文件在被索引之前,需要经过Analyzer处理。常用的中文分词器有庖丁、IKAnalyzer等。
Document
Document对象代表一组域(Field)的集合。其实说白了就是文件,可能是文本文件,word或者pdf等。
Field
Field就是每个文档中包含的不同的域。
lucene构建索引的流程图如下:
index.jpg
                图:lucene构建索引流程
搜索过程中的几个核心类IndexSearcher
IndexSearcher是对前边IndexWriter创建的索引进行搜索。
Term
Term对象是搜索功能的基本单元,跟Field对象非常类似,可以放入我们查询的条件。
Query
Query就是Lucene给我们的查询接口,它有很多的子类,我们可以基于这些进行功能丰富的查询。
TermQuery
TermQuery是Lucene提供的最基本的查询类型。
TopDocs

TopDocs类是一个简单的指针容器,指针一般指向前N个排名的搜索结果,搜索结果即匹配查询条件的文档。 index.png

                    图:lucene查询请求流程

[源码下载]


资料来源:http://www.cnblogs.com/skyme/archive/2012/07/31/2615054.html


欢迎加入about云群371358502、39327136,云计算爱好者群,亦可关注about云腾讯认证空间||关注本站微信

没找到任何评论,期待你打破沉寂

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

推荐上一条 /2 下一条