Pintac
Pintac

Reputation: 1585

ElasticSearch : Query multiple value in array

I am trying to put together a query/filter for elastic search. Here is what the structure look like

{
   _id:"0872300234",
   customers:[
      {
         name:"bob",
         priority:1,
         type:"GoodUser"
      },
      {
         name:"dan",
         priority:10,
         type:"BadUser"
      },
      {
         name:"sam",
         priority:10,
         type:"GoodUser"
      },
      {
         name:"cam",
         priority:2,
         type:"BadUser"
      }
   ]
}

So lets call this a "profile" document/record. I would like to find all the profiles that has a customer in that has a priority of 10 and is a "goodUser" (the same customer) so in the example sam will match but dan will not. I got a query that gives me a profile where a customer has priority 10 and a customer(not the same one) has type GoodUser.

Is there a way to query a array item as a whole.

thanks

Upvotes: 4

Views: 4761

Answers (1)

Andrei Stefan
Andrei Stefan

Reputation: 52368

You need nested types for that. More about nested objects you can find here and the reason why you need them in situations where associations between nested fields is important. In your case, the mapping would need to look like this:

{
  "mappings": {
    "profile": {
      "properties": {
        "customers": {
          "type": "nested",
          "properties": {
            "name": {
              "type": "string"
            },
            "priority": {
              "type": "integer"
            },
            "type": {
              "type": "string"
            }
          }
        }
      }
    }
  }
}

And the query would need to be nested, as well:

{
  "query": {
    "nested": {
      "path": "customers",
      "query": {
        "bool": {
          "must": [
            {"match": {
              "customers.type": "goodUser"
            }},
            {"term": {
              "customers.priority": {
                "value": 10
              }
            }}
          ]
        }
      }
    }
  }
}

Upvotes: 4

Related Questions