es版本是2.1.2(比较老的版本了)
索引有8个分片
做聚合查询使用脚本对两个聚合字段做除法处理
{
"size": 0,
"query": {
"bool": {
"must": [
{
"term": {
"lvl": 7
}
},
{
"terms": {
"dt": [
"2019-09-01",
"2019-09-02",
"2019-09-03",
"2019-09-04",
"2019-09-05"
]
}
},
{
"terms": {
"buId": [
"1726"
]
}
}
]
}
},
"aggregations": {
"dt": {
"terms": {
"field": "dt"
},
"aggregations": {
"deptId1": {
"terms": {
"field": "deptId1",
"size": 0
},
"aggregations": {
"storageRatio": {
"avg": {
"script": {
"inline": "if (doc['inspQtty'].value == 0) val = 0; else val = doc['outWhSaleQtty'].value / doc['inspQtty'].value; return val"
}
}
}
}
}
}
}
}
}
主要看script里的脚本内容是通过doc['xxx'].value方式取字段值得,这样执行就会报错:
{
"took" : 14,
"timed_out" : false,
"_shards" : {
"total" : 8,
"successful" : 4,
"failed" : 4,
"failures" : [ {
"shard" : 1,
"index" : "app_supply_global_purchase_daily",
"node" : "NlWR-tGoQ7y6wlonWp1mBQ",
"reason" : {
"type" : "groovy_script_execution_exception",
"reason" : "failed to run inline script [if (doc[inspQtty].value == 0) val = 0; else val = doc[outWhSaleQtty].value / doc[inspQtty].value; return val] using lang [groovy]",
"caused_by" : {
"type" : "missing_property_exception",
"reason" : "No such property: inspQtty for class: 84c39ed31f7ac7aad63d352da0c010bddc68c7a5"
}
}
} ]
},
"hits" : {
"total" : 0,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
"dt" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [ ]
}
}
}
这里reason中错误提示:“No such property: inspQtty for class:”就是groovy脚本找不到inspQtty字段,但是这个字段是存在的。最后通过尝试才找到原因是groovy脚本取字段方式问题
需要换成doc[\"xxxx\"]方式取字段,需要加转义字符"\",因为这个是在Java里执行的脚本。