Search code examples
elasticsearchelasticsearch-dsl

Elastic search , And operator , Nested fields


I have a document some thing like { "name": "abc", "age": "20", "attributes": [{ "city": "NEW YORK" }, { "city": "NEW JERSEY" } ] }

and i want a query to return NO record if i search with YORK JERSEY. i have used the "and" operator and it doesnt work since am searching on the same field and not multiple fields since york and jersey is present in both places , its giving me back 2 records , any thoughts ? and i also read about Nested fields but it requires reindexing of data , so any solution with out reindexing the data ?


Solution

  • Arrays of objects do not work as you would expect: you cannot query each object independently of the other objects in the array. If you need to be able to do this then you should use the nested data type instead of the object data type.

    Refer to this ES official document on Arrays to get a detailed explanation, and please refer to this SO answer.

    Adding a working example with index data, mapping, search query, and search result

    You have to reindex your data, after applying nested data type

    Index Mapping:

    {
      "mappings":{
        "properties":{
          "attributes":{
            "type":"nested"
          }
        }
      }
    }
    

    Index Data:

    {
      "name": "abc",
      "age": "20",
      "attributes": [
        {
          "city": "NEW YORK"
        },
        {
          "city": "NEW JERSEY"
        }
      ]
    }
    

    Search Query:

    {
        "query": {
            "nested": {
                "path": "attributes",
                "query": {
                    "bool": {
                        "must": [
                            {
                                "match": {
                                    "attributes.city": "YORK"
                                }
                            },
                            {
                                "match": {
                                    "attributes.city": "JERSEY"
                                }
                            }
                        ]
                    }
                },
                "inner_hits": {}
            }
        }
    }
    

    Search Result:

    Returns no result