我希望在大量城市名称上构建一个自动完成的文本框。搜索功能如下: 我想对多词短语进行“开头”搜索。例如,如果用户输入了“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 相同,因此它应该可以工作。 Heres 一个工作 sample 我很快地组成测试。我使用的是 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/