PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 25, 2022

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

 October 25, 2022     elasticsearch, json     No comments   

Issue

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.


Solution

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"
            }
          }
        }
      ]
    }
  }
}


Answered By - rabbitbr
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing