Programjon
Programjon

Reputation: 23

Elasticsearch - only return specific elements of an array of objects in query

I have a doc that has a field "watch_providers" which is an array of objects:

  "hits" : {
    "total" : {
      "value" : 6,
      "relation" : "eq"
    },
    "max_score" : 6.262947,
    "hits" : [
      {
        "_index" : "usermovies",
        "_type" : "_doc",
        "_id" : "68900c39-faef-4523-b069-c462a33c6655_d88af923-3bd4-4dee-96ad-56fc2593b3fd",
        "_score" : 6.262947,
        "_source" : {
          "plot" : "Gordie, Chris, Teddy and Vern are four friends who decide to hike to find the corpse of Ray Brower, a local teenager, who was hit by a train while plucking blueberries in the wild.",
          "description" : "Gordie, Chris, Teddy and Vern are four friends who decide to hike to find the corpse of Ray Brower, a local teenager, who was hit by a train while plucking blueberries in the wild.",
          "movie_id" : "d88af923-3bd4-4dee-96ad-56fc2593b3fd",
          "title" : "Stand by Me",
          "watch_providers" : [
            {
              "country" : "FI",
              "logo_path" : "/oEntjkQyz84qo1C4FZK9jW1qznl.jpg",
              "provider_name" : "Netflix",
              "tmdb_type" : "buy"
            },
            {
              "country" : "AT",
              "logo_path" : "/3VEZVpmNPZdyIxUeFYWVGsS18xd.jpg",
              "provider_name" : "Netflix",
              "tmdb_type" : "ads"
            },
            {
              "country" : "US",
              "logo_path" : "/q6tl6Ib6X5FT80RMlcDbexIo4St.jpg",
              "provider_name" : "Netflix",
              "tmdb_type" : "buy"
            }....

I only want my query to return the watch_provider object with country value "US". I want everything else in the doc to remain as is. How can I do this? Nested inner hits? Thanks in advance for your help!

Upvotes: 0

Views: 700

Answers (1)

ExploZe
ExploZe

Reputation: 446

Yes you need to use nested inner hits.

For example

{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "watch_providers",
            "inner_hits": {
              "size": 10
            },
            "query": {
              "bool": {
                "must": [
                  {
                    "term": {
                      "watch_providers.country": "us"
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}

Upvotes: 1

Related Questions