Unique Array Elements in Painless Script


(LeFinc) #1

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()"
}
}


Sorting comblex Array elements with Painless script
(LeFinc) #2

Sorted the sorting part, this seems to work

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

(LeFinc) #3

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!


(system) #4

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