我不知道如何使词组查询正常工作。它返回精确的数学表达式,但是slop选项似乎没有什么不同。
这是我的代码:
static void Main(string[] args)
{
using (Directory directory = new RAMDirectory())
{
Analyzer analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);
using (IndexWriter writer = new IndexWriter(directory, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED))
{
// index a few documents
writer.AddDocument(createDocument("1", "henry morgan"));
writer.AddDocument(createDocument("2", "henry junior morgan"));
writer.AddDocument(createDocument("3", "henry immortal jr morgan"));
writer.AddDocument(createDocument("4", "morgan henry"));
}
// search for documents that have "foo bar" in them
String sentence = "henry morgan";
IndexSearcher searcher = new IndexSearcher(directory, true);
PhraseQuery query = new PhraseQuery()
{
//allow inverse order
Slop = 3
};
query.Add(new Term("contents", sentence));
// display search results
List<string> results = new List<string>();
Console.WriteLine("Looking for \"{0}\"...", sentence);
TopDocs topDocs = searcher.Search(query, 100);
foreach (ScoreDoc scoreDoc in topDocs.ScoreDocs)
{
var matchedContents = searcher.Doc(scoreDoc.Doc).Get("contents");
results.Add(matchedContents);
Console.WriteLine("Found: {0}", matchedContents);
}
}
private static Document createDocument(string id, string content)
{
Document doc = new Document();
doc.Add(new Field("id", id, Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.Add(new Field("contents", content, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
return doc;
}
我认为除id = 3的文档以外的所有选项都应该匹配,但只有第一个选项可以匹配。我错过了什么?
在《 Lucene In Action》第二版,第3.4.6节中,按词组搜索:PhraseQuery。
PhraseQuery使用此信息来查找术语之间相距一定距离的文档
当然,一个普通的TermQuery可以找到知道这些单词中的任何一个的技巧,但是在这种情况下,我们只希望文档中的短语完全并排(快速狐狸)或之间有一个单词的短语(快速[无关]狐狸)
因此,PhraseQuery实际上是在术语之间使用的,该章中的示例代码也证明了这一点。当您使用StandardAnalyzer时,分析后的“亨利·摩根”将是亨利和摩根。因此,您不能将“ henry morgan”添加为一个术语
/*
Sets the number of other words permitted between words
in query phrase.If zero, then this is an exact phrase search.
*/
public void setSlop(int s) { slop = s; }
setSlop的定义可以进一步解释这种情况。在对您的代码稍作更改后,我就知道了。
// code in Scala
val query = new PhraseQuery();
query.setSlop(3)
List("henry", "morgan").foreach { word =>
query.add(new Term("contents", word))
}
在这种情况下,这四个文档将全部匹配。如果您还有其他问题,建议您阅读《 Lucene In Action 2nd》中的该章。这可能会有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句