TransWikia.com

Sorting and paging nested documents

Stack Overflow Asked by Taras Kohut on January 14, 2021

Elasticsearch has out of the box support of sorting and pagination. But what if I want to retrieve only nested objects, paginate them and sort by it’s field?
For example:

{
  "mappings" : {
    "library" : {
      "properties" : {
        "name" : {"type": "string"},
        "books" : {
          "type": "nested",
          "properties" : {
            "title" : {"type": "string"},
            "author" : {"type": "string"},
            "year" : {"type": "integer"}
          }
        }
      }
    }
  }
}

How can I ask Elasticsearch: “give me first 10 books with offset = 20 with title= 'Elasticsearch' sorted by year“? Is it possible with nested type, or I should use slower parent-child relationship?

2 Answers

I figured out that it's not possible to sort and paginate nested documents. This topic proves it https://discuss.elastic.co/t/nested-objects-hits-inner-hits-and-sorting/32565.

Correct answer by Taras Kohut on January 14, 2021

Yes, that's possible, you can use nested inner hits to achieve what you want:

POST index/library/_search
{
    "query" : {
        "nested" : {
            "path" : "books",
            "query" : {
                "match" : {"books.title" : "Elasticsearch"}
            },
            "inner_hits" : {
                "from": 20,
                "size": 10,
                "sort": {"books.year": "asc"}
            } 
        }
    }
}

Answered by Val on January 14, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP