# Search results to contain only first element of an array field

**URL:** https://discuss.elastic.co/t/search-results-to-contain-only-first-element-of-an-array-field/136525
**Category:** Elasticsearch
**Created:** [June 19, 2018, 3:28pm UTC](https://discuss.elastic.co/t/search-results-to-contain-only-first-element-of-an-array-field/136525 "2018-06-19T15:28:03Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![Pyppe](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/pyppe/32/3531_2.png) [@Pyppe](https://discuss.elastic.co/u/Pyppe)
#### Post date: [June 19, 2018, 3:28pm UTC](https://discuss.elastic.co/t/search-results-to-contain-only-first-element-of-an-array-field/136525/1 "2018-06-19T15:28:04Z")

</div>

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:

```json
{
  "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!

---

<div class="post-metadata">

### Author: ![Pyppe](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/pyppe/32/3531_2.png) [@Pyppe](https://discuss.elastic.co/u/Pyppe)
#### Post date: [June 19, 2018, 3:35pm UTC](https://discuss.elastic.co/t/search-results-to-contain-only-first-element-of-an-array-field/136525/2 "2018-06-19T15:35:09Z")

</div>

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

```json
"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?

---

<div class="post-metadata">

### Author: ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)
#### Post date: [July 17, 2018, 3:35pm UTC](https://discuss.elastic.co/t/search-results-to-contain-only-first-element-of-an-array-field/136525/3 "2018-07-17T15:35:15Z")

</div>

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