好的我已經完成了。當我將這些術語一次添加到PhraseQuery對象時,它保留了常用的單詞。在這是「The」的情況下。
我所做的改爲使用QueryParser對象來解析查詢(包括引號)。這將刪除常用單詞,短語查詢現在就像一個魅力。
List<string> searchList = Regex.Matches(searchTerms, @"(?<match>\w+)|\""(?<match>[\w\s]*)""")
.Cast<Match>()
.Select(m => m.Groups["match"].Value)
.ToList();
QueryParser parser = new QueryParser(LuceneFields.BODY, Analyzer);
BooleanQuery booleanQuery = new BooleanQuery();
// go through each term
foreach (string term in searchList)
{
Query query = null;
if (term.Contains(" ")) // multi word phrase
query = parser.Parse("\"" + term + "\"");
else
query = parser.Parse(term);
if (query.ToString() != "")
booleanQuery.Add(query, BooleanClause.Occur.MUST);
}
我使用Lucene.NET創建一個簡單的搜索,我有一點麻煩短語搜索,因爲我是用布爾查詢相結合才能正常工作。
下面的代碼被用於搜索:
List<string> searchList = Regex.Matches(searchTerms, @"(?<match>\w+)|\""(?<match>[\w\s]*)""")
.Cast<Match>()
.Select(m => m.Groups["match"].Value)
.ToList();
QueryParser parser = new QueryParser(LuceneFields.BODY, Analyzer);
BooleanQuery booleanQuery = new BooleanQuery();
// go through each term
foreach (string term in searchList)
{
Query query = null;
if (term.Contains(" ")) // multi word phrase
{
query = new PhraseQuery();
foreach (string str in term.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))
{
((PhraseQuery)query).Add(new Term(LuceneFields.BODY, str));
}
}
else
query = parser.Parse(term);
string strQuery = query.ToString();
if (query.ToString() != "")
booleanQuery.Add(query, BooleanClause.Occur.MUST);
}
我已檢查正在創建查詢,它看起來OK我:
+body:"The following table"
而且我也證實了這一文本實際上是在Lucene索引中,你可以從搜索結果中看到只是搜索「table」
我真的很擔心可能是什麼問題。
我用下面的代碼來創建索引:
Directory = FSDirectory.Open(new System.IO.DirectoryInfo(IndexDirectory));
Analyzer = new StandardAnalyzer(Version);
using (IndexWriter indexWriter = new IndexWriter(Directory, Analyzer, new IndexWriter.MaxFieldLength(Int32.MaxValue)))
{
Response.Write("Adding document...");
Document document = new Document();
// Store the IDDataContent
document.Add(new Field(LuceneFields.ID, id.ToString(), Field.Store.YES, Field.Index.ANALYZED));
// store the url to the file itself
document.Add(new Field(LuceneFields.HREF, FileURL, Field.Store.YES, Field.Index.ANALYZED));
//document.Add(new Field(LuceneFields.TITLE, Article.Title, Field.Store.YES, Field.Index.ANALYZED));
// store the text of the PDF
document.Add(new Field(LuceneFields.BODY, PdfContents, Field.Store.YES, Field.Index.ANALYZED));
indexWriter.AddDocument(document);
indexWriter.Optimize();
indexWriter.Commit();
}
你嘗試運行使用盧克短語查詢這樣的情況下工作? – Mikos
使用Luke的查詢返回預期結果 – Rollcredit