0

This is an example of what my data looks like for an Elastic Search index called video_service_inventory:

{
    'video_service': 'netflix',
    'movies' : [
        {'title': 'Mission Impossible', 'genre: 'action'},
        {'title': 'The Hangover', 'genre': 'comedy'},
        {'title': 'Zoolander', 'genre': 'comedy'},
        {'title': 'The Ring', 'genre': 'horror'}
    ]
}

I have established in my index that the "movies" field is of type "nested"

I want to write a query that says "get me all video_services that contain both of these movies":

{'title': 'Mission Impossible', 'genre: 'action'}
AND
{'title': 'The Ring', 'genre': 'horror'}

where, the title and genre must match. If one movie exists, but not the other, I don't want the query to return that video service.

Ideally, I would like to do this in 1 query. So far, I haven't been able to find a solution.

Anyone have suggestions for writing this search query?

1 Answers1

0

the syntax may vary depending on elasticsearch version, but in general you should combine multiple nested queries within a bool - must query. For nested queries you need to specify path to "navigate" to the nested documents, and you need to qualify the properties with the part + the field name:

{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "movies",
            "query": {
              "bool": {
                "must": [
                  { "terms": { "movies.title": "Mission Impossible" } },
                  { "terms": { "movies.genre": "action" } }
                ]
              }
            }
          }
        },
        {
          "nested": {
            "path": "movies",
            "query": {
              "bool": {
                "must": [
                  { "terms": { "movies.title": "The Ring" } },
                  { "terms": { "movies.genre": "horror" } }
                ]
              }
            }
          }
        }
      ]
    }
  }
}

This example assumes that the title and genre fields are not analyzed properties. In newer versions of elasticsearch you may find them as a .keyword field, and you would then use "movies.genre.keyword" to query on the not analyzed version of the data.¨

For details on bool queries you can have a look at the documentation on the ES website: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html

For nested queries: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-nested-query.html

Peter
  • 106
  • 6