檢索領域的明星lucene,被公認為高效的檢索算法,其被廣泛應用在其他領域中,包括微軟的郵箱檢索等。其的核心包有7個,名稱和功能介紹如下:
序号 | 包名 | 功能簡介 |
1 | index | 建構索引 |
2 | analyze | 文本分析接口 |
3 | document | 文檔邏輯接口 |
4 | Search | 文檔檢索接口 |
5 | Query | 建構查詢接口 |
6 | Store | 存儲處理接口 |
為了使用Lucene,一個應用程式需要包含以下步驟: 1)建立增加Field的文檔; 2)建立IndexWriter增加文檔資訊; 3)通過QueryParser建立查詢實體; 4)通過IndexSearcher查詢文檔;. 使用中的核心關鍵類是IndexWriter和IndexReader,這兩個類分别負責索引的建立和文檔的檢索.其執行個體如下,Lucene版本号是6.1.2: public static void main(String[] args) {
try {
Analyzer analyzer=new StandardAnalyzer();
//Directory directory=new RAMDirectory();
Directory directory=FSDirectory.open(Paths.get("D:\\lucene"));
IndexWriterConfig config=new IndexWriterConfig(analyzer);
IndexWriter writer=new IndexWriter(directory,config);
Document document=new Document();
String text = "This is the text to be indexed.";
document.add(new Field("fieldname", text, TextField.TYPE_STORED));
writer.addDocument(document);
writer.close();
DirectoryReader reader=DirectoryReader.open(directory);
IndexSearcher searcher=new IndexSearcher(reader);
QueryParser parser=new QueryParser("fieldname", analyzer);
Query query=parser.parse("text");
ScoreDoc[] hits = searcher.search(query, 100).scoreDocs;
// Iterate through the results:
for (int i = 0; i < hits.length; i++) {
Document hitDoc = searcher.doc(hits[i].doc);
System.out.print(hitDoc.toString());
}
reader.close();
directory.close();
} catch (Exception e) {
// TODO: handle exception
System.out.print(e.getStackTrace());
}
}