目录
一、查询语句
二、Java代码实现
基础介绍:
ES自定义评分机制:function_score查询详解-阿里云开发者社区ES自定义评分机制:function_score查询详解https://developer.aliyun.com/article/1054571
开发版本详见:Elasticsearch-经纬度查询(8.x-半径查询)_es经纬度范围查询-CSDN博客
本案例只展示随机查询,具体查询权重需根据自身业务修改
一、查询语句
GET /article-test-read/_search
{
"query": {
"function_score": {
"query": {
"match_phrase": {
"content": "长沙"
}
},
"functions": [
{
"random_score": {
"field": "_seq_no",
"seed": 100
}
}
],
"score_mode": "multiply" // 将随机分数与其他查询分数相乘
}
}
}
二、Java代码实现
具体查询对象,可自行定义,本方法只提供思路,莫直接粘贴使用
// 封装ES查询参数
BoolQuery.Builder boolQueryBuilder = new BoolQuery.Builder();
// 封装ES查询参数
List<Query> shouldList = new ArrayList<>();
// 笔记关键词查询
Query byIkTitle = MatchQuery.of(match -> match.field("title")
.query(request.getSearch()).boost(2.0f))._toQuery();
shouldList.add(byIkTitle);
Query byIkContent = MatchQuery.of(match -> match.field("content")
.query(request.getSearch()))._toQuery();
shouldList.add(byIkContent);
boolQueryBuilder.should(shouldList).minimumShouldMatch("1");
// 随机查询
long randomValue = RandomUtil.randomLong(665359, 159265359);
FunctionScoreQuery functionScoreQuery = FunctionScoreQuery.of(f -> f.query(q -> q.bool(boolQueryBuilder.build()))
.functions(fn -> fn.randomScore(r -> r.field("_seq_no").seed(String.valueOf(randomValue))))
.scoreMode(FunctionScoreMode.Multiply)
.boostMode(FunctionBoostMode.Multiply)
);
SearchRequest.Builder searchRequestBuilder = new SearchRequest.Builder();
searchRequestBuilder.index(esIndexProperties.getNoteIndexRead())
.query(query -> query.functionScore(functionScoreQuery))
.size(request.getSize());
// ES查询
SearchRequest searchRequest = searchRequestBuilder.build();
log.info("notePageSearch query:{}", searchRequest.toString());
SearchResponse<NoteIndex> searchResponse = esUtil.queryDocument(searchRequest, NoteIndex.class);
searchResponse.hits().hits().forEach(hit -> {
if (Objects.nonNull(hit.source())) {
// 业务处理
}
});