算分函数查询
@SpringBootTest
public class MyTest{
//注入RestHighLevelClient对象
@Autowired
private RestHighLevelClient restHighLevelClient;
@Test
public void test() throws IOException {
//准备SearchRequest请求对象,并指定索引库名
SearchRequest searchRequest = new SearchRequest(索引库名);
//准备BoolQueryBuilder查询对象
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//在BoolQueryBuilder查询对象中添加TermQueryBuilder查询对象,must表示必须匹配且参与算分
boolQueryBuilder.must(QueryBuilders.termQuery(字段名, 搜索词));
//在BoolQueryBuilder查询对象中添加RangeQueryBuilder查询对象,filter表示必须匹配且不参与算分
boolQueryBuilder.filter(QueryBuilders.rangeQuery(字段名).gte(大于等于的值).lte(小于等于的值));
//准备FunctionScoreQueryBuilder查询对象,并在其中添加BoolQueryBuilder查询对象
FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
//原始查询,相关性算分的查询
boolQueryBuilder,
//算分函数数组
new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
//创建算分函数对象并将其放入数组中
new FunctionScoreQueryBuilder.FilterFunctionBuilder(
//指定满足算分函数的过滤条件
QueryBuilders.termQuery(字段名, 搜索词),
//指定算分函数和值
ScoreFunctionBuilders.算分函数(值)
)
});
//在SearchRequest请求对象中放入FunctionScoreQueryBuilder查询对象
searchRequest.source().query(functionScoreQueryBuilder);
//发送请求,得到响应对象
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//从响应对象中获取响应结果
SearchHits searchHits = searchResponse.getHits();
//获取文档的总条数
long total = searchHits.getTotalHits().value;
//获取搜索结果数组
SearchHit[] hits = searchHits.getHits();
//创建文档集合,用于存放结果
List<文档类名> 集合对象名 = new ArrayList<>();
//遍历数组
for (SearchHit hit : hits) {
//获取Json格式的文档内容
String json = hit.getSourceAsString();
//反序列化Json,这里需要引入fastjson的依赖
文档类名 文档对象名 = JSON.parseObject(json, 文档类名.class);
//将结果放入集合
集合对象名.add(文档对象名);
}
}
}
布尔查询
@SpringBootTest
public class MyTest{
//注入RestHighLevelClient对象
@Autowired
private RestHighLevelClient restHighLevelClient;
@Test
public void test() throws IOException {
//准备SearchRequest请求对象,并指定索引库名
SearchRequest searchRequest = new SearchRequest(索引库名);
//准备BoolQueryBuilder查询对象
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//在BoolQueryBuilder查询对象中添加TermQueryBuilder查询对象,must表示必须匹配且参与算分
boolQueryBuilder.must(QueryBuilders.termQuery(字段名, 搜索词));
//在BoolQueryBuilder查询对象中添加RangeQueryBuilder查询对象,filter表示必须匹配且不参与算分
boolQueryBuilder.filter(QueryBuilders.rangeQuery(字段名).gte(大于等于的值).lte(小于等于的值));
//在SearchRequest请求对象中放入BoolQueryBuilder查询对象
searchRequest.source().query(boolQueryBuilder);
//发送请求,得到响应对象
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//从响应对象中获取响应结果
SearchHits searchHits = searchResponse.getHits();
//获取文档的总条数
long total = searchHits.getTotalHits().value;
//获取搜索结果数组
SearchHit[] hits = searchHits.getHits();
//创建文档集合,用于存放结果
List<文档类名> 集合对象名 = new ArrayList<>();
//遍历数组
for (SearchHit hit : hits) {
//获取Json格式的文档内容
String json = hit.getSourceAsString();
//反序列化Json,这里需要引入fastjson的依赖
文档类名 文档对象名 = JSON.parseObject(json, 文档类名.class);
//将结果放入集合
集合对象名.add(文档对象名);
}
}
}