Luence4 五分钟快速入门示例

KelliEchols 8年前

来自: http://blog.csdn.net/fenglibing/article/details/9713681


使用Lucene,可以非常方便给我们的应用增加上全文索引的功能,使用上也非常简单,只需要5分钟我们就可以学会如何使用它。

1、先从官方下载, 下面的示例代码也是基于4.4的;

2、建立一个JAVA工程,将这些个jar从Lucene的目录中找出来:lucene-analyzers-common-4.4.0.jar、lucene-core-4.4.0.jar、lucene-queries-4.4.0.jar、lucene-queryparser-4.4.0.jar,并加入到工程的classpath中;

3、示例JAVA代码,为了简单好理解,示例是以将内存中加入一些字符串,并通过查询结果,再将结果显示出来。

1)、建立内容索引

//创建一个分析器,这里使用的是标准分析器,适用于大多数场景,并且在StandardAnalyzer中包括了部分中文分析处理功能,虽然其本身也有一个中文分析器ChineseAnalyzer,  //不过ChineseAnalyzer将会在5.0的版本中被去掉,使用StandardAnalyzer即可。  //另外在analyzers-common中,包括了针对很多种不同语言的分析器,其中包括中文分析器  Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_44);    //Directory是用于索引文件的存储的抽象类,其子类有将索引文件写到文件的,也有直接放到内存中的,这里的RAMDirectory就是放在内存中索引  //优点是速度快,缺少是不适合于大量数据的索引。这里的数据比较少,所以使用RAMDirctory非常适合。  //具体的可以查看Directory, RAMDirectory,FSDirectory等API说明,这里要强调一下的是FSDirectory是一个文件索引存储的抽象类,下面还有三个子类:MMapDirectory, NIOFSDirectory, SimpleFSDirectory,根据不同的操作系统及使用场景进行不同的选择了。  Directory index = new RAMDirectory();    //IndexWriterConfig包括了所有创建IndexWriter的配置,一旦IndexWriter创建完成后,此时再去修改IndexWriterConfig是不会影响到IndexWriter实例的,此时如果想获取正确的IndexWirter的配置,最好是通过IndexWirter.getConfig()方法了,另外IndexWriterConfig本身也是一个final类。  IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_44, analyzer);    //顾名思义,IndexWriter是用于维护及增加索引的  IndexWriter w = new IndexWriter(index, config);    addDoc(w, "Lucene in Action", "193398817");  addDoc(w, "Lucene for Dummies", "55320055Z");  addDoc(w, "Managing Gigabytes", "55063554A");  addDoc(w, "The Art of Computer Science", "9900333X");  w.close();
以下是addDoc方法的代码,功能是将内容加入到索引中
private static void addDoc(IndexWriter w, String title, String isbn) throws IOException {    Document doc = new Document();    doc.add(new TextField("title", title, Field.Store.YES));    doc.add(new StringField("isbn", isbn, Field.Store.YES));    w.addDocument(doc);  }

这里我们需要注意一下,增加标题索引使用的是TextField,增加isbn索引使用的是StringField,这两个都是IndexableField的子类,TextField表示是会被拆分并且被索引的字段,而StringField只会一个整体被索引,而不会进行拆分索引。

2)、查询通过读取命令行参数,并将其传给luence的QueryParset,再通过Query执行查询

String querystr = args.length > 0 ? args[0] : "lucene";  //通过查询解析器QueryParser创建一个查询Query.  //QueryParser是JavaCC(http://javacc.java.net)编译的其中最重要的方法就是QueryParserBase.parse(String),  //特别需要注意的是QueryParser不是线程安全的  Query q = new QueryParser(Version.LUCENE_44, "title", analyzer).parse(querystr);
 

3)、执行查询根据index创建IndexSearcher,然后TopScoreDocCollector就会返回查询的结果

//这个表示每次最多显示的结果数  int hitsPerPage = 10;  //创建索引读取器  IndexReader reader = IndexReader.open(index);  //创建索引查询器  IndexSearcher searcher = new IndexSearcher(reader);  //以TopDocs的方式返回最多hitsPerPage的查询结果  TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true);  //执行查询  searcher.search(q, collector);  ScoreDoc[] hits = collector.topDocs().scoreDocs;
 

4)、显示索引查询结果

System.out.println("Found " + hits.length + " hits.");  for(int i=0;i<hits.length;++i) {      int docId = hits[i].doc;      Document d = searcher.doc(docId);      System.out.println((i + 1) + ". " + d.get("isbn") + "\t" + d.get("title"));  }
以下是完全整的代码:
import org.apache.lucene.analysis.standard.StandardAnalyzer;  import org.apache.lucene.document.Document;  import org.apache.lucene.document.Field;  import org.apache.lucene.document.StringField;  import org.apache.lucene.document.TextField;  import org.apache.lucene.index.DirectoryReader;  import org.apache.lucene.index.IndexReader;  import org.apache.lucene.index.IndexWriter;  import org.apache.lucene.index.IndexWriterConfig;  import org.apache.lucene.queryparser.classic.ParseException;  import org.apache.lucene.queryparser.classic.QueryParser;  import org.apache.lucene.search.IndexSearcher;  import org.apache.lucene.search.Query;  import org.apache.lucene.search.ScoreDoc;  import org.apache.lucene.search.TopScoreDocCollector;  import org.apache.lucene.store.Directory;  import org.apache.lucene.store.RAMDirectory;  import org.apache.lucene.util.Version;    import java.io.IOException;    public class HelloLucene {    public static void main(String[] args) throws IOException, ParseException {      // 0. Specify the analyzer for tokenizing text.      //    The same analyzer should be used for indexing and searching      StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_44);        // 1. create the index      Directory index = new RAMDirectory();        IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_44, analyzer);        IndexWriter w = new IndexWriter(index, config);      addDoc(w, "Lucene in Action", "193398817");      addDoc(w, "Lucene for Dummies", "55320055Z");      addDoc(w, "Managing Gigabytes", "55063554A");      addDoc(w, "The Art of Computer Science", "9900333X");      w.close();        // 2. query      String querystr = args.length > 0 ? args[0] : "lucene";        // the "title" arg specifies the default field to use      // when no field is explicitly specified in the query.      Query q = new QueryParser(Version.LUCENE_44, "title", analyzer).parse(querystr);        // 3. search      int hitsPerPage = 10;      IndexReader reader = DirectoryReader.open(index);      IndexSearcher searcher = new IndexSearcher(reader);      TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true);      searcher.search(q, collector);      ScoreDoc[] hits = collector.topDocs().scoreDocs;            // 4. display results      System.out.println("Found " + hits.length + " hits.");      for(int i=0;i<hits.length;++i) {        int docId = hits[i].doc;        Document d = searcher.doc(docId);        System.out.println((i + 1) + ". " + d.get("isbn") + "\t" + d.get("title"));      }        // reader can only be closed when there      // is no need to access the documents any more.      reader.close();    }      private static void addDoc(IndexWriter w, String title, String isbn) throws IOException {      Document doc = new Document();      doc.add(new TextField("title", title, Field.Store.YES));        // use a string field for isbn because we don't want it tokenized      doc.add(new StringField("isbn", isbn, Field.Store.YES));      w.addDocument(doc);    }  }