Search results to contain only first element of an array field

Hi there.

I want to limit the search result JSON, so that for a particular (nested) field — that is an array — only the first element (if one exists) is returned. I guess the _source filtering doesn't support this. I tried painless, but cannot figure out how to handle the case when the array is empty:

{
  "query": {...},
  "script_fields": {
    "firstElement": {
      "script": {
        "lang": "painless",
        "source": "params['_source'].parent.arrayThatMightBeEmpty[0]"
      }
    }
  }
}

So this will work, as long as the arrayThatMightBeEmpty contains elements, but will fail at runtime, if any search result contains an empty array.

How can this be solved?

Thanks!

1 Like

OK, thanks for rubber ducking, at least the following works:

"source": "params['_source'].parent.arrayThatMightBeEmpty.stream().findFirst().orElse(null)"

But I'd still prefer to return null or the actual element. Instead of an array. E.g. [null]. Any tips?

1 Like

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