ErickSkrauch
ErickSkrauch

Reputation: 81

ElasticSearch: query nested objects, that match filter

I have such index:

{
  "id":2,
  "name":"test home",
  "city_id":"31",
  "county_id":"1",
  "zip_code":"123",
  "residencePlans":[
    {
      "id" : 1,
      "unit_price_from":480240,
      "bathrooms_count":3,
      "interior_area_sqrft":23,
      "floor_range_hight":5,
      "bedrooms_count":5,
      "elevator_type_id":4,
      "price_psqft":3756,
    },
    {
      "id" : 2,
      "unit_price_from":123456,
      "bathrooms_count":1,
      "interior_area_sqrft":12,
      "floor_range_hight":4,
      "bedrooms_count":2,
      "elevator_type_id":3,
      "price_psqft":1234,
    }
  ],
}

And then I use some filters. Some of them are applied to the top object, and some to nesting.

I need to query residencePlans, that match filter, applied for their. eg filter on residencePlans.bathrooms_count >= 3 should return only residence with id = 1 and not 2.

{
  "id": [2],
  "residencePlans.id": [1]
}

I marked residencePlans as nested mapping, but it doesn't help.

Upvotes: 3

Views: 214

Answers (1)

Jim Edelstein
Jim Edelstein

Reputation: 792

Checkout the documentation here: https://www.elastic.co/guide/en/elasticsearch/guide/current/nested-query.html

And here: https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-inner-hits.html

Something like this should do it

{
  "query": {
    "bool": {
      "must": [
        { "match": { "id": 1 }}, 
        {
          "nested": {
            "path": "residencePlans", 
            "query": {
              "bool": {
                "must": [ 
                  { "gte": { "residencePlans.unit_price_from": 3 }}
                ]
               }
             }
           }
         }
       ]
     },
     inner_hits: {}
   }
 }

I've revised my answer to take into account the particulars of filtering your top level document and your nested documents. Please let me know if it works for you!

Upvotes: 2

Related Questions