Merge 2 maps into single map


(Leela Kumili) #1

Hi,

Can someone help me how can I merge 2 maps into single map using painless script in watcher transform?

I am building 2 maps where first map has data like this:

[
{
"src": "A",
"earlier": 34905
},
{
"src": "B",
"earlier": 494
}
]

and second map has data like this:

[
{
"src": "A",
"latest": 4685
},
{
"src": "B",
"latest": 765
}
]

Now i want to merge both of them as single map resulting in

[
{
"src": "A",
"earlier": 34905,
"latest": 4685
},
{
"src": "B",
"earlier": 494,
"latest": 765
}
]

Here is sample transform script:

"transform": {
"script": {
"lang": "painless",
"source": "def firstmap=ctx.payload.aggregations.range.buckets.earlier.by_source.buckets.stream().map(p ->['src':p.key,'earlier':p.total.value]).collect(Collectors.toList());def secondmap=ctx.payload.aggregations.range.buckets.latest.by_source.buckets.stream().map(p ->['src':p.key,'latest':p.total.value]).collect(Collectors.toList());"
}
}


(Alexander Reelsen) #2

please format your code snippets properly to make them easier to read. This forum supports markdown, so it is super easy to do so and will help others reading your questions a lot. Thanks!

There is a Map.merge() method you could take a look at. alternatively you could just write the whole logic yourself (which might make it easier to understand).

There are no painless helpers to do that. The reason for this, that it is super hard to know how a merge should happen. Should duplicate values overwrite, removed, or a calculation happening? It depends on the use-case and would be super hard to add logic for all these cases.

--Alex


(system) #3

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