elasticsearchelasticsearch-queryelasticsearch-nested

ElasticSearch simple query


I have structure like this in my ElasticSearch

{
        _index: 'index',
        _type: 'product',
        _id: '896',
        _score: 0,
        _source: {
          entity_id: '896',
          category: [
            {
              category_id: 2,
              is_virtual: 'false'
            },
            {
              category_id: 82,
              is_virtual: 'false'
            }
          ]
        }
      }

I want return all "producs" that have "82" category_id.

{
  "query": {
    "bool": {
      "filter": {
        "terms": {
          "category.category_id": [
            82
          ]
        }
      }
    }
  }
}

This query gives me 0 hits.

What is right way to do this?


Solution

  • Adding working example, you need to define the category as nested field and modify your search query by including the nested path

    Index Mapping

    {
        "mappings": {
            "properties": {
                "entity_id": {
                    "type": "text"
                },
                "category": {
                    "type": "nested"
                }
            }
        }
    }
    

    Index your document

    {
        "entity_id": "896",
        "category": [
            {
                "category_id": 2,
                "is_virtual": false
            },
            {
                "category_id": 82,
                "is_virtual": false
            }
        ]
    }
    

    Proper search query, note we are using nested query which doesn't support normal filter(so your query gives error)

    {
        "query": {
            "nested": {
                "path": "category",
                "query": {
                    "bool": {
                        "must": [
                            {
                                "match": {
                                    "category.category_id": 82
                                }
                            }
                        ]
                    }
                }
            }
        }
    }
    

    Search result retuns indexed doc

     "hits": [
                {
                    "_index": "complexnested",
                    "_type": "_doc",
                    "_id": "1",
                    "_score": 1.0,
                    "_source": {
                        "entity_id": "896",
                        "category": [
                            {
                                "category_id": 2,
                                "is_virtual": false
                            },
                            {
                                "category_id": 82,
                                "is_virtual": false
                            }
                        ]
                    }
                }
            ]