在 Elasticsearch 中对嵌套对象进行排序

Sort nested object in Elasticsearch

我正在使用以下映射:

PUT /my_index
{
  "mappings": {
    "blogpost": {
      "properties": {
        "title": {"type": "string"}
        "comments": {
          "type": "nested", 
          "properties": {
            "comment": { "type": "string"  },
            "date":    { "type": "date"    }
          }
        }
      }
    }
  }
}

文档示例:

PUT /my_index/blogpost/1
{
  "title": "Nest eggs",
  "comments": [ 
    {
      "comment": "Great article",
      "date":    "2014-09-01"
    },
    {
      "comment": "More like this please",
      "date":    "2014-10-22"
    },
    {
      "comment": "Visit my website",
      "date":    "2014-07-02"
    },
    {
      "comment": "Awesome",
      "date":    "2014-08-23"
    }
  ]
}

我的问题是如何检索此文档并将嵌套对象 "comments" 按 "date" 排序?结果:

PUT /my_index/blogpost/1
{
  "title": "Nest eggs",
  "comments": [ 
    {
      "comment": "Awesome",
      "date":    "2014-07-23"
    },
    {
      "comment": "Visit my website",
      "date":    "2014-08-02"
    },
    {
      "comment": "Great article",
      "date":    "2014-09-01"
    },
    {
      "comment": "More like this please",
      "date":    "2014-10-22"
    }
  ]
}

您需要 sortinner_hits 上对 nested objects 进行排序。这将为您提供所需的输出

GET my_index/_search
{
  "query": {
    "nested": {
      "path": "comments",
      "query": {
        "match_all": {}
      },
      "inner_hits": {
        "sort": {
          "comments.date": {
            "order": "asc"
          }
        },
        "size": 5
      }
    }
  },
  "_source": [
    "title"
  ]
}

我正在使用 source filtering 仅获取 "title",因为 comments 将在 inner_hit 中检索,但如果您想要

可以避免这种情况

size 是 5,因为默认值为 3,我们在给定的示例中有 4 个对象。

希望对您有所帮助!