Elasticsearch - 嵌套字段排序

时间:2021-01-09 10:53:33

标签: elasticsearch

我有一个由以下定义的索引:

    {
    "mappings": {
        "properties": {
            "firstName": {
                "type": "keyword"
            },
            "lastName": {
                "type": "keyword"
            },
            "affiliations": {
                "type": "nested",
                "properties": {
                    "organisation": {
                        "type": "keyword"
                    },
                    "team": {
                        "type": "keyword"
                    },
                    "dateBeginning": {
                        "type": "date",
                        "format": "yyyy-MM-dd"
                    },
                    "dateEnding": {
                        "type": "date",
                        "format": "yyyy-MM-dd"
                    },
                    "country": {
                        "type": "keyword"
                    }
                }
            }
        }
    }
    }

基本上,对于每个研究人员(researchers 是我命名索引的方式),我想按日期开始按降序对隶属关系进行排序。我在 EL 官方文档中阅读了有关内部命中的内容,但不确定它是如何工作的

_id : 3

而且它并没有真正起作用。

研究人员与 { "query": { "nested": { "path": "affiliations", "query": { "match": { "_id": 3 } }, "inner_hits": { "sort" : [ { "affiliations.dateBeginning" : { "order" : "desc", "nested": { "path": "affiliations", "filter": { "term": { "_id": 3 } } } } } ] } } } } 有两个隶属关系,一个 dateBeginning 设置为 _id : 3,另一个设置为 2015-06-30。所以我也试过这个:

2017-06-30

而且它不会按 dateBeginning 对从属关系进行排序。

我也尝试过用 SQL API 来做(因为我更熟悉 SQL 语言),但仍然无法获取我想要的数据。

所以我对 ElasticSearch 很陌生,我使用的是 { "sort" : [ { "affiliations.dateBeginning" : { "order" : "desc", "nested": { "path": "affiliations" } } } ], "query": { "nested": { "path": "affiliations", "query": { "match": { "_id": 3 } } } } } 版本,我不知道还能做什么。

关于我在这里做错的任何建议?

编辑

这是来自该索引的文档示例:

7.10

1 个答案:

答案 0 :(得分:1)

一旦进入嵌套查询,内部命中就不需要额外的嵌套查询。删除它,排序将正常工作:

{
  "query": {
    "nested": {
      "path": "affiliations",
      "query": {
        "match": {
          "_id": 3
        }
      },
      "inner_hits": {
        "sort": [
          {
            "affiliations.dateBeginning": {
              "order": "desc"
            }
          }
        ]
      }
    }
  }
}

请注意,这不会对顶级点击进行排序——只会对内部点击进行排序。 但是您可以按照 affiliations.dateBeginning 的值在顶级排序,如下所示:

POST researchers/_search
{
  "sort": [
    {
      "affiliations.dateBeginning": {
        "order": "desc",
        "nested_path": "affiliations"
      }
    }
  ]
}

但请注意,语法现在略有不同:我们说的是 path 而不是 nested_path