Tri Pham
Tri Pham

Reputation: 91

Elasticsearch: merge terms query and match query

Assume, my table has 2 fields: user_name and age I want to check list user name:[john, mary, jim] and that user has "age" is 20. How can I do? I think I will merge 2 queries below:

But I not sure. Please help me. Thanks.

Upvotes: 1

Views: 846

Answers (1)

BrookeB
BrookeB

Reputation: 1769

The terms query seems appropriate for the name. However, I would recommend a term filter for the "age", since it is a numeric value. Generally, the match query is for analyzed fields that you plan to do full-text searching on.

As an example, you can link your two search criteria together using a filtered query like this:

{
  "query": {
    "filtered": {
      "query": {
        "terms": {
          "user_name": ["john","mary","jim"]
        }
      },
      "filter": {
        "term": {
          "age": 20
        }
      }
    }
  }
}

Another possibility is to combine your search criteria using a bool query. For example.

{
  "query": {
    "bool": {
      "must": [
        {
          "terms": {
            "user_name": ["john","mary","jim"]
          }
        },
        {
          "term": {
            "age": 20
          }
        }
      ]
    }
  }
}

Have a look at the documentation for Bool Query here.

Upvotes: 3

Related Questions