# Sorting on nested fields containing null values in elasticsearch

**URL:** <https://discuss.elastic.co/t/sorting-on-nested-fields-containing-null-values-in-elasticsearch/193544>\
**Category:** Elasticsearch\
**Created:** [August 2, 2019, 1:40pm UTC](https://discuss.elastic.co/t/sorting-on-nested-fields-containing-null-values-in-elasticsearch/193544 "2019-08-02T13:40:21Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![sakshi\_malik](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/sakshi_malik/32/51529_2.png) [@sakshi\_malik](https://discuss.elastic.co/u/sakshi_malik)\
**Post date:** [August 2, 2019, 1:40pm UTC](https://discuss.elastic.co/t/sorting-on-nested-fields-containing-null-values-in-elasticsearch/193544/1 "2019-08-02T13:40:21Z")

</div>

I am trying to sort on nested field in elasticsearch, but it is always showing docs with null valued nested field at the top of the sorted list while sorting in ascending order. I want to sort (in ascending as well as descending order) and want the null valued nested field docs to appear at the end of the sorted list.

This is the sorting query I am using :

```
{
  "query": {
    "match_all": {}
  },
  "sort": {
    "_script": {
      "type": "string",
      "order": "asc",
      "script": {
        "lang": "painless",
        "source": "def val=params['_source'].tags; if(val==null){return '';}else{return params['_source'].tags} "
      }
    }
  }
}

```

Below is the mapping I have applied related to the nested 'tags' field:

```
"tags": {
            "type": "nested",
            "properties": {
              "tag": {
                "type": "text",
                "fields": {
                  "keyword": {
                    "type": "keyword",
                    "ignore_above": 256
                  }
                },
                "analyzer": "index_analyzer",
                "search_analyzer": "search_analyzer"
              }
            }
          }

```

Sample payload:

```
"tags": [
  {
    "tag": "check"
  },
  {
    "tag": "production"
  },
  {
    "tag": "test"
  }
]
```

---

<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:** [August 30, 2019, 1:40pm UTC](https://discuss.elastic.co/t/sorting-on-nested-fields-containing-null-values-in-elasticsearch/193544/2 "2019-08-30T13:40:21Z")

</div>

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