【问题标题】:Lucene: prefix query not working with WhitespaceAnalyzerLucene:前缀查询不适用于 WhitespaceAnalyzer
【发布时间】:2014-07-21 17:54:46
【问题描述】:

我正在对 Lucene 的各种 Query 对象进行一些试验,并试图了解为什么在使用 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 在索引期间存储值的方式上没有发现任何差异。有人可以澄清发生了什么问题吗?

【问题讨论】:

    标签: java api lucene


    【解决方案1】:

    StandardAnalyzer 在被索引时将文本小写。 WhitespaceAnalyzer 没有。索引中的术语,WhitespaceAnalyzer 是“威尼斯”。

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

    【讨论】:

    • 好的,现在我明白了。将“setLowercaseExpandedTerms”值设置为 false 并将前缀替换为“Ven*”即可。非常感谢!
    • 在我看来,QueryParser 默认小写这些术语似乎是不对的。感谢@femtoRgon 的提示
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 2018-01-12
    • 2020-11-26
    • 2013-07-12
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    相关资源
    最近更新 更多