Append object to array if not exists elasticsearch

Viewed 548

I have the following code

body: {
    script: {
        source: 'ctx._source.permissions.add(params.permission);',
        params: {
            permission
        }
    }
}

Permission object is an object being appended to array of permissions. Permission object will have some id property. So permission object would be something like:

{
  id: 'some unique value',
  name: 'permission name
}

How do I only add it, if there is no permission object in that array with the property id, so If that array has an object with the params.id value I am trying to add, the add should fail...

1 Answers

Try Below source :

"source":"List perm=ctx._source.permissions; if(perm!=null && !perm.stream().anyMatch(p-> p.id.equals(params.permission.id))){ctx._source.permissions.add(params.permission)}

I would advice you go through painless document.

Related