【问题标题】:Elastic search querying nested document array弹性搜索查询嵌套文档数组
【发布时间】:2018-05-17 10:54:09
【问题描述】:

考虑我在弹性搜索索引中有一些文档(在下面提到的结构中)

{
  "xid": "1234567",
  "time": "12/5/12 5:49 AM",
  "data": [
    {
      "id": "abc",
      "amount": 400
    },
    {
     "id": "def",
      "amount": 200 
    }
  ]
}
{
  "xid": "1234568",
  "time": "13/5/12 7:23 AM",
  "data": [
    {
      "id": "abc",
      "amount": 400
    },
    {
     "id": "ghi",
      "amount": 300 
    }
  ]
}

现在在每个文档的数据数组中,我想按 id 分组并找到总和。

对于给定的 2 个文档,解决方案类似于

{
"id" : "abc",
"total" :800
},
{
"id" : "def",
"total" :200
},
{
"id" : "ghi",
"total" :300
}

请帮助我构建我的请求查询。
我最初的方法是

{
  "aggs": {
    "group_by_id": {
      "terms": {
        "field": "data.id.keyword"
      },
      "aggs": {
       "total" : {
         "sum": {
          "field": "data.amount"
        }
       }
      }
    }
  }
}

下面给出的查询结果不是预期的结果。

{
"id" : "abc",
"total" :1300
},
{
"id" : "def",
"total" :600
},
{
"id" : "ghi",
"total" :700
}

【问题讨论】:

    标签: elasticsearch elasticsearch-5


    【解决方案1】:

    您需要使用nested 聚合,并且您的字段类型data 应在映射中声明为nested

    否则 Elasticsearch 将对您的文档有以下视图:

    {
      "xid": "1234567",
      "time": "12/5/12 5:49 AM",
      "data.id": ["abc", "def"],
      "data.amount": [400, 200]
    }
    
    {
      "xid": "1234568",
      "time": "13/5/12 7:23 AM",
      "data.id": ["abc", "ghi"],
      "data.amount": [400, 300]
    }
    

    data 字段的新映射应如下所示:

    "data": {
      "type": "nested",
      "properties": {
        "id": {
          "type": "keyword"
        },
        "amount": {
          "type": "float"
        }
      }
    }
    

    现在您可以进行以下聚合:

    {
      "size": 0,
      "aggs": {
        "data": {
          "nested": {
            "path": "data"
          },
          "aggs": {
            "group_by_id": {
              "terms": {
                "field": "data.id"
              },
              "aggs": {
                "total": {
                  "sum": {
                    "field": "data.amount"
                  }
                }
              }
            }
          }
        }
      }
    }
    

    这是你将得到的结果:

    "buckets": [
      {
        "key": "abc",
        "doc_count": 2,
        "total": {
          "value": 800
        }
      },
      {
        "key": "def",
        "doc_count": 1,
        "total": {
          "value": 200
        }
      },
      {
        "key": "ghi",
        "doc_count": 1,
        "total": {
          "value": 300
        }
      }
    ]
    

    【讨论】:

    • 谢谢,我会尽力让您知道状态。
    猜你喜欢
    • 1970-01-01
    • 2021-09-01
    • 2015-09-24
    • 2023-01-10
    • 2017-06-11
    • 2019-04-24
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多