范围查询:range
- es中任何查询都能排序
- gte:设置下限
- lte:设置上限
GET goods/_search
{
"query": {
"range": {
"price": {
"gte": 100,
"lte": 500
}
}
}
}
也可以设置排序规则:
GET goods/_search
{
"query": {
"range": {
"price": {
"gte": 100,
"lte": 500
}
}
},
"sort": [
{
"saleNum": {
"order": "desc"
}
}
]
}
@Test
public void testRangeQuery() throws IOException {
SearchRequest searchRequest = new SearchRequest("goods");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("price");
rangeQuery.gte(100);
rangeQuery.lte(500);
sourceBuilder.query(rangeQuery);
sourceBuilder.sort("saleNum", SortOrder.DESC);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHits searchHits = searchResponse.getHits();
long value = searchHits.getTotalHits().value;
System.out.println("总记录数:" + value);
SearchHit[] hits = searchHits.getHits();
List<Goods> goodsList = new ArrayList<>();
for (SearchHit hit : hits) {
String sourceAsString = hit.getSourceAsString();
Goods goods = JSON.parseObject(sourceAsString, Goods.class);
goodsList.add(goods);
}
goodsList.forEach(c -> System.out.println(JSON.toJSONString(c)));
}
|