Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting and paging nested documents

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?

like image 423
Taras Kohut Avatar asked Jul 17 '16 15:07

Taras Kohut


1 Answers

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"}
            } 
        }
    }
}
like image 104
Val Avatar answered Oct 01 '22 19:10

Val