gpt4 book ai didi

java - Lucene:前缀查询不适用于 WhitespaceAnalyzer

转载 作者:行者123 更新时间:2023-11-29 05:20:45 25 4
gpt4 key购买 nike

我正在对 Lucene 的各种查询对象进行一些试验,我试图理解为什么在使用 WhitespaceAnaylzer 进行索引时前缀查询与任何文档都不匹配。考虑以下测试代码:

protected String[] ids = { "1", "2" };
protected String[] unindexed = { "Netherlands", "Italy" };
protected String[] unstored = { "Amsterdam has lots of bridges",
"Venice has lots of canals" };
protected String[] text = { "Amsterdam", "Venice" };

@Test
public void testWhitespaceAnalyzerPrefixQuery() throws IOException, ParseException {
File indexes = new File(
"C:/LuceneInActionTutorial/indexes");

FSDirectory dir = FSDirectory.open(indexes);

IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_9,
new LimitTokenCountAnalyzer(new WhitespaceAnalyzer(
Version.LUCENE_4_9), Integer.MAX_VALUE));
IndexWriter writer = new IndexWriter(dir, config);

for (int i = 0; i < ids.length; i++) {
Document doc = new Document();
doc.add(new StringField("id", ids[i], Store.NO));
doc.add(new StoredField("country", unindexed[i]));
doc.add(new TextField("contents", unstored[i], Store.NO));
doc.add(new Field("city", text[i], TextField.TYPE_STORED));
writer.addDocument(doc);
}
writer.close();

DirectoryReader dr = DirectoryReader.open(dir);
IndexSearcher is = new IndexSearcher(dr);
QueryParser queryParser = new QueryParser(Version.LUCENE_4_9,
"contents", new WhitespaceAnalyzer(Version.LUCENE_4_9));
queryParser.setLowercaseExpandedTerms(true);
Query q = queryParser.parse("Ven*");
assertTrue(q.getClass().getSimpleName().contains("PrefixQuery"));
TopDocs hits = is.search(q, 10);
assertEquals(1, hits.totalHits);
}

如果我将 WhitespaceAnaylzer 替换为 StandardAnalyzer,则测试会通过。我使用 Luke 来检查索引内容,但没有发现 Lucene 在索引期间存储值的方式有任何差异。任何人都可以澄清发生了什么问题吗?

最佳答案

StandardAnalyzer 在索引时将文本小写。 WhitespaceAnalyzer 没有。索引中使用 WhitespaceAnalyzer 的术语是“Venice”。

虽然查询解析器会将您的查询小写,因为您已经设置了 setLowercaseExpandedTerms(true)(这也是默认设置,要禁用它,您需要将其显式设置为 false)。所以您的查询是“ven*”,与“Venice”不匹配。

关于java - Lucene:前缀查询不适用于 WhitespaceAnalyzer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24871572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com