Elasticsearch的range范围匹配,可以实现类似SQL语句中的>, >=, <, <=关系表达式。
构建range查询
方式1
// 等价SQL: price > 100 and price < 200
RangeQueryBuilder rangeQueryBuilder = new RangeQueryBuilder("price");
rangeQueryBuilder.gt(100);
rangeQueryBuilder.lt(200);
// 等价SQL: price >= 100 and price <= 200
RangeQueryBuilder rangeQueryBuilder = new RangeQueryBuilder("price");
rangeQueryBuilder.gte(100);
rangeQueryBuilder.lte(200);
方式2
// 等价SQL: price >= 150 and price <= 300
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("price")
.gte(150)
.lte(300);
创建SearchRequest
Java 所有的ES查询请求都是通过SearchRequest对象进行设置,因此需要实例化SearchRequest对象,设置query参数。
SearchRequest searchRequest = new SearchRequest();
// 通过SearchSourceBuilder构建搜索参数
SearchSourceBuilder builder = new SearchSourceBuilder();
// 设置query参数,绑定前面创建的Query对象
builder.query(rangeQueryBuilder);
// 设置SearchRequest搜索参数
searchRequest.source(builder);
执行请求
// 执行ES请求
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
提示: 如何处理查询结果,请参考 Java ES查询基本写法