Lucene - 如何查询文本和过滤数值范围

时间:2013-11-07 17:39:08

标签: java lucene

请原谅我,但我是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();
}

2 个答案:

答案 0 :(得分:1)

您是否考虑过添加NumericRangeQuery并将其与BooleanQuery中的初始查询相结合? 您可以使用MUST clause

组合它们

答案 1 :(得分: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);