在Elasticsearch中对嵌套对象进行排序 [英] Sort nested object in Elasticsearch

查看:665
本文介绍了在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"
    }
  ]
}

我的问题是如何检索此文档并按日期"对嵌套对象注释"进行排序?结果:

My question is how to retrieve this document and sort the nested object "comments" by "date"? the result:

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

推荐答案

您需要在

You need to sort on the inner_hits to sort the nested objects. This will give you the desired output

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

我正在使用源过滤仅获得"title"作为comments的信息,将在inner_hit内部检索,但是如果需要,您可以避免这种情况

I am using source filtering to get only "title" as comments will be retrieved inside inner_hit but you can avoid that if you want

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

size is 5 because default value is 3 and we have 4 objects in the given example.

希望这会有所帮助!

这篇关于在Elasticsearch中对嵌套对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆