简体   繁体   中英

'And' 'Or' Query in ElasticSearch

public class User 
{
  public string Email { get; set; }
  public int Age { get; set; }
  public bool Active { get; set; }
}

client.Index(new User { Email ="test@test.te" });

Query in Linq C# for example :

rep.Where(user=>user.Email=="test@test.te" &&  (user.Age>18 || user.Active== true));

How to make this query for Elasticsearch (I mean same query in Elasticsearch)?

You can use a combination of :

  • range filter for the age field ( reference )
  • term filter for the email and active fields ( reference )
  • a bool filter with should clauses (equivalent to OR) to combine the age and active filters ( reference )
  • another bool filter to combine the previous one with the email filter in must clause (equivalent to AND)
  • A filtered query to be able to use filters defined above.

It may be useful for you to know the differences between query and filters .

You should end with something like this :

{
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "must": [
            {
              "term": {
                "email": "test@test.te"
              }
            },
            {
              "bool": {
                "should": [
                  {
                    "range": {
                      "age": {
                        "gt": 18
                      }
                    }
                  },
                  {
                    "term": {
                      "active": "true"
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }
  }
}

Note:

for this query to work, the email field must be not_analyzed as the term filter looks for the exact same value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM