Elasticsearch filtering nested object

10,050
{
  "query": {
    "filtered": {
      "query": {
        "match_all": {}
      },
      "filter": {
        "bool": {
          "filter": [
            {
              "range": {
                "variants.price": {
                  "gte": 0
                }
              }
            },
            {
              "range": {
                "variants.price": {
                  "lte": 50
                }
              }
            },
            {
              "nested": {
                "path": "features",
                "query": {
                  "bool": {
                    "should": [
                      {"term":{"features.key":"type"}},
                      {"term":{"features.key":"city"}}
                    ]
                  }
                }
              }
            }
          ]
        }
      }
    }
  }
}
Share:
10,050
CptnKrunch
Author by

CptnKrunch

Updated on June 20, 2022

Comments

  • CptnKrunch
    CptnKrunch almost 2 years

    I have a simplified object that looks something like this:

    "name" : "Partner Name",
    "features" : [ 
        {
            "val" : "Family",
            "key" : "Type"
        },
        {
            "val" : "Paris",
            "key" : "City"
        }
    ],
    "variants" : [ 
        {
            "name" : "Activity 1 Name",
            "description" : "Quick description",
            "price" : 20
        }
    ]
    

    I want to filter by the City and Type keys. My current query filters by price but I can't get it working for City or Type. Adding more terms to the filter array didn't do the trick.

    'query':{
        'filtered':{
            'query':{
                'query_string':{
                    'query':query
                }
            },
        'filter': {
            'bool':{
                'filter': [{ 
                        'range': {
                            'variants.price': {
                                'gte': 0
                            }
                        }
                    },
                    { 
                        'range': {
                            'variants.price': {
                                'lte': 50
                            }
                        }
                    },
                    {
                        'term': {
                            'active': true
                        }
                    }
                ]
            }
         }
      }
    }
    

    Any help would be appreciated. Thanks!