Miguel Barrios
Miguel Barrios

Reputation: 483

ELASTICSEARCH - Filter values in inner hits

In this query I want to get the fields witg values "data.addresses.ces.cp": "true"" from the most recent doc, and then but it returns true values, like false How could I filter only true?

{ "_source": "created_at",
  "size": 1, 
  "sort": [
    {
      "created_at.keyword": {
        "order": "desc"
      }
    }
  ], 
  "query": {
    "nested": {
      "path": "data.addresses",
      "inner_hits": {
        "_source": ["data.addresses.ces.secondname", "data.addresses.ces.cp"],
        "size":100
      },
      "query": {
        "nested": {
          "path": "data.addresses.ces",
          "query": {
            "match": {
              "data.addresses.ces.cp": "true"
            }
          }
        }
      }
    }
  }

    
  

Output:

                "ces" : [
                  {
                    "secondname" : "lopez",
                    "cp" : true
                  },
                  {
                    "secondname" : "gomez",
                    "cp" : false          <--------------- error
                  },
                  {
                    "secondname" : "garcia",
                    "cp" : false         <---------------error
                  }
                ]
              }
            },

Upvotes: 0

Views: 2914

Answers (2)

Joe - Check out my books
Joe - Check out my books

Reputation: 16925

It is somewhat confusing why you'd query data.addresses.services.cp but you wanna retrieve data.addresses.ces.cp. What's this ces? Is it a typo from services?

In any case, as @Val suggested, you can place another inner_hits into the innermost nested query:

{
  "_source": [
    "created_at"
  ],
  "size": 10,
  "query": {
    "nested": {
      "inner_hits": {
        "size": 100,
        "name": "ih_addresses"
      },
      "path": "data.addresses",
      "query": {
        "nested": {
          "inner_hits": {
            "name": "ih_services"
          },
          "path": "data.addresses.services",
          "query": {
            "match": {
              "data.addresses.services.cp": true
            }
          }
        }
      }
    }
  }
}

Note that inner_hits can have a name attribute to distinguish one from the other.

Upvotes: 2

Val
Val

Reputation: 217354

You need to move inner_hits inside the innermost nested query:

{ "_source": "created_at",
  "size": 1, 
  "sort": [
    {
      "created_at.keyword": {
        "order": "desc"
      }
    }
  ], 
  "query": {
    "nested": {
      "path": "data.addresses",
      "query": {
        "nested": {
          "path": "data.addresses.ces",
          "inner_hits": {
            "_source": ["data.addresses.ces.secondname", "data.addresses.ces.cp"],
            "size":100
          },
          "query": {
            "match": {
              "data.addresses.ces.cp": "true"
            }
          }
        }
      }
    }
  }

Upvotes: 1

Related Questions