为什么我无法在Lucene 4.0的搜索结果中获得最近由IndexWriter添加的文档?

时间:2013-03-04 08:00:56

标签: lucene

如标题所说,我遇到了一个疑惑问题。 我为我的测试程序构建了一个索引,然后使用IndexWriter将文档添加到索引中。代码是:

IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_CURRENT, analyzer);
IndexWriter iwriter = new IndexWriter(directory, config);
Document doc1 = new Document();
doc1.add(new Field("name", "张三", Field.Store.YES, Field.Index.ANALYZED));
doc1.add(new IntField("year", 2013, Field.Store.YES));
doc1.add(new TextField("content", "123456789", Field.Store.YES));
iwriter.addDocument(doc1);
iwriter.commit();
iwriter.close();

当我尝试搜索此索引时,我无法获得此文档。我真的得到了正确的结果数,它比以前多了一个。但是当我尝试打印doc.get(' name')时,输出错误。

搜索部分中的代码是:

DirectoryReader ireader = DirectoryReader.open(directory);
System.out.println(ireader.numDeletedDocs());
IndexSearcher isearcher = new IndexSearcher(ireader);
// Parse a simple query that searches for "text":
QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, "name", analyzer);
Query query = parser.parse("张");

ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;
System.out.println(hits.length);

在结果中,有一个"名称:李四"。 我确信在索引和搜索过程中我使用了StandardAnalyzer。而StandardAnalyzer会将一个汉字作为单个标记。为什么当我搜索"张"时,我会得到"李四"?添加文档时有什么问题吗?或者docid是不匹配的?

1 个答案:

答案 0 :(得分:0)

添加文档后你是否(重新)打开了索引? Lucene搜索仅返回索引打开搜索时存在的文档。

[编辑...]

使用 IndexReader.Open() IndexReader.doOpenIfChanged()再次打开索引。 doOpenIfChanged()的优点是,如果您仍然可以使用旧的IndexReader实例(因为索引未更改),则返回null。

(如果我没记错的话, DirectoryReader.Open()只打开索引目录,因此如果你只是调用<,则更高级别的Lucene代码没有意识到索引已经改变了强> DirectoryReader.Open 即可。)

相关问题