Obtain last 2 elements of nested object and perform logic on them

Hello all,

I've been reading ES docs, SO and this forums' posts about this for the past 2 days, but I can't seem to figure it out.

Given this data structure, which is a part of a bigger data structure that represents a user:

"reviews": [
            {
              "userEmail": "user1@email.com",
              "time": "2019-07-31T00:28:21.988315333Z",
              "userName": "User 1",
              "user": "1",
              "fieldIWantToCompare": 1
            },
            {
              "userEmail": "user2@email.com",
              "time": "2019-07-31T00:28:21.988315333Z",
              "userName": "User 2",
              "user": "2",
              "fieldIWantToCompare": 0
            },
            {
              "userEmail": "user3@email.com",
              "time": "2019-07-31T00:28:21.988315333Z",
              "userName": "User 3",
              "user": "3",
              "fieldIWantToCompare": 1
            }
            ...
          ]

reviews is a nested object.

How can I (if even possible at all) select the last 2 elements of this nested object to then perform some logic on their fields? What I want to do is compare a field on the last object and the penultimate object, and if they're not the same AND match a parameter, I want the query to filter the whole bigger structure in.

Here's a snippet of (Go) code that outlines what I'd do to get what I want on a normal application.
This is essentially what I want to do in ES:

previous := reviews[len(reviews) - 2]
current := reviews[len(reviews) - 1]

if previous.fieldIWantToCompare == <some_parameter_here> && previous.fieldIWantToCompare != current.fieldIWantToCompare {
    return true // The whole user would be returned by the query.
}

I've tried using scripts to get the length of fields but I can't seem to make it work as this is a nested object and I don't think I fully understand how they work.
I know they're flattened by ES like so:

{
"reviews.userEmail" : ["user1@email.com", "user2@email.com", "user3@email.com"],
"reviews.userName": ["User 1", "User 2", "User 3"]
...
}

But I don't understand how to access the lengths of these arrays or how to access their data, essentially by array index.

Thanks!

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