我正在使用Lucene.net來索引產品目錄。我使用ANTS Profiler來分析我的搜索結果,我注意到使用MultiFieldQueryParser創建和解析查詢的行爲幾乎與實際搜索(約100ms)一樣長。然後我嘗試手動創建查詢,這發生得非常快(約1ms)。我寧願不必手動解析,雖然它確實給了我相同的結果集,但我擔心我可能無法處理某些用例或輸入(儘管輸入來自網站上的文本搜索,用戶將不知道關於Lucene搜索語法的任何內容)。我的代碼(這兩種方法)如下:爲什麼MultiFieldQueryParser比手工創建查詢慢得多?
IApplicationSettings settings = new ApplicationSettingService();
FSDirectory directory = FSDirectory.Open(new DirectoryInfo(settings.GetSetting<string>("LuceneMainSearchDirectory")));
RAMDirectory ramDir = new RAMDirectory(directory);
_Searcher = new IndexSearcher(ramDir, true);
string[] searchFields = new string[] { "ProductName", "ProductLongDescription", "BrandName", "CategoryName" };
//Add a wildcard character to end of search to give broader results
if (!searchTerm.EndsWith(" ")) { searchTerm = searchTerm + "*"; }
//Use query parser...this block typically takes about 100ms on my machine, roughly 40% on the constructor and 60% on the call to Parse
MultiFieldQueryParser multiParser = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_29, searchFields, _analyzer);
multiParser.SetDefaultOperator(QueryParser.AND_OPERATOR);
Query query = multiParser.Parse(searchTerm);
//Manually create query....this block doesn't even take 1ms on my machine
BooleanQuery booleanQuery = new BooleanQuery(true);
var terms = searchTerm.Split(' ');
foreach (string s in terms)
{
BooleanQuery subQuery = new BooleanQuery(true);
if (!s.EndsWith("*"))
{
Query query1 = new TermQuery(new Term("ProductName", s));
Query query2 = new TermQuery(new Term("ProductLongDescription", s));
Query query3 = new TermQuery(new Term("BrandName", s));
Query query4 = new TermQuery(new Term("CategoryName", s));
subQuery.Add(query1, BooleanClause.Occur.SHOULD);
subQuery.Add(query2, BooleanClause.Occur.SHOULD);
subQuery.Add(query3, BooleanClause.Occur.SHOULD);
subQuery.Add(query4, BooleanClause.Occur.SHOULD);
}
else
{
Query query1 = new WildcardQuery(new Term("ProductName", s));
Query query2 = new WildcardQuery(new Term("ProductLongDescription", s));
Query query3 = new WildcardQuery(new Term("BrandName", s));
Query query4 = new WildcardQuery(new Term("CategoryName", s));
subQuery.Add(query1, BooleanClause.Occur.SHOULD);
subQuery.Add(query2, BooleanClause.Occur.SHOULD);
subQuery.Add(query3, BooleanClause.Occur.SHOULD);
subQuery.Add(query4, BooleanClause.Occur.SHOULD);
}
booleanQuery.Add(subQuery, BooleanClause.Occur.MUST);
}
//Run the search....results are the same for simple multiword text queries
var result2 = _Searcher.Search(booleanQuery, null, maxResults);
var result = _Searcher.Search(query, null, maxResults);
一種選擇使用手動查詢構建可能是共享MultiFieldQueryParser救了我,但我猜想它的解析方法不是線程安全的(雖然我只看過那關於Java版本...請糾正我,如果我在這個假設是錯誤的)。
我做錯了什麼或者這只是野獸的性質?