1 Lucene简介
Apache Lucene 是一个高性能的,功能齐全的文本搜索引擎开发包。下面一张图展示了 Lucene 与应用之间的关系,可以看出 Lucene 用在什么地方,怎么用。
2 Lucene官网上的示例
下面一段代码是 Lucene 5.4.0 core 的 API。这是关于如何使用 Lucene 来索引和搜索的一个简单例子(例子中使用了 JUnit 来检查结果是否符合预期):
Analyzer analyzer = new StandardAnalyzer();
// Store the index in memory:
Directory directory = new RAMDirectory();
// To store an index on disk, use this instead:
//Directory directory = FSDirectory.open("/tmp/testindex");
IndexWriterConfig config = new IndexWriterConfig(analyzer);
IndexWriter iwriter = new IndexWriter(directory, config);
Document doc = new Document();
String text = "This is the text to be indexed.";
doc.add(new Field("fieldname", text, TextField.TYPE_STORED));
iwriter.addDocument(doc);
iwriter.close();
// Now search the index:
DirectoryReader ireader = DirectoryReader.open(directory);
IndexSearcher isearcher = new IndexSearcher(ireader);
// Parse a simple query that searches for "text":
QueryParser parser = new QueryParser("fieldname", analyzer);
Query query = parser.parse("text");
ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
assertEquals(1, hits.length);
// Iterate through the results:
for (int i = 0; i < hits.length; i++) {
Document hitDoc = isearcher.doc(hits[i].doc);
assertEquals("This is the text to be indexed.", hitDoc.get("fieldname"));
}
ireader.close();
directory.close();
Lucene官网给出了如上一段代码,这段代码首先使用Lucene创建索引,然后再进行关键字查询。第一次看到难免会看的头晕目眩,便于理解这里我用思维导图画了一张步骤图,用来记录lucene创建索引或关键字查询的过程。
3 一张图教你如何使用Lucene
上面这张图片列出了使用lucene创建索引和关键字查询的主要步骤。对比下面中文注释的代码便于理解整个代码运行的过程。
// ============ 创建索引 =============
// 一、创建词法分析器
Analyzer analyzer = new StandardAnalyzer();
// 二、创建索引存储目录
// Store the index in memory:
Directory directory = new RAMDirectory();
// To store an index on disk, use this instead:
//Directory directory = FSDirectory.open("/tmp/testindex");
// 三、创建索引写入器
IndexWriterConfig config = new IndexWriterConfig(analyzer);
IndexWriter iwriter = new IndexWriter(directory, config);
// 四、将内容存储到索引
Document doc = new Document();
String text = "This is the text to be indexed.";
doc.add(new Field("fieldname", text, TextField.TYPE_STORED));
iwriter.addDocument(doc);
iwriter.close();
// ============ 关键字查询 =============
// 一、创建索引存储目录读取器
// Now search the index:
DirectoryReader ireader = DirectoryReader.open(directory);
// 二、创建索引搜索器
IndexSearcher isearcher = new IndexSearcher(ireader);
// 三、解析查询
// Parse a simple query that searches for "text":
QueryParser parser = new QueryParser("fieldname", analyzer);
Query query = parser.parse("text");
// 四、获取结果
ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
assertEquals(1, hits.length);
// Iterate through the results:
for (int i = 0; i < hits.length; i++) {
Document hitDoc = isearcher.doc(hits[i].doc);
assertEquals("This is the text to be indexed.", hitDoc.get("fieldname"));
}
ireader.close();
directory.close();