[英]Lucene - How do I query on text and filter numeric range
Pardon me, but I'm a newbie to Lucene. 请原谅我,但我是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();
}
Did you think about adding a NumericRangeQuery
and combine it with your initial query in a BooleanQuery
? 您是否考虑过添加NumericRangeQuery
并将其与NumericRangeQuery
的初始查询BooleanQuery
? You can combine them using the MUST
clause 您可以使用MUST
子句合并它们
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.