Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multifieldquery and filters in Lucene.net

I want to perform a multi field search on a lucene.net index but filter the results based on one of the fields. Here's what I'm currently doing:

To index the fields the definitions are:

doc.Add(new Field("id", id.ToString(), Field.Store.YES, Field.Index.UN_TOKENIZED));
doc.Add(new Field("title", title, Field.Store.NO, Field.Index.TOKENIZED));
doc.Add(new Field("summary", summary, Field.Store.NO, Field.Index.TOKENIZED, Field.TermVector.YES));
doc.Add(new Field("description", description, Field.Store.NO, Field.Index.TOKENIZED, Field.TermVector.YES));
doc.Add(new Field("distribution", distribution, Field.Store.NO, Field.Index.UN_TOKENIZED));

When I perform the search I do the following:

MultiFieldQueryParser parser = new MultiFieldQueryParser(new string[]{"title", "summary", "description"}, analyzer);
parser.SetDefaultOperator(QueryParser.Operator.AND);
Query query = parser.Parse(text);

BooleanQuery bq = new BooleanQuery();
TermQuery tq = new TermQuery(new Term("distribution", distribution));
bq.Add(tq, BooleanClause.Occur.MUST);
Filter filter = new QueryFilter(bq);

Hits hits = searcher.Search(query, filter);

However, the result is always 0 hits.

What am I doing wrong?

like image 567
Khotu Nam Avatar asked Feb 02 '10 17:02

Khotu Nam


1 Answers

I think I now have a solution. I have discarded the use of the QueryFilter and am using a boolean query to constrain the results before the MultiFieldQuery. So the code will look something like this:

MultiFieldQueryParser parser = new MultiFieldQueryParser(new string[]{"title", "summary", "description"}, analyzer); 
parser.SetDefaultOperator(QueryParser.Operator.AND); 
Query query = parser.Parse(text); 

BooleanQuery bq = new BooleanQuery(); 
TermQuery tq = new TermQuery(new Term("distribution", distribution)); 
bq.Add(tq, BooleanClause.Occur.MUST); 
bq.Add(query, BooleanClause.Occur.MUST)

Hits hits = searcher.Search(bq); 
like image 107
Khotu Nam Avatar answered Sep 22 '22 08:09

Khotu Nam