当搜索中使用多个单词时,如何在 Lucene.net 中执行 AND 搜索



我正在使用 Lucene.net 来尝试了解如何在我的应用程序中实现它。

我有以下代码

            .....
            // Add 2 documents
            var doc1 = new Document();
            var doc2 = new Document();
            doc1.Add(new Field("id", "doc1", Field.Store.YES, Field.Index.ANALYZED));
            doc1.Add(new Field("content", "This is my first document", Field.Store.YES, Field.Index.ANALYZED));
            doc2.Add(new Field("id", "doc2", Field.Store.YES, Field.Index.ANALYZED));
            doc2.Add(new Field("content", "The big red fox jumped", Field.Store.YES, Field.Index.ANALYZED));
            writer.AddDocument(doc1);
            writer.AddDocument(doc2);
            writer.Optimize();
            writer.Close();
            // Search for doc2
            var parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "content", new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29));
            var query = parser.Parse("big abcdefg test1234");
            var searcher = new IndexSearcher(indexDirectory, true);
            var hits = searcher.Search(query);
            Assert.AreEqual(1, hits.Length());
            var document = hits.Doc(0);
            Assert.AreEqual("doc2", document.Get("id"));
            Assert.AreEqual("The big red fox jumped", document.Get("content"));

这个测试通过了,这让我有点沮丧。 我认为这意味着 Lucene.Net 使用 OR 进行术语之间的搜索,而不是 AND,但我找不到有关如何实际执行 AND 搜索的任何信息。

我要做的最终结果是,如果有人搜索"马修·安德森",我不希望它显示引用"马修·多伊"的文档,因为这在任何方面、形状或形式上都不相关。

A.如果要求所有单词都位于文档中,但不要求单词连续且按您指定的顺序排列:查询

+big +red

比赛

* the big red fox jumped
* the red big fox jumped
* the big fast red fox jumped

但不匹配

* the small red fox jumped

二.如果要匹配短语(即需要所有单词;单词必须连续且按指定的顺序):查询

+"big red"

比赛

* the big red fox jumped

但不匹配

* the red big fox jumped
* the big fast red fox jumped
* the small red fox jumped

var query = parser.Parse("+big +abcdefg +test1234");查询时会得到什么 这应该会导致解析器要求匹配文档中存在所有术语。另一种可能性是以编程方式构造查询。

BooleanQuery query = new BooleanQuery();
query.add(new BooleanClause(new TermQuery(new Term("field", "big"))), Occur.MUST);
query.add(new BooleanClause(new TermQuery(new Term("field", "abcdefg"))), Occur.MUST);
query.add(new BooleanClause(new TermQuery(new Term("field", "test1234"))), Occur.MUST);

最新更新