1

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 ?

  • did you get a chance to go through my answer, looking forward to get feedback from you – ESCoder Oct 07 '20 at 07:00
  • sorry , i thought i commented but looks like i didnt hit enter , thanks @Bhavya , it was helpful and i tried with your example and it worked. so is there any other work around other than not re indexing the data ? – anil chowdary Oct 07 '20 at 13:54
  • thanks for your update . According to me I don't think there is any other way to achieve your use case apart from using nested query (b/c of the reason mentioned in my answer). And please don't forget to accept and upvote my answer – ESCoder Oct 07 '20 at 15:05

1 Answers1

1

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

ESCoder
  • 15,431
  • 2
  • 19
  • 42