Čamo
Čamo

Reputation: 4163

Elasticsearch nested query and sorting

can somebody help me to understand what Elastic means by nested. In documentations https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-sort.html#_nested_sorting_examples is an example which does not show how the document object looks like. It look like I should imagine the mapping from the search query. Query looks like:

POST /_search
{
   "query": {
      "nested": {
         "path": "parent",
         "query": {
            "bool": {
                "must": {"range": {"parent.age": {"gte": 21}}},
                "filter": {
                    "nested": {
                        "path": "parent.child",
                        "query": {"match": {"parent.child.name": "matt"}}
                    }
                }
            }
         }
      }
   },
   "sort" : [
      {
         "parent.child.age" : {
            "mode" :  "min",
            "order" : "asc",
            "nested": {
               "path": "parent",
               "filter": {
                  "range": {"parent.age": {"gte": 21}}
               },
               "nested": {
                  "path": "parent.child",
                  "filter": {
                     "match": {"parent.child.name": "matt"}
                  }
               }
            }
         }
      }
   ]
}

Can somebody write a document structure on which this query will work?

Upvotes: 0

Views: 3186

Answers (2)

Siddu
Siddu

Reputation: 156

In Elastic nested means it's an array of objects. To store an array of objects into a field in elastic search you have to map the field to a nested while creating the index.

PUT parent
       {
       "mappings": {
        "doc":{
      "properties": {
        "name":{
          "type": "text"
        },
        "age":{
          "type": "integer"
        },
        "child":{
          "type": "nested",
          "properties": {
            "name":{
              "type":"text"
            },
            "age":{
              "type":"integer"
            }
          }

        }
      }
    }
  }
}

and a sample nested document cab be inserted like this

POST parent/doc
{
  "name":"abc",
  "age":50,
  "child":[
    {
      "name":"son1",
      "age":25
    },
    {
      "name":"adughter1",
      "age":20
    }
    ]
}

Upvotes: 1

nitzien
nitzien

Reputation: 1267

Something like this.

{
    "parent": {
        "name": "Elasti Sorch",
        "age": 23,
        "child": [
           {
              "name": "Kibana Lion",
              "age": 12
           }, 
           {
              "name": "Matt",
              "age": 15
           }
        ] 
    }
}

Upvotes: 1

Related Questions