Elasticsearch-2019年按嵌套字段排序

时间:2019-06-11 00:21:01

标签: php sorting elasticsearch

因此,我试图找出一种基于嵌套文档的单个属性对文档进行排序的方法。例如,假设我有一个“视频”索引。每个视频都有一个视频所属类别的列表。每个类别都是一个嵌套文档,其中包含有关该类别的某些元数据,例如id,意见,这是一个示例映射:

 "videos" : {
    "properties" : {
      "categories" : {
        "type" : "nested",
        "properties" : {
          "id" : {
            "type" : "integer"
          },
          "views" : {
            "type" : "integer"
          },
          "slug" : {
            "type" : "keyword"
          }
        }
      },
      "title" : {
        "type" : "text"
      },
    }
  }

这是一个示例文档:

  {
    "_index" : "videos",
    "_id" : "123",
    "_source" : {
      "title" : "this is a test video",
      "categories" : [
        {
          "id" : 3533,
          "slug" : "animals",
          "views" : 314
        },
        {
          "id" : 3564,
          "slug" : "comedy",
          "views" : 814
        },
        {
          "id" : 4072,
          "slug" : "politics",
          "views" : 80
        }
      ],
    }
  }

因此,我想按特定类别的观看次数对视频进行排序。例如,按“喜剧”类别中的观看次数按降序对视频进行排序。我已经在网上搜寻了解决方案,但是其中大多数似乎都是针对某个问题或使用过时的查询。

1 个答案:

答案 0 :(得分:1)

Ypu需要使用嵌套过滤器。您可以获取更多信息https://qbox.io/blog/sorting-nested-fields-in-elasticsearch

GET videos/_search
{

  "sort": [
    {
      "categories.views": {
        "order": "asc",
        "nested": {
          "path": "categories",
          "filter": {
            "term": {
              "categories.slug": "comedy"
            }
          }
        }
      }
    }
  ]
}

结果

   "hits" : [
      {
        "_index" : "videos",
        "_type" : "_doc",
        "_id" : "uT6bRGsBFW2mvGhmMxUU",
        "_score" : null,
        "_source" : {
          "title" : "this is a test video",
          "categories" : [
            {
              "id" : 3533,
              "slug" : "animals",
              "views" : 314
            },
            {
              "id" : 3564,
              "slug" : "comedy",
              "views" : 814
            },
            {
              "id" : 4072,
              "slug" : "politics",
              "views" : 80
            }
          ]
        },
        "sort" : [
          814
        ]
      },
      {
        "_index" : "videos",
        "_type" : "_doc",
        "_id" : "uj6bRGsBFW2mvGhmXxWl",
        "_score" : null,
        "_source" : {
          "title" : "this is a test video",
          "categories" : [
            {
              "id" : 3533,
              "slug" : "animals",
              "views" : 314
            },
            {
              "id" : 3564,
              "slug" : "comedy",
              "views" : 900
            },
            {
              "id" : 4072,
              "slug" : "politics",
              "views" : 80
            }
          ]
        },
        "sort" : [
          900
        ]
      }
    ]