用以上code去update ctr, 然后发现log中出现了too many dynamic script rejected,导致ctr更新失败。
寻找原因
在ES官网上查找Script相关的文档说明,在Script Parameters栏目发现以下参数
lang
Specifies the language the script is written in. Defaults to painless. 指定编写脚本的语言,默认为painless。
source, id
Specifies the source of the script. An inline script is specified source. A stored script is specified id and is retrieved from the cluster state. 指定脚本的来源。inline类型的脚本是指定source。stored类型的脚本是指定source的id,通过id从ES集群上检索对应的source。
params
Specifies any named parameters that are passed into the script as variables. 指定作为变量传递到脚本的任何参数。
然后在这个下面的一段话,很重要,就是解决我们问题的关键信息
The first time Elasticsearch sees a new script, it compiles it and stores the compiled version in a cache. Compilation can be a heavy process.
If you need to pass variables into the script, you should pass them in as named params instead of hard-coding values into the script itself. For example, if you want to be able to multiply a field value by different multipliers, don’t hard-code the multiplier into the script:
POST _scripts/ctr_calc{"script": {"lang":"painless","source":"ctx._source.click_count=params.click_count;ctx._source.impr_count=params.impr_count;ctx._source.ctr=(double)ctx._source.click_count/ctx._source.impr_count*100" }}
结果
通过以上两种方法,都可以解决too many dynamic script rejected的问题。