ElasticSearch-使用script_fields添加一个带有条件的新参数



逻辑:添加一个参数来显示当前用户喜欢该产品的产品,供Front-end处理。(需要user_id的参数(

映射方法:

{"mappings": { "properties": {
"name_product": {"type": "text"},
"price": {"type":"long"},
"user_who_like":{"type":"text"}
}            }               }

样本数据:

{
"name_product": "ABC",
"price": 320,
"user_who_like": ["a2","a1"]    #id of people who liked this product before
}

预期结果:

{
"name_product": "ABC",
"price": 320,
"user_who_like": ["a2","a1"],
"liked": true                   //the current user did like this product
}
{
"name_product": "EDF",
"price": 320,
"user_who_like": ["a2"],
"liked": false                  //the current user did not like this product
}

在查找了这么多资源后,我迄今为止最好的尝试:

{
"query": {"bool": {"must": [{"match_all": {}}]}}
,
"script_fields": {
"info": {
"script": "params['_source']"
},
"is_like": {
"script": {
"params": {
"my_id": "a1"
},
"source": "if (doc['user_who_like'].size()!= 0) 
{
for (id_index in doc['user_who_like']) 
{if id_index == params.my_id {return true} else {return false}
} 
else 
{
return false
}"
}
}
}
}

不工作,给我这个错误:

"root_cause": [
{
"type": "script_exception",
"reason": "compile error",
"script_stack": [
"... oc['user_who_like']) {if id_index == params.my_id  ...",
"                             ^---- HERE"
],
"script": "if (doc['user_who_like'].size()!= 0) {for (id_index in doc['user_who_like']) {if id_index == params.my_id {return true} else {return false}} else {return false}}",
"lang": "painless",
"position": {
"offset": 81,
"start": 56,
"end": 106
}
}
],

别忘了用括号包装if条件:

if id_index == params.my_id

|
|
v
if (id_index == params.my_id) 

最新更新