[Lucene.Net] 搜尋多個欄位

[Lucene.Net] 搜尋多個欄位

如果你跟我一樣剛開始玩Lucene.Net的話,搜尋的部分應該差不多都是用下面這樣的範例

QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "ArticleTitle", new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29));
Query query = parser.Parse(_searchString);

這樣的範例是針對一個欄位搜尋,

那如果要針對多個欄位呢?

要針對多的欄位搜尋的話,有三個方式,

第一個是用BooleanQuery

Query _queryTitle = new TermQuery(new Term("ArticleTitle", _searchString));
Query _queryId = new TermQuery(new Term("ArticleId", _searchString));
BooleanQuery _query = new BooleanQuery();
_query.Add(_queryTitle, BooleanClause.Occur.SHOULD);
_query.Add(_queryId, BooleanClause.Occur.SHOULD);
TopDocs _topDocs = indexSearcher.Search(_query,10);

如果想要用and的效果,則是將 BooleanClause.Occur.SHOULD 改成BooleanClause.Occur.MUST

 

第二個用MultifieldQueryFieldParser

MultiFieldQueryParser _mQueryParser = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_29 ,new string[] { "ArticleTitle", "ArticleId" }, new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29));
TopDocs _topDocs = this._searcher.Search(_mQueryParser.Parse(_searchString), 10);

第三個則是一樣用QueryParser,只是設定搜尋字串的時候,要使用特定的語法.(其實就只是把欄位跟查詢條件寫在一起而已...)

QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "ArticleTitle", new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29));
string _queryString = "ArticleTitle:" + _searchString + " OR ArticleId:" + _searchString;
Query query = parser.Parse(_queryString);
TopDocs _topDocs = this._searcher.Search(query, 10);

如果_queryString沒有設定特定的欄位的話,就會搜尋ArticleTitle

 

參考網頁 : 

BooleanClause.Occur

Lucene QueryParser two Fields

Query Parser Syntax