检索领域的明星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());
}
}