gpt4 book ai didi

elasticsearch - 按数组中的出现次数进行计数和排序

转载 作者:行者123 更新时间:2023-12-02 23:42:58 24 4
gpt4 key购买 nike

我有一个名为帐户的类型,具有以下映射:

        "country" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"followingClientIds" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
},
"fielddata" : true
},
followingClientIds是我遵循的其他帐户的字符串ID数组。
我想构建一个查询,以获取来自某个国家/地区的每个帐户,并按照我们都遵循的共同帐户的数量对它们进行排序。
这是我到目前为止所做的一些查询:

GET account/_search
{
"size": 20,
"query": {
"bool": {
"filter": {
"term": {
"country.keyword": "AT"
}
}
}
},
"sort": [
{
"followingClientIds.keyword": {
"order": "asc",
"nested_filter": {
"terms": {
"followingClientIds.keyword": [
"dFbEW23hVZ3w8jhH9LeCw3QG33UjuF5C"
]
}
}
}
}
]
}
例如,我在帐户类型中有这3个文档:
{
"username": "user2",
"country": "AT",
"followingClientIds": ["abc"]
},
{
"username": "user3",
"country": "AT",
"followingClientIds": ["abc", "bcd", "cde"]
},
{
"username": "user4",
"country": "AT",
"followingClientIds": ["abc"]
}
想象一下,我将发送给查询的 国家之后的ClientIds 进行排序:
{
"country": "AT",
"followingClientIds": ["abc", "bcd", "cde"]
}
我希望结果是这样的:
{
"username": "user3",
"country": "AT",
"followingClientIds": ["abc", "bcd", "cde"],
"fields": [ // dont really need this custom field, but would be cool
"mutual_following_count": 3
]
},
{
"username": "user2",
"country": "AT",
"followingClientIds": ["abc"],
"fields": [
"mutual_following_count": 1
]
},
{
"username": "user4",
"country": "AT",
"followingClientIds": ["abc"],
"fields": [
"mutual_following_count": 1
]
}

最佳答案

如果您正在寻找一个名为mutual_following_count的独立computed field,则可以使用以下脚本来完成。但是你won't be able to sort on it
唯一的其他选择是脚本排序,它首先计算一个值,然后按该值排序。结果查询如下所示:

{
"size": 20,
"query": {
"bool": {
"filter": {
"term": {
"country.keyword": "AT"
}
}
}
},
"sort": [
{
"_script": {
"type": "number",
"order": "desc",
"script": {
"lang": "painless",
"params": {
"followingClientIds": ["abc", "bcd", "cde"]
},
"source": """
// deduplicate
def fromSource = doc.followingClientIds
.stream()
.distinct()
.collect(Collectors.toList());
def fromParams = params.followingClientIds
.stream()
.distinct()
.collect(Collectors.toList());

// size() is a float so cast
return (int) fromParams.findAll(x -> fromSource.contains(x)).size();
"""
}
}
}
]
}
缺点是您不能“命名”这种排序。 mutual_following_count或其他都没有。

关于elasticsearch - 按数组中的出现次数进行计数和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63839816/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com