3

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.

2
  • Do you mean residencePlans.unit_price_from >= 300000 ? Both residencePlans in your example have a "unit_price_from" greater than 3. Commented Feb 22, 2016 at 21:22
  • My typo. I mean bathrooms_count. Commented Feb 23, 2016 at 8:39

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

8 Comments

Yes, in this case I will get full document, but I need exctly id of top doc and residencePlans ids, that match this filter.
Just to be clear, the issue is that you aren't getting the matching residence plans included in the result?
Opposite: I getting all residence plans, but want only matching.
I've added an example of the expected result
Great question, answer revised to including inner_hits, please let me know if it works for you.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.