2011-05-06 30 views
4

我正在玩Lucene.net试图获得如何在我的应用程序中实现它的句柄。当在搜索中使用多个单词时,如何在Lucene.net中执行AND搜索?

我有以下代码

  ..... 
      // 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")); 

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

我要做的最终结果是,如果有人搜索“马修安德森”,我不希望它提出引用“马修多恩”的文档,因为这与任何形式都不相关,形状或形成。

回答

6

答:如果您需要的所有单词是一个文档中,但不要求的话是连续和顺序指定:查询

+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 
+1

确定这是有道理的。因为你给了我连续匹配的例子,所以将其标记为答案。我想我需要编写一个字符串分析器来将用户输入转换为正确的lucene查询字符串,这应该很有趣。 – KallDrexx 2011-05-07 00:39:27

+0

很久没有问了。如果我想要返回数据,如果有foudn这个词叫红色但是大不存在或者大,但是红色不存在,那么查询应该如何。 – Thomas 2014-07-14 09:13:19

+0

@Thomas查询语法支持用圆括号分组子句。所以,这应该工作:'(+ red-big)(+ big -red)' – 2014-07-14 22:52:18

2

当您的查询是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);