【问题标题】:How to search across all the fields?如何搜索所有领域?
【发布时间】:2013-02-16 16:25:03
【问题描述】:

在 Lucene 中,我们可以使用 TermQuery 来搜索带有字段的文本。我想知道如何在一堆字段或所有可搜索字段中搜索关键字?

【问题讨论】:

    标签: lucene.net lucene


    【解决方案1】:

    另一种方法是使用MultiFieldQueryParser,它不需要索引您已经拥有的任何内容,也不需要组合不同的查询。

    您可以提供要搜索的字段列表和查询,仅此而已。

    MultiFieldQueryParser queryParser = new MultiFieldQueryParser(
                    Version.LUCENE_41, 
                    new String[]{"title", "content", "description"},
                    new StandardAnalyzer(Version.LUCENE_41));
    
    Query query = queryParser.parse("here goes your query");
    

    这就是我使用 Java 编写的原始 lucene 库的方式。我不确定 MultiFieldQueryParser 是否也可以在 lucene.net 中使用。

    【讨论】:

    • MultiFieldQueryParser 是一种优雅的方法.. :)
    • 谢谢,你的回答也不错;)+1
    • 至少在 4.8(本评论的最新版本)中,在 Lucene.Net - 它位于 Classic 文件夹下的 Lucene.Net.QueryParser 项目中。
    【解决方案2】:

    两种方法

    1) 索引时间方法:使用 catch-all 字段。这只不过是附加所有字段中的所有文本(输入文档中的总文本)并将产生的巨大文本放在单个字段中。您必须在索引时添加一个附加字段以充当一个包罗万象的字段。

    2) 搜索时方法:使用BooleanQuery 组合多个查询,例如 TermQuery 实例。可以形成这些多个查询以覆盖所有目标字段。

    Example文末查看。

    如果您在运行时知道目标字段列表,请使用方法 2。否则,您必须使用第一种方法。

    【讨论】:

    • 感谢大图的解释。第一种方法是我在同一索引中存储不同类型的产品时使用的方法,例如打印机与监视器,其中每个文档存在不同的字段,但我想使用带有简单搜索字符串的“全文”搜索并带回所有匹配的产品。
    【解决方案3】:

    另一种使用“MultifieldQueryParser”搜索所有字段的简单方法是在查询中使用 IndexReader.FieldOption.ALL

    这是 c# 中的示例。

    Directory directory = FSDirectory.Open(new DirectoryInfo(HostingEnvironment.MapPath(VirtualIndexPath)));
    
        //get analyzer
        Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_29);
    
        //get index reader and searcher
        IndexReader indexReader__1 = IndexReader.Open(directory, true);
        Searcher indexSearch = new IndexSearcher(indexReader__1);
    
        //add all possible fileds in multifieldqueryparser using indexreader getFieldNames method
        var queryParser = new MultiFieldQueryParser(Version.LUCENE_29, indexReader__1.GetFieldNames(IndexReader.FieldOption.ALL).ToArray(), analyzer);
        var query = queryParser.Parse(Criteria);
        TopDocs resultDocs = null;
    
        //perform search
        resultDocs = indexSearch.Search(query, indexReader__1.MaxDoc());
        var hits = resultDocs.scoreDocs;
    

    click here 查看我以前在 vb.net 中对同一问题的回答

    【讨论】:

    • 我看不出在这里使用鸭子打字的意义(即dynamic关键字)。也许您想对var 使用类型干预?
    猜你喜欢
    • 1970-01-01
    • 2013-07-06
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多