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"
}
]