【问题标题】:Finding strict prefixes in lucene在 lucene 中查找严格的前缀
【发布时间】:2017-11-12 06:48:25
【问题描述】:

我正在尝试使用 Lucene 实现自动完成功能。例如,如果用户键入“Lucene”,则返回的结果可能是“Lucene in Action”和“Lucene for Dummies”。

我遇到的问题是该字段应该以搜索的文本开头,它不应该在中间的某个地方;搜索“Lucene”不应返回“Enterprise Lucene”。到目前为止,这是我的代码,不排除上述内容:

    StandardAnalyzer analyzer = new StandardAnalyzer();
    Directory index = new RAMDirectory();
    IndexWriterConfig config = new IndexWriterConfig(analyzer);

    IndexWriter indexWriter = new IndexWriter(index, config);
    addDocument(indexWriter, "Luceneinaction");
    addDocument(indexWriter, "LuceneforDummies");
    addDocument(indexWriter, "WhyisLucenesohard");
    addDocument(indexWriter, "Managing Gigabytes");
    addDocument(indexWriter, "The Art of Computer Science");
    indexWriter.close();

    Query query = new PrefixQuery(new Term("title", "lucene"));

    IndexReader reader = DirectoryReader.open(index);
    IndexSearcher searcher = new IndexSearcher(reader);
    TopDocs docs = searcher.search(query, 10);
    for (ScoreDoc scoreDoc : docs.scoreDocs) {
        System.out.println(searcher.doc(scoreDoc.doc).get("title"));
    }

有没有简单的方法来解决这个问题? PrefixQuery 似乎与 StringField 不兼容,我找不到不会在空格上拆分的分词器。

【问题讨论】:

    标签: autocomplete lucene


    【解决方案1】:

    当您在 solr 中索引文本字段时,它将被标记化。例如,空格标记器将文档拆分为气味中的每个空格。所以你可能无法根据字符串位置进行搜索。

    对于您的用例,您应该将此字段复制/存储为字符串类型(使用关键字 toeknizer)而不是文本。然后你会发现 solr 将完整的香味存储为单个字符串,允许你执行正则表达式模式搜索。

    【讨论】:

      【解决方案2】:

      如果您想使用一个字段进行全文搜索,您应该始终使用 Textfield,因为这将被分析(基于您给定的分析器)。 参见 javadoc:Field

      了解需要使用哪种类型的字段非常重要。

      对于您的用例,如果您在 TextField 中搜索,则不必使用 PrefixQuery。

      【讨论】:

        猜你喜欢
        • 2011-02-22
        • 1970-01-01
        • 2023-03-27
        • 1970-01-01
        • 2023-03-31
        • 2021-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多