Unique Array Elements in Painless Script

Hello!

I'm looking for a way to use Update API with painless script to turn the following record:

{
    "foo": [6,3,4,4,8,4,2,1]
}

into

{
    "foo": [1,2,3,4,6,8]
}

In other words, I would like to extract unique elements in field "foo", sort them, and replace the original field contents. How do I do this? Is there a comprehensive list of painless array functions that would be at least relatively up-to-date? I'm aware that it's still a language in development. Thanks!

Non-working examples - do not use

So far, I have tried a few different ideas, such as:

To sort:

{
"script" : {
"inline": "ctx._source.foo=ctx._source.foo.sort()"
}
}

To get unique:

{
"script" : {
"inline": "ctx._source.foo=ctx._source.foo.unique()"
}
}

To get unique (fingers crossed, thinking Java 8):

{
"script" : {
"inline": "ctx._source.foo=ctx._source.foo.distinct()"
}
}

1 Like

Sorted the sorting part, this seems to work

{
	"script" : {
		"inline": "ctx._source.foo=
                                 ctx._source.foo.stream().sorted()
                                        .collect(Collectors.toList())"
	}
}
3 Likes

And the final answer, unique and sorting:

{
	"script" : {
		"inline": "ctx._source.foo=
                               ctx._source.foo.stream().distinct().sorted()
                                          .collect(Collectors.toList())"
	}
}

Hope that helped somebody!

13 Likes

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.