When using es to perform the following update operations recently:
POST customer/customer_info/_update_by_query
{
"query": {
"bool": {
"filter": [
{
"term": {
"data_type": {
"value": 1
}
}
},
{
"terms": {
"customer_id": [
"101320130050"
]
}
}
]
}
},
"script": {
"source": """
if(!ctx._source.customer_group.contains(params.val)) {
ctx._source.customer_group.add(params.val)
}""",
"params": {
"val": "22347"
}
}
}
Script description: First query the document whose data_type is 1 and customer_id is 101320130050, and then if the document's array customer_group does not contain 22347, add 22347 to customer_group.
Run error:
dynamic method [java.lang.String,add/1] not fond
Later, the reason for the investigation was because the customer_group was empty or the array element was 0 . Simply put, the document whose data_type is 1 and customer_id is 101320130050 does not have the customer_group field, or there is no element in the customer_group array, just like "customer_group":[]
Looking up the information, it is found that es uses script to determine that it is empty and the element is equal to 0. You can write it like this:
ctx._source.customer_group==null||ctx._source.customer_group?.size() ==0
或者:
ctx._source.customer_group==null||ctx._source.customer_group.length==0
The modified dsl statement is as follows:
POST customer_v2023/customer_info/_update_by_query
{
"query": {
"bool": {
"filter": [
{
"term": {
"data_type": {
"boost": 1,
"value": 1
}
}
},
{
"terms": {
"boost": 1,
"customer_id": [
"101320130050"
]
}
}
],
"adjust_pure_negative": true,
"boost": 1
}
},
"script": {
"source": """
if(ctx._source.customer_group==null||ctx._source.customer_group?.size() ==0) {
ctx._source.customer_group=[params.val]
} else if(!ctx._source.customer_group.contains(params.val)) {
ctx._source.customer_group.add(params.val)
}
""",
"params": {
"val": "22347"
}
}
}
Script description: If customer_group is empty or the elements in it are 0, assign 22347 directly to customer_group, otherwise if customer_group does not contain 22347, add 22347 to customer_group.
Others on the Internet, such as judging by doc['xxx'].length or doc['fieldname'].values.length, have failed the test, which may be related to different versions of es:
"script": {
"source": "doc['xxx'].length==0",
"lang": "painless"
}
Regarding elasticsearch's script to determine whether the field is empty and the size of the element, refer to other URLs:
elasticsearch filtering by the size of a field that is an array
elasticsearch filter by length of a string field
Script queryedit