[英]Not able sort based on multiple text field in elastic-search
doc1:
{
"createdAt": "2022-11-25T09:45:00.000Z",
"tags": [
"Response Needed"
]
}
doc2 :
{
"createdAt": "2022-11-24T09:45:00.000Z",
"tags": [
"Customer care","Response Needed"
]
}
doc3 :
{
"createdAt": "2022-11-24T09:45:00.000Z",
"tags": [
]
}
I want to sort the below documents based on tags first and then createdAt.我想先根据标签对以下文档进行排序,然后再根据 createdAt 对它们进行排序。 If tags is present then it should be in ascending order of createdAt otherwise if tags is blank then it should be in sort based on createdAt in Descending order.
如果标签存在,那么它应该按照 createdAt 的升序排列,否则如果标签为空,那么它应该按照 createdAt 的降序排列。
I believe the solution is to use Script based sorting .我相信解决方案是使用基于脚本的排序。
PUT idx_sort
{
"mappings": {
"properties": {
"createdAt": {
"type": "date"
},
"tags": {
"type": "keyword"
}
}
}
}
POST idx_sort/_doc
{
"createdAt": "2022-11-25T09:45:00.000Z",
"tags": [
"Response Needed"
]
}
POST idx_sort/_doc
{
"createdAt": "2022-11-24T09:45:00.000Z",
"tags": [
"Response 02"
]
}
POST idx_sort/_doc
{
"createdAt": "2022-11-24T09:45:00.000Z",
"tags": [
"Customer care","Response Needed"
]
}
POST idx_sort/_doc
{
"createdAt": "2022-11-24T09:45:00.000Z",
"tags": [
]
}
Query询问
GET idx_sort/_search
{
"sort": [
{
"_script": {
"type": "number",
"script": {
"lang": "painless",
"source": """
def list = doc['tags.keyword'];
if(list.size() > 0){
return list.size();
} else {
return 0;
}
"""
},
"order": "desc"
}
},
{
"createdAt": {
"order": "asc"
}
}
]
}
Response回复
"hits": [
{
"_index": "idx_sort",
"_id": "j489toQBEoAIompjkkXO",
"_score": null,
"_source": {
"createdAt": "2022-11-24T09:45:00.000Z",
"tags": [
"Response 02"
]
},
"sort": [
1,
1669283100000
]
},
{
"_index": "idx_sort",
"_id": "kI89toQBEoAIompjxkWN",
"_score": null,
"_source": {
"createdAt": "2022-11-24T09:45:00.000Z",
"tags": [
"Customer care",
"Response Needed"
]
},
"sort": [
1,
1669283100000
]
},
{
"_index": "idx_sort",
"_id": "jo83toQBEoAIompjcEXD",
"_score": null,
"_source": {
"createdAt": "2022-11-25T09:45:00.000Z",
"tags": [
"Response Needed"
]
},
"sort": [
1,
1669369500000
]
},
{
"_index": "idx_sort",
"_id": "kY8-toQBEoAIompj6kXg",
"_score": null,
"_source": {
"createdAt": "2022-11-24T09:45:00.000Z",
"tags": []
},
"sort": [
0,
1669283100000
]
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.