Lucene.net 无法搜索“.net”
Q1:我正在使用 Lucene 进行搜索。一切都运行良好且快速。当我尝试搜索短语“.net”时,没有找到任何内容。也许你知道我该如何应对这个问题。
Q2:如何搜索并忽略大小写?
更新 1
Q1:我正在使用 SimpleLucene 保存作业。这是代码:
DirectoryIndexWriter _indexWriter = new DirectoryIndexWriter(new DirectoryInfo(indexPath), true);
using (var indexService = new IndexService(_indexWriter))
{
var result = indexService.IndexEntities(jobsTempArray, new JobIndexDefinition());
Console.WriteLine("{0} products indexed in {1} milliseconds.", result.Count, result.ExecutionTime);
}
JobIndexDefinition 文件:
public class JobIndexDefinition : IIndexDefinition<LucenceJobModel>
{
public Document Convert(LucenceJobModel job)
{
var document = new Document();
document.Add(new Field("jobtitle", job.JobTitle, Field.Store.YES, Field.Index.ANALYZED));
document.Add(new Field("AreaCode", job.AreaCode.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("Company", job.Company, Field.Store.YES, Field.Index.NOT_ANALYZED));
var dateValue = DateTools.DateToString(job.DatePosted.Value, DateTools.Resolution.MILLISECOND);
document.Add(new Field("DatePosted", dateValue, Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("Description", job.Description, Field.Store.YES, Field.Index.ANALYZED));
document.Add(new Field("Expierence", job.Expierence, Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("JobType", job.JobType, Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("Link", job.Link, Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("LinkId", job.LinkId.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("Location", job.Location, Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("PayRate", job.PayRate, Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("Source", job.Source, Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("TaxTerm", job.TaxTerm, Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("Term", job.Term, Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("Title", job.Title, Field.Store.YES, Field.Index.NOT_ANALYZED));
return document;
}
public Term GetIndex(LucenceJobModel job)
{
return new Term("Link", job.Link);
}
}
我正在搜索 JobTitle、Description 和 DatePosted 字段。这是搜索代码:
public List<LucenceJobModel> JobsSearch(string keyword, string location, PageInfo pageInfo)
{
string[] words = keyword.Split(new[] { ' ' });
IndexReader reader = IndexReader.Open(SmartSearch.Instance.GetDirectory(), true);
var searcher = new IndexSearcher(reader);
var standardAnalyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);
var fields = new[] { "JobTitle", "Description", "DatePosted" };
var searchQuery = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_29, fields, standardAnalyzer);
//searchQuery.SetAllowLeadingWildcard(true);
// perform the search
var query = new BooleanQuery();
foreach (var word in words)
{
if (!String.IsNullOrEmpty(word))
{
var qTemp = searchQuery.Parse(word);
var q = searchQuery.Parse(qTemp.ToString().Substring(qTemp.ToString().LastIndexOf(":") + 1) + "*");
query.Add(q, BooleanClause.Occur.MUST);
}
}
int maxDocs = 1;
if (reader.MaxDoc() > 0)
maxDocs = reader.MaxDoc();
var results = searcher.Search(query, filter, maxDocs);
foreach (var scoreDoc in results.scoreDocs)
{
var document = searcher.Doc(scoreDoc.doc);
}
var jobs = new List<LucenceJobModel>();
for (int i = 0; i < results.scoreDocs.Length; i++)
{
var document = searcher.Doc(results.scoreDocs[i].doc);
if (i >= (pageInfo.CurrentPage - 1) * pageInfo.ItemsPerPage && i < pageInfo.CurrentPage * pageInfo.ItemsPerPage)
{
jobs.Add(LucenceJobModel.ConvertFromDoc(document));
}
itemsForGroup.Add(new ItemGroupFor
{
Company = document.GetField("Company").StringValue(),
DatePosted = DateTools.StringToDate(document.GetField("DatePosted").StringValue()),
JobType = document.GetField("JobType").StringValue(),
Location = document.GetField("Location").StringValue(),
Source = document.GetField("Source").StringValue(),
Title = document.GetField("Title").StringValue()
});
}
pageInfo.TotalItems = results.scoreDocs.Length;
return jobs;
}
我希望能够搜索“C#”或“.net”等关键字,而无需删除“#”或“.”。
Q2:我正在位置字段中搜索。这是代码:
public List<string> GetLocations(string term)
{
IndexReader reader = IndexReader.Open(SmartSearch.Instance.GetDirectory(), true);
var searcher = new IndexSearcher(reader);
var standardAnalyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);
QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "Location", standardAnalyzer);
string str = parser.Parse(term).ToString().Substring(parser.Parse(term).ToString().LastIndexOf(":") + 1);
PrefixQuery q = new PrefixQuery(new Term("Location", string.Format("{0}", str)));
TopDocs results = searcher.Search(q, 5000);
return results
.scoreDocs
.Select(x => searcher.Doc(x.doc))
.Select(x => x.GetField("Location").StringValue())
.Distinct()
.ToList();
}
我想搜索“纽约”、“纽约”等。但我知道只有情况正确时才会进行搜索。
Q1: I am making a search using Lucene. Everything works fine and quickly. When I tried to search for the phrase ".net", it didn't find anything. Maybe you know how can I cope with this.
Q2: How can I search and ignore case?
Update 1
Q1:I am saving jobs using SimpleLucene. Here is the code:
DirectoryIndexWriter _indexWriter = new DirectoryIndexWriter(new DirectoryInfo(indexPath), true);
using (var indexService = new IndexService(_indexWriter))
{
var result = indexService.IndexEntities(jobsTempArray, new JobIndexDefinition());
Console.WriteLine("{0} products indexed in {1} milliseconds.", result.Count, result.ExecutionTime);
}
JobIndexDefinition file:
public class JobIndexDefinition : IIndexDefinition<LucenceJobModel>
{
public Document Convert(LucenceJobModel job)
{
var document = new Document();
document.Add(new Field("jobtitle", job.JobTitle, Field.Store.YES, Field.Index.ANALYZED));
document.Add(new Field("AreaCode", job.AreaCode.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("Company", job.Company, Field.Store.YES, Field.Index.NOT_ANALYZED));
var dateValue = DateTools.DateToString(job.DatePosted.Value, DateTools.Resolution.MILLISECOND);
document.Add(new Field("DatePosted", dateValue, Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("Description", job.Description, Field.Store.YES, Field.Index.ANALYZED));
document.Add(new Field("Expierence", job.Expierence, Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("JobType", job.JobType, Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("Link", job.Link, Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("LinkId", job.LinkId.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("Location", job.Location, Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("PayRate", job.PayRate, Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("Source", job.Source, Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("TaxTerm", job.TaxTerm, Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("Term", job.Term, Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("Title", job.Title, Field.Store.YES, Field.Index.NOT_ANALYZED));
return document;
}
public Term GetIndex(LucenceJobModel job)
{
return new Term("Link", job.Link);
}
}
I am searching for JobTitle, Description and DatePosted fields. Here is the search code:
public List<LucenceJobModel> JobsSearch(string keyword, string location, PageInfo pageInfo)
{
string[] words = keyword.Split(new[] { ' ' });
IndexReader reader = IndexReader.Open(SmartSearch.Instance.GetDirectory(), true);
var searcher = new IndexSearcher(reader);
var standardAnalyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);
var fields = new[] { "JobTitle", "Description", "DatePosted" };
var searchQuery = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_29, fields, standardAnalyzer);
//searchQuery.SetAllowLeadingWildcard(true);
// perform the search
var query = new BooleanQuery();
foreach (var word in words)
{
if (!String.IsNullOrEmpty(word))
{
var qTemp = searchQuery.Parse(word);
var q = searchQuery.Parse(qTemp.ToString().Substring(qTemp.ToString().LastIndexOf(":") + 1) + "*");
query.Add(q, BooleanClause.Occur.MUST);
}
}
int maxDocs = 1;
if (reader.MaxDoc() > 0)
maxDocs = reader.MaxDoc();
var results = searcher.Search(query, filter, maxDocs);
foreach (var scoreDoc in results.scoreDocs)
{
var document = searcher.Doc(scoreDoc.doc);
}
var jobs = new List<LucenceJobModel>();
for (int i = 0; i < results.scoreDocs.Length; i++)
{
var document = searcher.Doc(results.scoreDocs[i].doc);
if (i >= (pageInfo.CurrentPage - 1) * pageInfo.ItemsPerPage && i < pageInfo.CurrentPage * pageInfo.ItemsPerPage)
{
jobs.Add(LucenceJobModel.ConvertFromDoc(document));
}
itemsForGroup.Add(new ItemGroupFor
{
Company = document.GetField("Company").StringValue(),
DatePosted = DateTools.StringToDate(document.GetField("DatePosted").StringValue()),
JobType = document.GetField("JobType").StringValue(),
Location = document.GetField("Location").StringValue(),
Source = document.GetField("Source").StringValue(),
Title = document.GetField("Title").StringValue()
});
}
pageInfo.TotalItems = results.scoreDocs.Length;
return jobs;
}
I want to be able to search for keywords such as "C#" or ".net" without deleting "#" or ".".
Q2: I am searching in Location field. Here is code:
public List<string> GetLocations(string term)
{
IndexReader reader = IndexReader.Open(SmartSearch.Instance.GetDirectory(), true);
var searcher = new IndexSearcher(reader);
var standardAnalyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);
QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "Location", standardAnalyzer);
string str = parser.Parse(term).ToString().Substring(parser.Parse(term).ToString().LastIndexOf(":") + 1);
PrefixQuery q = new PrefixQuery(new Term("Location", string.Format("{0}", str)));
TopDocs results = searcher.Search(q, 5000);
return results
.scoreDocs
.Select(x => searcher.Doc(x.doc))
.Select(x => x.GetField("Location").StringValue())
.Distinct()
.ToList();
}
I want to search for "New york", "New York" and so on. But I know it searches only if case is right.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不熟悉“SimpleLucene”,但您的代码看起来比需要的复杂得多。
有几点:
字段名称区分大小写,您将职位名称存储为“jobtitle”,但使用“JobTitle”进行搜索。他们需要匹配。
您提到您想要搜索 DatePosted 和 Location 字段,但它们在您发布的代码中是“NOT_ANALYZED”。如果您想搜索这些字段,请将其更改为“ANALYZED”。
如果您想保留“.net”和“C#”等术语,请尝试空白分析器。请记住,空白分析器不使用小写过滤器,因此搜索“.NET”不会匹配“.net”。您可能必须编写自己的分析器。
A1:所有内置分析器(关键字和空格除外)都会从术语中删除句点,因此如果您搜索:“net”、“.net”、“.net”、...net 应该没有关系...”,等等。如果情况并非如此,则还有另一个问题。发布一些代码,也许我们可以提供帮助。
如果您需要匹配“.net”和“C#”等术语,您可能会有更好的运气如果这不能满足您的需求。您可能需要编写自己的分析器。
A2:标准分析器会自动将大写字母转换为小写字母,因此您已经忽略了大小写
。 /today/2003/07/30/LuceneIntro.html" rel="nofollow">此页面提供了各种分析器对短语执行操作的良好示例。
从上面的页面:
分析“快速分析”棕色狐狸跳了起来战胜懒狗”
分析“XY&Z Corporation - [电子邮件;受保护]“
I'm not familiar with "SimpleLucene" but your code looks a lot more complex than it needs to be.
A few things:
Field names are case-sensitive, you store the job title as "jobtitle" but search for it using "JobTitle". They need to match.
You mentioned that you want to search the DatePosted and Location fields but they are "NOT_ANALYZED" in the code you posted. Change it to "ANALYZED" if you want to search those fields.
Try the whitespace analyzer if you want to keep terms like ".net" and "C#". Keep in mind that the whitespace analyzer does not use the lowercase filter, so a search for ".NET" wont match ".net". You may have to write your own analyzer.
A1: All of the built in Analyzers (except keyword and whitespace) strip the period from a term, so it shouldn't matter if you search for: "net", ".net", ".net", ...net...", etc.. If this isn't the case, there's another problem. Post some code and maybe we can help.
If you need to match terms like ".net" and "C#" you will probably have better luck with the Whitespace Analyzer. If that doesn't meet your needs you will probably have to write your own analyzer.
A2: The Standard Analyzers automatically converts upper-case to lower case, so case is already ignored for you.
This page has good examples of what the various Analyzers do to a phrase.
From the page above:
Analzying "The quick brown fox jumped over the lazy dogs"
Analzying "XY&Z Corporation - [email protected]"
A1:
这听起来很严重,因为您不会使用与查询相同的
Analyzer
/Tokenizer
来进行索引。您需要确保同一字段的两者相同。例如,
如果在索引时生成术语
.net
,并且您的查询分析器剥离点,它将找不到任何内容。A2:StandardAnalyzer 应该处理这个问题
A1:
This heavily sounds as you would not use the same
Analyzer
/Tokenizer
for indexing as for querying.You need to make sure that both are the same for the same field. E.g.
If the term
.net
is produced while indexing and your query analyzer strips points it will not find anything.A2: The StandardAnalyzer should take care of this