简体   繁体   English

ElasticSearch中的'And''Or'查询

[英]'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 : 例如,在Linq C#中进行查询:

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)? 如何对Elasticsearch进行此查询(我的意思是Elasticsearch中的相同查询)?

You can use a combination of : 您可以组合使用:

  • range filter for the age field ( reference ) age字段的range过滤器( 参考
  • term filter for the email and active fields ( reference ) emailactive字段的term过滤器( 参考
  • a bool filter with should clauses (equivalent to OR) to combine the age and active filters ( reference ) 一个带有should子句(等效于OR)的bool过滤器,用于组合age过滤器和active过滤器( 参考
  • another bool filter to combine the previous one with the email filter in must clause (equivalent to AND) 另一个bool过滤器,用于将上一个过滤器与must子句中的email过滤器组合在一起(等同于AND)
  • A filtered query to be able to use filters defined above. 一个能够使用上面定义的过滤器的filtered查询。

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. 此查询工作,电子邮件字段必须not_analyzed作为术语过滤器查找值完全相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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