Querying Nested Structure

I try to query documents that have nested objects:

{
      "name":"Adam",
      "cities":[
         {
            "name":"California",
            "activities":[
               {
                  "name":"Hicking"
               },
               {
                  "name":"Camping"
               },
               {
                  "name":"Festival"
               }
            ]
         },
         {
            "name":"Miami",
            "activities":[
               {
                  "name":"Festival"
               },
               {
                  "name":"Diving"
               },
               {
                  "name":"Surfing"
               }
            ]
         }
      ]
    }

I want to retrieve all conditions based on an activity, for example, I want to retrieve all cities where Adam wants to go to festivals. The query result should be California and Miami and if we search about what is the town where Adam will do hicking, the query result should be California.
This is what it SHOULD be, but the actual result is that when I search about the cities where Adam will do hicking, the query result was California and Miami!!

This is the query I used:

    GET index/_search
    {
      "query": 
            {
             "bool": {"filter": [
                        {"term": {
                             "cities.activities.name.keyword": "Hicking"
                                 }}
                               ]}
                    },"_source":["cities.name"]
          }

And this is the search result:

        "_index" : "index",
        "_type" : "prod",
        "_id" : "1",
        "_score" : 0.0,
        "_source" : {
          "cities" : [
            {
              "name" : "California"
            },
            {
              "name" : "Miami"
            }
          ]
        }

How can make the query in the right way for such a data structure?

Will nested field helps?

Should I redesign the data structure?

Hi!

One possibility is to use Nested Query, using the cities and/or activities field as "nested".
To find out which nested object was matched use inner_hits.

This is a possibility:

GET idx_test/_search
{
  "_source": [
    "cities.name"
  ],
  "query": {
    "nested": {
      "path": "cities",
      "query": {
        "term": {
          "cities.activities.name.keyword": {
            "value": "Diving"
          }
        }
      },
      "inner_hits": {}
    }
  }
}

Thanks!! It worked
But how can I use the fuzzy search with nested queries??

1 Like

Yes. You can try something like this:

{
          "nested": {
            "path": "field",
            "query": {
              "match": {
                "field_name": {
                  "query": "any text",
                  "fuzziness": "AUTO"
                }
              }
            }
          }
        }

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.