Task1
数据
索引Task1
保存了公安案件的嫌疑人信息
PUT test_index/_bulk?refresh
{"index": {"_id": 1}}
{"ajbh":"12345","ajmc":"li'an'an'jian","lasj":"2020/05/21 13:25:23","jsbax_sjjh2_xz_ryjbxx_cleaning":[{"XM":"zhangsan","NL":"30","SF":"nan"},{"XM":"lisi","NL":"31","SF":"nan"},{"XM":"wangwu","NL":"30","SF":"nv"},{"XM":"zhaoliu","NL":23,"SF":"nan"}]}
{"index":{"_id":2}}
{"ajbh":"563245","ajmc":"jie'an'shi'jian","lasj":"2020/05/21 13:25:23","jsbax_sjjh2_xz_ryjbxx_cleaning":[{"XM":"zhangsan2","NL":"30","SF":"nan"},{"XM":"lisi2","NL":"31","SF":"nan"},{"XM":"wangwu2","NL":"30","SF":"nv"},{"XM":"zhaoliu2","NL":"23","SF":"nv"}]}
{"index":{"_id":3}}
{"ajbh":"12345","ajmc":"li'an'an'jian","lasj":"2020/05/21 13:25:23","jsbax_sjjh2_xz_ryjbxx_cleaning":[{"XM":"zhangsan3","NL":"30","SF":"nan"},{"XM":"lisi3","NL":"31","SF":"nan"},{"XM":"wangwu3","NL":"30","SF":"nv"},{"XM":"zhaoliu3","NL":"23","SF":"nan"}]}
要求:
- 统计nan性嫌疑人的数量(注意,是统计嫌疑人数量,而不是文档数量,结果应为 8 )
答案:
GET test_index/_search
{
"size": 0,
"aggs": {
"nan_xianyifan_count": {
"sum": {
"script": {
"lang": "painless",
"source": """
int count = 0;
for(int i=0;i<params['_source']['jsbax_sjjh2_xz_ryjbxx_cleaning'].length;i++){
if(params['_source']['jsbax_sjjh2_xz_ryjbxx_cleaning'][i]['SF'] == 'nan'){
count++;
}
}
return count;
"""
}
}
}
}
}
Task2
要求
创建一个名为calculate_discount
的脚本模板,计算一个新的discount_price
, 其值为打折后的价钱,
使用脚本模板分别计算并输出product
索引中商品的原价price
,9折、8折的价格。
答案:
POST _scripts/calculate_discount
{
"script": {
"lang": "painless",
"source": "doc['price'].value * params['discount']"
}
}
GET product/_search
{
"script_fields": {
"source_price": {
"script": {
"id": "calculate_discount",
"params": {
"discount": 1
}
}
},
"9_discount_price": {
"script": {
"id": "calculate_discount",
"params": {
"discount": 0.9
}
}
},
"8_discount_price": {
"script": {
"id": "calculate_discount",
"params": {
"discount": 0.8
}
}
}
}
}
总结
对于scripting 坑还是比较多的
大部分在 两种语言上 painless 和 expression
- expression 可能会写成 expressions
- 在进行计算时 painless计算必须带value 而 expression 则带不带都行
- 在使用 params时,painless可以使用params.参数名称 或 params['参数名称'] 而 expression则需要直接xxx
- 在update中 要使用ctx上下文来调用原字段
- 查询时 要使用 doc['字段'] (注意这里必须加单引号), 对于复杂的类型 要使用 params['_source']['字段']