Reputation: 11752
Pardon me, but I'm a newbie to Lucene.
I have added documents to my index with multiple fields
Document doc = new Document();
doc.add(new TextField("productName", productName, Field.Store.YES));
doc.add(new FloatField("price", Float.parseFloat(price), Field.Store.YES));
//+additional fields
I would like to search for a product and filter to a price range. Can someone tell me how to apply a filter to these results?
String[] queryStrings = {searchTerm};
String[] fields = {"itemName"}; //might query multiple fields in future
try {
Query q = MultiFieldQueryParser.parse(luceneVersion, queryStrings, fields, analyzer); // assuming I might want to search additional fields like description in the future
IndexReader reader = DirectoryReader.open(indexDirectory);
IndexSearcher searcher = new IndexSearcher(reader);
TopDocs td = searcher.search(q, to);
// Not sure how to filter here, I eventually will want to save these results for pagination
} catch (Exception e){
e.printStackTrace();
}
Upvotes: 1
Views: 1973
Reputation: 56
I had a similar requirement of combining a search on fields along with a range filter. I ended up with following code
Set<String> fieldSet = Sets.newHashSet();
fieldSet.add(rangeQueryField);
BooleanQuery fieldsQuery = new BooleanQuery();
for (String field : fields) {
fieldSet.add(field);
WildcardQuery queryPart = new WildcardQuery(new Term(field, queryText));
fieldsQuery.add(queryPart, Occur.SHOULD);
}
BooleanQuery query = new BooleanQuery();
query.add(fieldsQuery, Occur.MUST);
NumericRangeFilter<Long> longNumericRangeFilter = NumericRangeFilter.newLongRange(rangeQueryField, rangeValue, Long.MAX_VALUE, false, false);
MultiFieldQueryParser queryParser = new MultiFieldQueryParser(version, fieldSet.toArray(new String[0]), analyzer);
queryParser.setAllowLeadingWildcard(true);
Query q = queryParser.parse(query.toString());
TopFieldDocs searchResults = searcher.search(q, longNumericRangeFilter, maxResultsToReturn, sort);
Upvotes: 0
Reputation: 4623
Did you think about adding a NumericRangeQuery
and combine it with your initial query in a BooleanQuery
?
You can combine them using the MUST
clause
Upvotes: 1