多域检索和区间范围检索使用频率非常高
下面的代码展示了两个的使用方法,同时顺便介绍了布尔查询类BooleanQuery,关系有三种:Occur.MUST,Occur.MUST_NOT,Occur.SHOULD
//实现逻辑检索需要使用BooleanQuery,具体可以查询相关的逻辑关系表达式Occur
BooleanQuery booleanQuery = new BooleanQuery();
Directory dir = FSDirectory.open(new File(indexpath));
IndexSearcher is = new IndexSearcher(DirectoryReader.open(dir));
Analyzer analyzer = new SmartChineseAnalyzer();
String housename=condition.getHousename();
long minPrice = condition.getMinPrice();
long maxPrice = condition.getMaxPrice();
if (!StringUtils.isBlank(housename))
{
//使用MultiFieldQueryParser实现多域检索
QueryParser qp = new MultiFieldQueryParser(new String[]{"housename","kfs"}, analyzer);
//QueryParser qp = new QueryParser("housename", analyzer);
Query query = qp.parse(housename+"*");
booleanQuery.add(query, Occur.MUST);
}
if (minPrice==0)
{
minPrice=Long.MIN_VALUE;
}
if (maxPrice==0)
{
maxPrice=Long.MAX_VALUE;
}
//使用NumericRangeQuery实现价格区间范围的检索,因为价格的索引使用的是LongField,所以使用的是NumericRangeQuery<Long>
NumericRangeQuery<Long> priceQuery = NumericRangeQuery.newLongRange("price", minPrice, maxPrice, true, true);
booleanQuery.add(priceQuery, Occur.MUST);
//使用Sort内实现检索结果排序
TopDocs hits = is.search(booleanQuery, 100, new Sort(new SortField("createtime", SortField.Type.LONG)));