当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《在Elasticsearch中对嵌套对象进行排序》经验,为你挑选了1个好方法。

我正在使用以下映射:

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

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

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

ChintanShah2.. 8

你需要sort在inner_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"
  ]
}

我正在使用源过滤来获取仅"title"comments内部检索,inner_hit但如果你想要你可以避免

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

希望这可以帮助!



1> ChintanShah2..:

你需要sort在inner_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"
  ]
}

我正在使用源过滤来获取仅"title"comments内部检索,inner_hit但如果你想要你可以避免

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

希望这可以帮助!

推荐阅读
家具销售_903
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有