Compare two arrays of json object in painless

220 Views Asked by At

Trying to compare 2 arrays that contains json objects in painless (elastic)

A: [{"key":"a1"},{"key":"a2"},{"key":"a3"},{"key":"a4"},{"key":"a5"}]
B: [{"key":"a1"},{"key":"a3"},{"key":"a4"}]

and receive on exit array that contains only unique values:

C: [{"key":"a2"},{"key":"a5"}]

It could be a new array (C) or updated A (array B could be same by size or smaller)

Tried Arrays.asList with remove but stuck with compile errors and not sure if it wrong syntax or approach.

C = Arrays.asList(ctx.payload.A).removeALL(Arrays.asList(ctx.payload.B))
1

There are 1 best solutions below

0
Aman Chauhan On

Following script should do the job:

Set setB = ctx.payload.B.stream().map(obj -> obj.key).collect(Collectors.toSet());
List C = ctx.payload.A.stream().filter(obj -> !setB.contains(obj.key)).collect(Collectors.toList());

I've utilized Java8 streams for shortness. You can read more about it here.