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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With