1

请原谅我,但我是 Lucene 的新手。
我已将包含多个字段的文档添加到我的索引中

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

我想搜索产品并过滤到价格范围。有人能告诉我如何对这些结果应用过滤器吗?

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();
}
4

2 回答 2

1

您是否考虑过添加 aNumericRangeQuery并将其与您的初始查询结合起来 a BooleanQuery?您可以使用MUST子句将它们组合起来

于 2013-11-07T18:00:32.610 回答
0

我有一个类似的要求,将字段搜索与范围过滤器结合起来。我最终得到了以下代码

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);
于 2014-03-24T21:05:28.047 回答