c# - Lucene.net 和部分 "starts with"词组搜索

标签 c# lucene.net lucene

我希望在大量城市名称上构建一个自动完成文本框。搜索功能如下: 我想对多词短语进行“开始于”搜索。例如,如果用户输入了“chicago he”,则只需要返回诸如“Chicago Heights”之类的位置。
我正在尝试为此使用 Lucene。我在理解这需要如何实现时遇到问题。

我已经尝试过我认为应该有效的方法:

我已经使用 KeywordAnalyzer 为位置编制了索引(我已经尝试了 TOKENIZED 和 UN_TOKENIZED):

doc.Add(new Field("Name", data.ToLower(), Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.NO));

并通过以下方式搜索它们(我也尝试了各种其他查询/分析器/等):

var luceneQuery = new BooleanQuery();
var wildcardQuery = new WildcardQuery(new Term("Name", "chicago hei*"));
luceneQuery.Add(wildcardQuery, BooleanClause.Occur.MUST);

我没有得到任何结果。非常感谢任何建议。

最佳答案

为此,您需要使用 Field.Index.NOT_ANALYZED 设置为您的字段编制索引,该设置与您使用的 UN_TOKENIZED 相同,因此它应该可以工作。这是我快速制作的用于测试的工作示例。我正在使用 Nuget 上可用的最新版本

IndexWriter iw = new IndexWriter(@"C:\temp\sotests", new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29), true);

Document doc = new Document();
Field loc = new Field("location", "", Field.Store.YES, Field.Index.NOT_ANALYZED);
doc.Add(loc);

loc.SetValue("chicago heights");
iw.AddDocument(doc);

loc.SetValue("new-york");
iw.AddDocument(doc);

loc.SetValue("chicago low");
iw.AddDocument(doc);

loc.SetValue("montreal");
iw.AddDocument(doc);

loc.SetValue("paris");
iw.AddDocument(doc);

iw.Commit();


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

WildcardQuery query = new WildcardQuery(new Term("location", "chicago he*"));

var hits = ins.Search(query);

for (int i = 0; i < hits.Length(); i++)
    Console.WriteLine(hits.Doc(i).GetField("location").StringValue());

Console.WriteLine("---");

query = new WildcardQuery(new Term("location", "chic*"));
hits = ins.Search(query);

for (int i = 0; i < hits.Length(); i++)
    Console.WriteLine(hits.Doc(i).GetField("location").StringValue());

iw.Close();
Console.ReadLine();

关于c# - Lucene.net 和部分 "starts with"词组搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12165488/

相关文章:

c# - 如何使用 ComboBox SelectionChanged 事件更改 StackPanel 颜色?

c# - async-await 是让我的程序中的两个独立任务并行运行的必要条件吗?

c# - Lucene 3.0.3 中的地理空间搜索 - API 重大更改?

solr - Solr 的 Cursor 和 ElasticSearch 的 Scroll 之间的差异

python - 尝试为 python 安装 lucene。首先需要安装jcc。为 jcc 构建 setup.py 时,出现错误 ld : library not found for -ljava

elasticsearch - 如何在Elasticsearch中映射人的年龄,使其保持真实

c# - Selenium webdriver - 驱动程序。在同一页面上导航

c# - 创建自定义全尺寸日历控件

Lucene:查询和过滤器有什么区别

c# - 为什么 Lucene.Net 索引器抛出 System.IO.IOException 未处理?