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

来源:互联网 发布:电信上网软件 编辑:程序博客网 时间:2024/04/30 15:13

在上面的篇幅中我们已经了解到了lucene,及lucene到底是做什么的,什么情况下才能够使用lucene,下面我们就结合一个例子来详细说明一下lucene的API,看看lucene是如何工作的。

lucene的下载

其实这个很简单了,直接到baidu或者google上搜索一下,一般情况下第一个就是我们要的链接。下边给出lucene下载的链接:

http://lucene.apache.org/

                图:lucene下载主页面

配置环境

我们下面要做很多的测试,会建立很多的测试工程,如果一个一个手动的添加jar包会非常的麻烦,那么我们就需要配置eclipse环境。

打开eclipse,选择windows->preferences->java->build path->user libraries

将我们上边下载后的lucene中的包全部加载到这个用户变量中。

               图:eclipse中加入的用户变量

建立索引

下面这个程序就是读取指定文件夹下的文件并且将文件生成索引的过程,它有两个参数,一个是要索引的文件路径,一个是索引存放的路径。

我们将文件放到我们硬盘的目录上,然后通过程序建立索引。

索引程序如下:

View Code
 1 public class Indexer { 2  3     public static void main(String[] args) throws Exception { 4         if (args.length != 2) { 5             throw new IllegalArgumentException("Usage: java " 6                     + Indexer.class.getName() + " <index dir> <data dir>"); 7         } 8         String indexDir = args[0]; // 1 9         String dataDir = args[1]; // 210 11         long start = System.currentTimeMillis();12         Indexer indexer = new Indexer(indexDir);13         int numIndexed;14         try {15             numIndexed = indexer.index(dataDir, new TextFilesFilter());16         } finally {17             indexer.close();18         }19         long end = System.currentTimeMillis();20 21         System.out.println("Indexing " + numIndexed + " files took "22                 + (end - start) + " milliseconds");23     }24 25     private IndexWriter writer;26 27     public Indexer(String indexDir) throws IOException {28         Directory dir = FSDirectory.open(new File(indexDir));29         writer = new IndexWriter(dir, // 330                 new StandardAnalyzer( // 331                         Version.LUCENE_30),// 332                 true, // 333                 IndexWriter.MaxFieldLength.UNLIMITED); // 334     }35 36     public void close() throws IOException {37         writer.close(); // 438     }39 40     public int index(String dataDir, FileFilter filter) throws Exception {41 42         File[] files = new File(dataDir).listFiles();43 44         for (File f : files) {45             if (!f.isDirectory() && !f.isHidden() && f.exists() && f.canRead()46                     && (filter == null || filter.accept(f))) {47                 indexFile(f);48             }49         }50 51         return writer.numDocs(); // 552     }53 54     private static class TextFilesFilter implements FileFilter {55         public boolean accept(File path) {56             return path.getName().toLowerCase() // 657                     .endsWith(".txt"); // 658         }59     }60 61     protected Document getDocument(File f) throws Exception {62         Document doc = new Document();63         doc.add(new Field("contents", new FileReader(f))); // 764         doc.add(new Field("filename", f.getName(), // 865                 Field.Store.YES, Field.Index.NOT_ANALYZED));// 866         doc.add(new Field("fullpath", f.getCanonicalPath(), // 967                 Field.Store.YES, Field.Index.NOT_ANALYZED));// 968         return doc;69     }70 71     private void indexFile(File f) throws Exception {72         System.out.println("Indexing " + f.getCanonicalPath());73         Document doc = getDocument(f);74         writer.addDocument(doc); // 1075     }76 77 }

然后在工程上点击右键Run->Run configuration,新建一个Java Application,输入两个参数一个是索引目录,一个是文件存放目录

                    图:配置运行界面

运行后可以行到分析结果,当然目录中索引的内容不同得到的结果也就会不同。

        图:索引txt文件时输出

根据索引查询

因为这里边还没涉及到中文的部分,所以我们查询所有文档中包括"RUNNING"的文档。

程序内容如下:

View Code
 1 public class Searcher { 2  3     public static void main(String[] args) throws IllegalArgumentException, 4             IOException, ParseException { 5         if (args.length != 2) { 6             throw new IllegalArgumentException("Usage: java " 7                     + Searcher.class.getName() + " <index dir> <query>"); 8         } 9 10         String indexDir = args[0]; // 111         String q = args[1]; // 212 13         search(indexDir, q);14     }15 16     public static void search(String indexDir, String q) throws IOException,17             ParseException {18 19         Directory dir = FSDirectory.open(new File(indexDir)); // 320         IndexSearcher is = new IndexSearcher(dir); // 321 22         QueryParser parser = new QueryParser(Version.LUCENE_30, // 423                 "contents", // 424                 new StandardAnalyzer( // 425                         Version.LUCENE_30)); // 426         Query query = parser.parse(q); // 427         long start = System.currentTimeMillis();28         TopDocs hits = is.search(query, 10); // 529         long end = System.currentTimeMillis();30 31         System.err.println("Found " + hits.totalHits + // 632                 " document(s) (in " + (end - start) + // 633                 " milliseconds) that matched query '" + // 634                 q + "':"); // 635 36         for (ScoreDoc scoreDoc : hits.scoreDocs) {37             Document doc = is.doc(scoreDoc.doc); // 738             System.out.println(doc.get("fullpath")); // 839         }40 41         is.close(); // 942     }43 }

同上操作,配置新的Java Application,如下图:

                  图:配置查询参数

点击运行,可以得到运行结果。

也就是我们上面索引的文件,当然,随着文件的多少及大小,速度会不同,这里只是一个演示程序,你可以根据你本身的程序自行设置查询条件。

索引过程中的几个核心类

IndexWriter

IndexWriter是索引过程的核心组件。用于创建一个新的索引并把文档加到已有的索引中去,也可以向索引中添加、删除和更新被索引文档的信息。

Directory

Directory类描述了Lucene索引的存放位置。

Analyzer

Analyzer是分词器接口,文本文件在被索引之前,需要经过Analyzer处理。常用的中文分词器有庖丁、IKAnalyzer等。

Document

Document对象代表一组域(Field)的集合。其实说白了就是文件,可能是文本文件,word或者pdf等。

Field

Field就是每个文档中包含的不同的域。

lucene构建索引的流程图如下:

                图:lucene构建索引流程

搜索过程中的几个核心类

IndexSearcher

IndexSearcher是对前边IndexWriter创建的索引进行搜索。

Term

Term对象是搜索功能的基本单元,跟Field对象非常类似,可以放入我们查询的条件。

Query

Query就是Lucene给我们的查询接口,它有很多的子类,我们可以基于这些进行功能丰富的查询。

TermQuery

TermQuery是Lucene提供的最基本的查询类型。

TopDocs

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

                    图:lucene查询请求流程

 

[源码下载]

原创粉丝点击