当前位置:网站首页>Wow, elasticsearch multi field weight sorting can play like this
Wow, elasticsearch multi field weight sorting can play like this
2020-11-06 01:28:00 【Yin Jihuan】
background
Readers ask questions :ES There is no list of the weight ranking of the , Reference ?
I've been in touch with , So I wrote this article , It can be referred to as .
In many complex business scenarios , The rules of sorting will be more complicated , A single descending order , Ascending order can't meet daily needs . however ES Provides a way to weight documents to sort , It still works .
First initialize three test data , Easy to view :
{
id: 1,
title: "Java How to learn ",
type: 3,
userId: 1,
tags: [
"java"
],
textContent: " I have to learn Java",
status: 1,
heat: 80
}
{
id: 2,
title: "Java How to learn ",
type: 2,
userId: 1,
tags: [
"java"
],
textContent: " I have to learn Java",
status: 1,
heat: 99
}
{
id: 3,
title: "Java How to learn ",
type: 1,
userId: 1,
tags: [
"java"
],
textContent: " I have to learn Java",
status: 1,
heat: 100
}
type:1 For translation ,2 For reprint ,3 For the original
The requirement is to query userId=1 All articles of , Sort in descending order of heat , But the original type of article should be displayed in the front , Priority over heat .
If we simply sort by heat , So the order must be id by 3( degree of heat :100),2( degree of heat :99),1( degree of heat :80) It's arranged like this .
But the original type should be at the front , So the result should be 1( degree of heat :80, type : original ),3( degree of heat :100, type : translate ),2( degree of heat :99, type : Reprint ).
The sorting conditions must be in terms of heat , This is for sure . The only thing that needs to be dealt with is how to put the original type at the top , If only implementation is considered , There are many ways .
such as : The original type of heat value can be adjusted higher , But what? , The heat value needs a new field , Only for sorting , It shows the user the same heat value as before , This makes sorting simple , Or according to the heat arrangement can achieve the effect .
weightFactorFunction
stay ES In search results _score I believe you are not unfamiliar with this field , This is a ES The score given , We can sort by score , Then improve the score of the original type to achieve the desired effect .
Look directly at Java Code it , adopt FunctionScoreQueryBuilder To build the query .
@Test
public void testSort() {
FunctionScoreQueryBuilder.FilterFunctionBuilder[] filterFunctionBuilders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("type", 3), ScoreFunctionBuilders.weightFactorFunction(100)),
new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("type", 2), ScoreFunctionBuilders.weightFactorFunction(1)),
new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("type", 1), ScoreFunctionBuilders.weightFactorFunction(1))
};
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
boolQuery.must(QueryBuilders.termQuery("userId", 1));
FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(boolQuery, filterFunctionBuilders);
searchSourceBuilder.query(functionScoreQueryBuilder)
.sort("_score", SortOrder.DESC)
.sort("heat", SortOrder.DESC);
SearchRequest searchRequest = new SearchRequest(elasticSearchIndexConfig.getArticleSearchIndexName());
searchRequest.types(EsConstant.DEFAULT_TYPE);
searchRequest.source(searchSourceBuilder);
List<ArticleDocument> searchResults = kittyRestHighLevelClient.search(searchRequest, ArticleDocument.class);
searchResults.forEach(doc -> {
System.out.println(doc.getId() + "\t" + doc.getType() + "\t" + doc.getHeat());
});
}
adopt ScoreFunctionBuilders.weightFactorFunction Set the corresponding weight for the article type , The weight of original article is 100, Everything else 1, In this way, the score of original articles is higher than that of other types of articles .
In order to rank, the score should be ranked first , Then the heat is sorted . We can get the results we want .
scriptFunction
Besides using weightFactorFunction To set the weight , In addition, it introduces a kind of higher flexibility , For more complex sorting scenarios scriptFunction.
scriptFunction It allows us to achieve weights through scripting , Look directly at the code :
@Test
public void testSort() {
String scoreScript = "if (doc['type'].value == 3) {" +
" return 100;" +
"} else {" +
" return 1;" +
"}";
FunctionScoreQueryBuilder.FilterFunctionBuilder[] filterFunctionBuilders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchAllQuery(), ScoreFunctionBuilders.scriptFunction(new Script(scoreScript)))
};
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
boolQuery.must(QueryBuilders.termQuery("userId", 1));
FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(boolQuery, filterFunctionBuilders);
searchSourceBuilder.query(functionScoreQueryBuilder)
.sort("_score", SortOrder.DESC)
.sort("heat", SortOrder.DESC);
SearchRequest searchRequest = new SearchRequest(elasticSearchIndexConfig.getArticleSearchIndexName());
searchRequest.types(EsConstant.DEFAULT_TYPE);
searchRequest.source(searchSourceBuilder);
List<ArticleDocument> searchResults = kittyRestHighLevelClient.search(searchRequest, ArticleDocument.class);
searchResults.forEach(doc -> {
System.out.println(doc.getId() + "\t" + doc.getType() + "\t" + doc.getHeat());
});
}
scoreScript It's the script that controls the weight , That is, a piece of code ( The default script is groovy), Is it convenient to do so much .
About author : Yin Jihuan , Simple technology enthusiasts ,《Spring Cloud Microservices - Full stack technology and case analysis 》, 《Spring Cloud Microservices introduction Actual combat and advanced 》 author , official account Ape world Originator .
I have compiled a complete set of learning materials , Those who are interested can search through wechat 「 Ape world 」, Reply key 「 Learning materials 」 Get what I've sorted out Spring Cloud,Spring Cloud Alibaba,Sharding-JDBC Sub database and sub table , Task scheduling framework XXL-JOB,MongoDB, Reptiles and other related information .
版权声明
本文为[Yin Jihuan]所创,转载请带上原文链接,感谢
边栏推荐
- Arrangement of basic knowledge points
- TRON智能钱包PHP开发包【零TRX归集】
- ES6学习笔记(二):教你玩转类的继承和类的对象
- 5.4 static resource mapping
- 6.4 viewresolver view parser (in-depth analysis of SSM and project practice)
- H5 makes its own video player (JS Part 2)
- PHPSHE 短信插件说明
- Summary of common algorithms of binary tree
- Python Jieba segmentation (stuttering segmentation), extracting words, loading words, modifying word frequency, defining thesaurus
- Using consult to realize service discovery: instance ID customization
猜你喜欢
Network security engineer Demo: the original * * is to get your computer administrator rights! 【***】
axios学习笔记(二):轻松弄懂XHR的使用及如何封装简易axios
How to select the evaluation index of classification model
Construction of encoder decoder model with keras LSTM
前端都应懂的入门基础-github基础
Python download module to accelerate the implementation of recording
vue任意关系组件通信与跨组件监听状态 vue-communication
ES6学习笔记(五):轻松了解ES6的内置扩展对象
用一个例子理解JS函数的底层处理机制
If PPT is drawn like this, can the defense of work report be passed?
随机推荐
What problems can clean architecture solve? - jbogard
关于Kubernetes 与 OAM 构建统一、标准化的应用管理平台知识!(附网盘链接)
Wechat applet: prevent multiple click jump (function throttling)
全球疫情加速互联网企业转型,区块链会是解药吗?
The difference between Es5 class and ES6 class
git rebase的時候捅婁子了,怎麼辦?線上等……
Mac installation hanlp, and win installation and use
一篇文章教会你使用Python网络爬虫下载酷狗音乐
ES6学习笔记(五):轻松了解ES6的内置扩展对象
比特币一度突破14000美元,即将面临美国大选考验
Summary of common algorithms of binary tree
速看!互联网、电商离线大数据分析最佳实践!(附网盘链接)
Skywalking series blog 1 - install stand-alone skywalking
Vue.js Mobile end left slide delete component
Common algorithm interview has been out! Machine learning algorithm interview - KDnuggets
带你学习ES5中新增的方法
6.2 handleradapter adapter processor (in-depth analysis of SSM and project practice)
2019年的一个小目标,成为csdn的博客专家,纪念一下
Wiremock: a powerful tool for API testing
用一个例子理解JS函数的底层处理机制