How can I use ElasticSearch term queries to filter for a value in an array of objects?

Viewed 22

I'm attempting to send a POST req to an API so that I only receive hits with role: "editor". The unfiltered response looks like:

_source: {
  configuration: {
    roles : [
        {role : "lead"},
        {role : "editor"},
      ]
  }
}

I'm attempting to use the following query to receive the desired response:

body: {
  size: 10,
  query: {
    bool: {
      must: { 
        term: {
          role : "editor"
        }
      }
    }
  }
}

But I receive 0 hits even though I can verify there are thousands of hits with role: "editor".

I've also tried variations of this request with:

body: {
  size: 10,
  query: {
    bool: {
      must: { 
        term: {
          "roles.role" : "editor"
        }
      }
    }
  }
}

or

body: {
  size: 10,
  query: {
    bool: {
      must: { 
        term: {
          "roles" : "role.editor"
        }
      }
    }
  }
}

Does anyone know what I'm doing incorrectly? It seems like the problem is that Roles is an array of objects and I'm not accessing the role value corectly.

1 Answers

If you field "roles" is nested type you must use Nested Query.

{
  "query": {
    "nested": {
      "path": "roles",
      "query": {
        "term": {
          "roles.role": {
            "value": "editor"
          }
        }
      }
    }
  }
}

If not "nested", try this:

{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "roles.role": {
              "value": "lead"
            }
          }
        }
      ]
    }
  }
}
Related