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

时间:2015-12-28 10:35:22

标签: elasticsearch nested

我使用以下映射:

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" by" 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"
    }
  ]
}

1 个答案:

答案 0 :(得分:6)

您需要inner_hits上的sortnested 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个对象。

希望这有帮助!