Q:非洲食人族的酋长吃什么?

如何对嵌套字段排序,望各位大佬指点一二。

Elasticsearch | 作者 junpassion | 发布于2019年12月19日 | 阅读数:1355

我一条记录里面有两个字段,userId,collectionRank,其中collectionRank里面包含两个嵌入字段:collectionId和pv。 例如这种:
{
"_index": "user_collection_stats",
"_type": "_doc",
"_id": "821788819",
"_score": 1,
"_source": {
"userid": 821788819,
"collectionRank": [
{
"collectionid": "4006653",
"pv": 8
},
{
"collectionid": "3836102",
"pv": 11
},
{
"collectionid": "3631489",
"pv": 5
}
]
}
}

我现在想通过查询语句,得到每个用户,关注的合集中按pv排好序(降序)的合集ID,怎样写查询语句呢,试了一些写法得到的都是无序的。
期待的结果如下:
{
"_index": "user_collection_stats",
"_type": "_doc",
"_id": "821788819",
"_score": 1,
"_source": {
"userid": 821788819,
"collectionRank": [
{
"collectionid": "3836102",
"pv": 11
},
{
"collectionid": "4006653",
"pv": 8
},

{
"collectionid": "3631489",
"pv": 5
}
]
}
}

跪求各位大佬指点,多谢
已邀请:

- Elasticsearch,php

赞同来自:

你要的这种效果,用嵌套好像是实现不了的,前几天我也在这样做过。可以用inner_hits,在inner_hits里面进行排序,里面返回的数据可以按照对应的顺序排序
查询条件:
GET user_collection_stats/_search
{
"query": {
"nested": {
"inner_hits": {
"sort": {
"collectionRank.pv": {
"order": "desc"
}
}
},
"path": "collectionRank",
"query": {
"match_all": {}
}
}
},
"sort": [
{
"collectionRank.pv": {
"order": "desc",
"nested": {
"path": "collectionRank"
}
}
}
]
}
返回的结果
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 1,
"max_score" : null,
"hits" : [
{
"_index" : "user_collection_stats",
"_type" : "_doc",
"_id" : "821788819",
"_score" : null,
"_source" : {
"userid" : 821788819,
"collectionRank" : [
{
"collectionid" : "4006653",
"pv" : 8
},
{
"collectionid" : "3836102",
"pv" : 11
},
{
"collectionid" : "3631489",
"pv" : 5
}
]
},
"sort" : [
11
],
"inner_hits" : {
"collectionRank" : {
"hits" : {
"total" : 3,
"max_score" : null,
"hits" : [
{
"_index" : "user_collection_stats",
"_type" : "_doc",
"_id" : "821788819",
"_nested" : {
"field" : "collectionRank",
"offset" : 1
},
"_score" : null,
"_source" : {
"collectionid" : "3836102",
"pv" : 11
},
"sort" : [
11
]
},
{
"_index" : "user_collection_stats",
"_type" : "_doc",
"_id" : "821788819",
"_nested" : {
"field" : "collectionRank",
"offset" : 0
},
"_score" : null,
"_source" : {
"collectionid" : "4006653",
"pv" : 8
},
"sort" : [
8
]
},
{
"_index" : "user_collection_stats",
"_type" : "_doc",
"_id" : "821788819",
"_nested" : {
"field" : "collectionRank",
"offset" : 2
},
"_score" : null,
"_source" : {
"collectionid" : "3631489",
"pv" : 5
},
"sort" : [
5
]
}
]
}
}
}
}
]
}
}

希望对你有帮助

要回复问题请先登录注册