首页 > 解决方案 > 使用嵌套对象数组对索引进行 ElasticSearch 查询和过滤

问题描述

我有一个具有以下文档结构的 ElasticSearch 索引设置

[
    {
      "id":id,
      "title: "Sample Title",
      "created_at":timestamp
      "categories:[
          {
              "name": "Category 1"
              "image": "image.png",
          },
          {
              "name": "Category 2"
              "image": "image.png",
          },
          {
              "name": "Category 3"
              "image": "image.png",
          },
          {
              "name": "Category 4"
              "image": "image.png",
          },
          ....
      ]
    },
    ....
]

该索引将包含数十万条这种格式的记录。我正在尝试弄清楚如何以最佳方式设置查询并构建此数据,以便我可以设置一个查询,使我能够以这种方式向最终用户显示类别列表。

此查询将能够通过 created_at 时间戳过滤,以便根据此类项目的数量调整计数。

标签: elasticsearch

解决方案


终于想通了。

首先,您必须为类别显式设置映射,否则将不允许您在聚合中使用“嵌套”属性。

"mappings": {
    "dynamic": "true",
    "properties":{
        "categories":{
            "type":"nested"
        }
    }
}

然后我发现解决这个问题的最佳方法是使用“复合”聚合https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-composite-aggregation.html

这将允许我对聚合进行分页并拉回所有必要的属性。

{
    "aggs": {
        "categories": {
            "nested": {
                "path": "categories"
            },
            "aggs": {
                "list": {
                    "composite": {
                        "sources": [
                            {
                                "name": {
                                    "terms": {
                                        "field": "categories.name.keyword"
                                    }
                                }
                            },
                            {
                                "image": {
                                    "terms": {
                                        "field": "categories.image.keyword"
                                    }
                                }
                            }
                        ]
                    }
                }
            }
        }
    }
}

推荐阅读