Luence5分鐘快速入門樣本

來源:互聯網
上載者:User

使用Lucene,可以非常方便給我們的應用增加上全文索引的功能,使用上也非常簡單,只需要5分鐘我們就可以學會如何使用它。

1、先從官方下載,現在的最新版本是4.4.0,下面的範例程式碼也是基於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_40);    // 1. create the index    Directory index = new RAMDirectory();    IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, 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_40, "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);  }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.