【问题标题】:ElasticSearch sum up nested object fieldElasticSearch 总结嵌套对象字段
【发布时间】:2020-10-01 20:31:14
【问题描述】:

我有一个嵌套字段,我想使用脚本总结该嵌套对象的值。我不能使用聚合,因为这个求和是为范围过滤完成的。

我的映射:

    {
      "_doc" : {,
        "properties" : {
          "searchPrices" : {
            "type" : "nested",
            "properties" : {
              "price" : {
                "type" : "double"
              },
              "type" : {
                "type" : "keyword"
              }
            }
          }
        }
      }
    }

我尝试的查询:

{
  "size": 100,
  "query": {
    "bool": {
      "must": [
        
        {
          "nested": {
            "path": "searchPrices",
            "query": {
              "bool": {
                "must": [
                  {
                    "script": {
                      "script": """
                        int sum = 0;
                        for (obj in doc['searchPrices.price']) {
                          sum = sum + obj;
                        } 
                        sum >= 200;"""
                    }
                  },
                  {
                    "term": {
                      "searchPrices.type": "recurringPrice"
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}

问题是这个脚本只选择第一个嵌套文档,而不管文档中有多个搜索价格。

示例文档:

        {
          "id" : "v2",
          "searchPrices" : [
            {
              "price" : 2000,
              "type" : "recurringPrice",
            },
            {
              "price" : 200,
              "type" : "recurringPrice",
              "conditions" : [
                "addon1"
              ]
            },
            {
              "price" : 400,
              "type" : "recurringPrice",
              "conditions" : [
                "addon2"
              ]
            }
          ]
        }

所以,不考虑2600的价格,只考虑2000的价格。

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    不幸的是,这似乎无法通过无痛脚本实现。

    根据 Elastic Team Member 回答的Help for painless iterate nested fields 文档,在查询时使用无痛脚本一次只能访问一个嵌套对象。

    所以,你遭受的情况——只考虑 2000 作为价格——是很自然的。

    【讨论】:

    • 是的,阅读更多内容后我意识到这很自然。但找不到解决方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 2021-10-18
    • 2015-07-30
    相关资源
    最近更新 更多