Home > Software engineering >  Sort ES results based on fields inside nested array objects
Sort ES results based on fields inside nested array objects

Time:11-03

Here is my mapping snippet

{
      "mappings": {
        "properties": {
          "files": {
            "type": "nested",
            "properties": {
              "name": {
                "type": "keyword",
                "index": true
              },
              "type": {
                "type": "keyword",
                "index": true
              },
              "size": {
                "type": "keyword",
                "index": true
              },
              "version": {
                "type": "keyword",
                "index": true
              }
            }
          }
        }
      }
    }

And here is my document data snippet,

{
  "_index": "files_v1",
  "_type": "_doc",
  "_id": "1",
  "_score": null,
  "_source": {
    "hdd-size": "256GB",
    "files": [
      {
        "name": "AllOrNothing",
        "type": "pdf",
        "size": "1mb",
        "version": "1"
      },
      {
        "name": "FallOrNothing",
        "type": "zip",
        "size": "2mb",
        "version": "2"
      },
      {
        "name": "ZeroOrNothing",
        "type": "txt",
        "size": "1mb",
        "version": "2"
      }
    ]
  }
}

Now, If I need to sort the search results when I query for files based on fields such as 'name' or 'type' or even both such as 'name' asc and 'type' desc, I am unable to do so.

I have tried below but failed,

"sort": [{
        "files.name": {
            "order": "asc",
            "nested_path": "files"
        }
    }]

Please suggest what am I missing here! Thank you in advance.

CodePudding user response:

Nested filter returns documents with all nested fields. To sort on matched nested documents you need to specify nested filter in sort documents.

{
      "files.name": {
        "order": "asc",
        "nested": {
          "path": "files",
          "filter": {  ---> you can use bool to combine complex queries
            "term": {
              "files.type": "txt"
            }
          }
        }
      }
    }

To sort documents in inner_hits use below

"inner_hits":{
  "sort": [
    {
      "nested.name": {
        "order": "asc"
      }
    }
  ]
}
  • Related