脚本
简单使用
POST product/_update/2
{"script": {"source": "ctx._source.salary+=1" #将薪水字段的值 + 1}
}
预定义变量
POST product/_update/2
{"script": {"lang": "painless","source": "ctx._source.salary+=params.num","params": {"num": 1}}
}
多行代码
下面脚本的意思是有这条数据就先 + num 然后乘scale,没有就插入这条数据。
POST product/_update/2
{"script": {"lang": "painless","source": """ #写在"""中多行代码ctx._source.salary+=params.num;ctx._source.salary*=params.scale;""","params": {"num": 1,"scale" : 2}},"upsert": {"name": "xiaomi nfc phone2","type": "c","price": 2999,"date": "2023-05-01","desc": "xiaomi 2023 new1","tags": ["88vip","tmall","newer"]}
}
动态字段
GET /product/_search
{"script_fields": {"or_price": {"script": {"source": "doc['salary'].value"}},"disc_price" : {"script" : {"source": "[doc['salary'].value * 0.9,doc['salary'].value * 0.8]"}}}
}
函数
定义一个全局函数,别人也可以使用。
全局函数里面不允许对文档直接进行赋值, “source”: “doc.salary.value += params.num” 这个+=就不行。
#定义函数
POST _scripts/myFun
{"script": {"lang": "painless","source": "[doc['salary'].value * 0.9,doc['salary'].value * 0.8]"}
}
#使用函数
GET /product/_search
{"script_fields": {"disc_price" : {"script" : {"id" : "myFun"}}}
}
带参数的引用
POST _scripts/calc_x
{"script": {"lang": "painless","source": "doc.salary.value + params.num"}
}
GET /product/_search
{"script_fields": {"disc_price" : {"script" : {"id" : "calc_x","params": {"num" : 10,"scale" : 10}}}}
}
更多用法
POST /product/_update/2
{"script": {"lang": "painless", "source": """ctx._source.tags.add("abc");"""}
}
for
POST /product/_update/2
{"script": {"lang": "painless", "source": """for (int i = 0; i < 3; i ++)ctx._source.tags.add("abc" + i);"""}
}
if
POST /product/_update/3
{"script": {"lang": "painless","source": """if (ctx._source.name ==~ /liyong.*/) {ctx._source.salary += 1000;} else {#不可以省略ctx.op = "noop";}"""}
}
综合使用
先筛选出salary >1801000的数据,然后再聚合中使用脚本进行聚合
get product/_search
{"query": {"constant_score": {"filter": {"range": {"salary": {"gt": 1801000}}}}},"aggs": {"tag_agg": {"sum": {"script": {"source": "doc['tags.keyword'].length"}}}}
}