Luence4 五分鐘快速入門示例
來自: 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();</pre>以下是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); } }