NOT运算符在查询lucene中不起作用

时间:2013-07-31 11:44:58

标签: lucene operator-keyword not-operator

我使用lucene 3.0.3.0版本,但我搜索的某些表达式无法正常工作。例如,如果我在“模型”字段上搜索“!Fiesta OR Astra”,则仅返回“vauxhallAstra”并且不返回“fordFocus”。我的代码如下:

var fordFiesta = new Document();

        fordFiesta.Add(new Field("Id", "1", Field.Store.YES, Field.Index.NOT_ANALYZED));

        fordFiesta.Add(new Field("Make", "Ford", Field.Store.YES, Field.Index.ANALYZED));

        fordFiesta.Add(new Field("Model", "Fiesta", Field.Store.YES, Field.Index.ANALYZED));



        var fordFocus = new Document();

        fordFocus.Add(new Field("Id", "2", Field.Store.YES, Field.Index.NOT_ANALYZED));

        fordFocus.Add(new Field("Make", "Ford", Field.Store.YES, Field.Index.ANALYZED));

        fordFocus.Add(new Field("Model", "Focus", Field.Store.YES, Field.Index.ANALYZED));



        var vauxhallAstra = new Document();

        vauxhallAstra.Add(new Field("Id", "3", Field.Store.YES, Field.Index.NOT_ANALYZED));

        vauxhallAstra.Add(new Field("Make", "Vauxhall", Field.Store.YES, Field.Index.ANALYZED));

        vauxhallAstra.Add(new Field("Model", "Astra", Field.Store.YES, Field.Index.ANALYZED));







        Directory directory = FSDirectory.Open(new DirectoryInfo(Environment.CurrentDirectory + "\\LuceneIndex"));

        Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);





        var writer = new IndexWriter(directory, analyzer, true, IndexWriter.MaxFieldLength.LIMITED);

        writer.AddDocument(fordFiesta);

        writer.AddDocument(fordFocus);

        writer.AddDocument(vauxhallAstra);


        writer.Optimize();                       

        writer.Close();

        IndexReader indexReader = IndexReader.Open(directory, true);
        Searcher indexSearch = new IndexSearcher(indexReader);

        var queryParser = new QueryParser(Version.LUCENE_30, "Model", analyzer);
        var query = queryParser.Parse("!Fiesta OR Astra");

        Console.WriteLine("Searching for: " + query.ToString());
        TopDocs resultDocs = indexSearch.Search(query, 200);            
        Console.WriteLine("Results Found: " + resultDocs.MaxScore);

        var hits = resultDocs.ScoreDocs;
        foreach (var hit in hits)
        {
            var documentFromSearcher = indexSearch.Doc(hit.Doc);
            Console.WriteLine(documentFromSearcher.Get("Make") + " " + documentFromSearcher.Get("Model"));
        }

        indexSearch.Close();
        directory.Close();

        Console.ReadKey();

1 个答案:

答案 0 :(得分:8)

!Fiesta OR Astra并不代表您认为的含义。 !Fiesta部分并不意味着,“除了嘉年华之外的所有东西”,正如您所料,但更像是“禁止嘉年华”。 Lucene查询中的NOT术语仅过滤掉结果,但找不到任何内容。

您定义的实际获取结果的唯一查询是Astra。因此,将找到包含Astra的所有内容,然后将过滤掉Fiesta的任何内容。

为了执行我相信您期望的查询,您需要以下内容:

Astra OR (*:* !Fiesta)

*:*作为MatchAllDocsQuery。由于您确实需要匹配所有文档来执行此类查询,因此可能会表现不佳。


混淆这样的“布尔”逻辑的解释是我真的不喜欢Lucene的AND / OR / NOT语法的原因。 +/-更清晰,更强大,并且不会引入像这样的古怪的问题。

This excellent article on the topic澄清了为什么你应该考虑MUST / MUST_NOT / SHOULD,而不是传统的布尔逻辑。