我对Lucene是新来的。我有两个文档,我希望有一个精确匹配的文档字段称为“关键字”(字段可能在一个文档中出现多次)。
private IndexWriter writer;
public void lucene() throws IOException, ParseException {
// Build the index
StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_42);
Directory index = new RAMDirectory();
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_42,
analyzer);
this.writer = new IndexWriter(index, config);
// Add documents to the index
addDoc("Spring", new String[] { "Java", "JSP",
"Annotation is cool" });
addDoc("Java", new String[] { "Oracle", "Annotation is cool too" });
writer.close();
// Search the index
IndexReader reader = DirectoryReader.open(index);
IndexSearcher searcher = new IndexSearcher(reader);
BooleanQuery qry = new BooleanQuery();
qry.add(new TermQuery(new Term("keyword", "\"Annotation is cool\"")), BooleanClause.Occur.MUST);
System.out.println(qry.toString());
Query q = new QueryParser(Version.LUCENE_42, "title", analyzer).parse(qry.toString());
int hitsPerPage = 10;
TopScoreDocCollector collector = TopScoreDocCollector.create(
hitsPerPage, true);
searcher.search(q, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;
for (int i = 0; i < hits.length; ++i) {
int docId = hits[i].doc;
Document doc = searcher.doc(docId);
System.out.println((i + 1) + ". \t" + doc.get("title"));
}
reader.close();
}
private void addDoc(String title, String[] keywords) throws IOException {
// Create new document
Document doc = new Document();
// Add title
doc.add(new TextField("title", title, Field.Store.YES));
// Add keywords
for (int i = 0; i < keywords.length; i++) {
doc.add(new TextField("keyword", keywords[i], Field.Store.YES));
}
// Add document to index
this.writer.addDocument(doc);
}
问题不在于如何索引字段。字符串字段是将整个输入索引为单个标记的正确方法。问题是你如何搜索。我真的不知道你打算用这种逻辑完成什么,真的。
BooleanQuery qry = new BooleanQuery();
qry.add(new TermQuery(new Term("keyword", "\"Annotation is cool\"")), BooleanClause.Occur.MUST);
//Great! You have a termQuery added to the parent BooleanQuery which should find your keyword just fine!
Query q = new QueryParser(Version.LUCENE_42, "title", analyzer).parse(qry.toString());
//Now all bets are off.
query.tostring()
是一种方便的调试方法,但是认为通过QueryParser运行输出文本查询将重新生成相同的查询是不安全的。标准的查询解析器实际上没有太多的能力将多个单词表示为一个术语。我相信,您所看到的字符串版本将如下所示:
keyword:"Annotation is cool"
它将被解释为短语。一个短语将查找三个连续的术语,Annotation、is和cool,但是按照索引的方式,只有一个术语“Annotation is cool”。
解决办法是永远不要使用像这样的逻辑
Query nuttyQuery = queryParser.parse(perfectlyGoodQuery.toString());
searcher.search(nuttyQuery);
相反,只需使用已经创建的BooleanQuery进行搜索。
searcher.search(perfectlyGoodQuery);