How can i make that query? is that a nested query?

Hi people,

I want to make a query for car with price between 50000 and 100000.
from that json:

[{
	"_id": "aaa",
	"_source": {
		"objs": [{
				"name": "car",
				"price": 60000
			},
			{
				"name": "milk",
				"price": 2
			}
		]
	}
}, {
	"_id": "bbb",
	"_source": {
		"objs": [{
				"name": "car",
				"price": 20000
			},
			{
				"name": "truck",
				"price": 75000
			}
		]
	}

}]

If i use match : "car" with range of price gte 50000 and lte 100000 it will return the both _ids but the correct will be only _id: "aaa".

Making some search i found that: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-nested-query.html

is that is correct to my use? have others way without change the mapping to make that query?

Can anyone have some examples of how can i do that?

Appreciate any help

1 Like

Very simple!

You are to created a nested type of mapping for "objs" field.
You can check more info here: https://www.elastic.co/guide/en/elasticsearch/reference/current/nested.html

  1. First you have create a nested field:

    PUT /my_index/_mapping
     {
        "properties": {
          "objs": {
            "type": "nested" 
          }
        }
      }
  1. Then you add an object normally as if you didn´t had this mapping

  2. Now you just make a query of nested type:

GET my_index/_search
{
  "query": {
    "nested": {
      "path": "objs",
      "query": {
        "bool": {
          "must": [
            { "match": { "objs.name": "car" }},
            { "match": { "objs.price":  "6000" }} 
          ]
        }
      }
    }
  }
}
3 Likes

Hey spdoes,

That solution shiny my day, i can imagine that was possible to do like that. i have been using an old guide.

thanks so much, have a nice day :slight_smile:

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.