2012-03-16 73 views
0

假设我在Lucence中存储了一个简短的未分析字段,有一种方法可以搜索该字段包含特定子字符串的文档。简单包含在Lucene中的查询

例如此字段值 “AA-88367分之98” 可以与后续的子串 “883”, “67分之98”, “AA-883” 相匹配, “883 98” 等

在查询Lucene时,我需要将其与其他过滤器结合使用。这是用于Lucene.NET 2.9

回答

1

您可以使用WildCardQuery,但如果通配符项以通配符(*或?)开头,那么如果该字段中有许多不同的术语,它将会非常慢。

这里是一个简单的示例,演示如何编写WildcardQuery。它使用不推荐的东西,应该修改为使用非弃用的重载,但你应该明白。

要与其他查询结合使用,您可以使用BooleanQuery类,该类允许将多个查询组合在一起。

RAMDirectory dir = new RAMDirectory(); 
IndexWriter iw = new IndexWriter(dir, new StandardAnalyzer()); 

Document doc = new Document(); 
doc.Add(new Field("test", "AA-883 98/67", Field.Store.YES, Field.Index.NOT_ANALYZED)); 
iw.AddDocument(doc); 
iw.Commit(); 

IndexSearcher searcher = new IndexSearcher(iw.GetReader()); 

WildcardQuery query = new WildcardQuery(new Term("test", "*883*")); 
Hits hits = searcher.Search(query); 
Console.WriteLine(hits.Length()); 
// prints 1 

query = new WildcardQuery(new Term("test", "*98/67*")); 
hits = searcher.Search(query); 
Console.WriteLine(hits.Length()); 
// prints 1 

query = new WildcardQuery(new Term("test", "*AA-883*")); 
hits = searcher.Search(query); 
Console.WriteLine(hits.Length()); 
// prints 1 

query = new WildcardQuery(new Term("test", "*883 98*")); 
hits = searcher.Search(query); 
Console.WriteLine(hits.Length()); 
// prints 1 

Console.ReadLine(); 
iw.Close(); 
dir.Close(); 
+0

谢谢也许我需要更新我的例子...完成...这项工作,该领域不分析? – AnthonyWJones 2012-03-16 14:52:57

+0

是的,它会工作,如果该领域没有分析,即时更新答案,用一点样本 – 2012-03-16 15:22:20

+0

这个答案是正确的,但你需要知道这种查询(带领先的通配符)可能需要检查所有条款字典(因此,对于大型索引,性能可能非常糟糕)。 – jpountz 2012-03-19 10:31:11