Lucene.Net+盘古分词使用案例
以下是多字段并列搜索函数。
/// <summary>
/// 多字段搜索(以空格,逗号等分隔符隔开)
/// </summary>
/// <param name="keyword"></param>
/// <returns></returns>
private TopDocs MulFieldsSearch(string keyword)
{
TopDocs docs = null;
int n = 100;
SetOutput("正在检索关键字:" + keyword);
try
{
BooleanClause.Occur[] flags=new BooleanClause.Occur[]{BooleanClause.Occur.MUST,BooleanClause.Occur.MUST};
string[] fields = new string[] { "id", "contents" };
string[] values = keyword.Trim().Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
if (fields.Length != values.Length)
{
throw new Exception("字段和对应值不一致");
}
//MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, new StandardAnalyzer());
//parser.SetDefaultOperator(QueryParser.Operator.OR);//或者的关系
//Query query = parser.Parse(keyword);
Query query = MultiFieldQueryParser.Parse(values, fields, flags, new StandardAnalyzer());
Stopwatch watch = new Stopwatch();
watch.Start();
docs = searcher.Search(query, (Filter)null, n); //排序获取搜索结果
watch.Stop();
StringBuffer sb = "搜索完成,共用时:" + watch.Elapsed.Hours + "时 " + watch.Elapsed.Minutes + "分 " + watch.Elapsed.Seconds + "秒 " + watch.Elapsed.Milliseconds + "毫秒";
SetOutput(sb);
}
catch (Exception ex)
{
SetOutput(ex.Message);
}
return docs;
}