簡體   English   中英

當在搜索中使用多個單詞時,如何在Lucene.net中執行AND搜索?

[英]How do I perform an AND search in Lucene.net when multiple words are used in a search?

我正在和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搜索的信息。

我想要的最終結果是,如果有人搜索“Matthew Anderson”,我不希望它提出涉及“Matthew Doe”的文件,因為這與任何方式,形狀或形式無關。

答:如果您要求所有單詞都在文檔中,但不要求單詞是連續的並且按照您指定的順序:查詢

+big +red

火柴

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

但不匹配

* the small red fox jumped

B.如果你想匹配一個短語(即所有需要的單詞;單詞必須是連續的並且按照指定的順序)而不是:查詢

+"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");時,你會得到什么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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM