在Elasticsearch的Painless脚本参数中传递一个动态值

hlswsv35  于 2022-11-02  发布在  ElasticSearch
关注(0)|答案(1)|浏览(291)

我在无痛脚本中传递参数map,该map的类型为<String, Long>。map的键定义了id,值定义了epoch Long中的foundDate
弹性文档的原始结构如下:

doc:{
     [ "id":11406, // type:Long
      "lastFixed": 1666015888000 // type epoch millis
     ]  // ...mutiple ids and their lastFixed Dates
}

我已经计算了foundDatelastFixed之间的平均差异(两者都在历元中)。
我已经构建了ES Painless脚本,如下所示:

"script": {
              "source": "(doc['lastFixed'] - params[doc['id']] )/ (1000*60*60)",
              "lang": "expression",
              "params": {
                "11406": 1614084531000,
                "11473": 1073523856000,
                "11549": 1447461154000,
                "43904": 1666015887000,
                "43905": 1666015887000,
                "43906": 1666015887000,
                "43907": 1666015887000,
                "43908": 1666015888000,
                "43909": 1666015888000,
                "43910": 1666015888000
                }
            }

对于idlastFound日期数组的嵌套,我使用nest-path-aggr-name,即嵌套路径。
我想在paramsMap中传递动态值,因为它将从Elasticsearch文档中的同一个id的Map中给出foundDate
但是我从ES中得到了解析错误。我已经厌倦了param.doc['id']param[],但是两者都在下降并给出解析错误。
在params map中传递动态值的正确方法是什么。

rkkpypqq

rkkpypqq1#

以下是基于我对您的问题的理解
我已经假设以下Map为您的文档。

PUT index-name
{
  "mappings": {
    "properties": {
      "nested_field":{
        "type": "nested"
      }
    }
  }
}

在您的问题中,我认为nested_field是nested类型。

示例文档

POST index-name/_doc
{
  "nested_field": [
    {
      "id": 11406,
      "lastFixed": 1666015888000
    },
    {
      "id": 11407,
      "lastFixed": 1666015888000
    }
  ]
}

我正在使用nested aggregation访问嵌套字段。

查询

{
  "size":0,
  "aggs": {
    "nest-path-aggr-name": {
      "nested": {
        "path": "nested_field"
      },
      "aggs": {
        "average_agg": {
          "avg": {
            "script": {
              "source": """
                    for(entry in params.entrySet())
                    {
                      if (entry.getKey() == doc['nested_field.id'].value.toString())
                      {
                        return ( doc['nested_field.lastFixed'].value -  entry.getValue())/ (1000*60*60); 
                      }
                    }
                      return 0;
                  """,
              "params": {
                "11406": 1614084531000,
                "11473": 1073523856000,
                "11549": 1447461154000,
                "43904": 1666015887000,
                "43905": 1666015887000,
                "43906": 1666015887000,
                "43907": 1666015887000,
                "43908": 1666015888000,
                "43909": 1666015888000,
                "43910": 1666015888000
              }
            }
          }
        }
      }
    }
  }
}

相关问题