0

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.

1
  • Do you want to sort inner hits? Commented Oct 31, 2022 at 2:57

1 Answer 1

1

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"
      }
    }
  ]
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your reply. I have a question, when you say to sort docs use, "nested.name": You actually meant, "files.name" right? Because, in the example asked, path is to "files" ...
@Sathya yes. For sorting all documents you need to use first syntax. For sorting inner hits within a returned document you need to use second query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.