ElasticSearch - NEST - 如何组合AND和OR语句

时间:2015-02-24 16:22:38

标签: elasticsearch nest

我是ElasticSearch的新手 - NEST API。

我们正在尝试使用AND / OR子句准备多个条件。 例如 - (条件1或条件2)和(条件3)

目前我们正在尝试连接查询条件。

任何人都可以使用NEST API提供更好的示例吗?

2 个答案:

答案 0 :(得分:4)

ElasticSearch中有一些名为Bool Query的东西。与匹配其他查询的布尔组合(AND,OR,NOT)的文档匹配的查询。它是使用一个或多个布尔子句构建的,每个子句都有一个类型化的子句。事件类型是:

必须:(AND)子句(查询)必须出现在匹配的文档中。

应该:(OR)子句(查询)应出现在匹配的文档中。在没有must子句的布尔查询中,一个或多个should子句必须与文档匹配。可以使用minimum_should_match参数设置要匹配的最小条件子数。

must_not:(NOT)子句(查询)不得出现在匹配的文档中。

因此,对于您给出的示例,您将获得以下查询:

bool 
    should
        condition 1
        condition 2
    bool
        must
            condition 3

在ElasticSearch中代码如下:

"filter": {
           "bool": {
               "should": [
                             {"term": {"tag": value1}},
                             {"term": {"tag": value2}}
                         ],
                         "bool": {
                                 "must":{"term": {"tag": "value3"}}
                                 }
                    }
           }

在NEST中它看起来像:

Filter(f=>f
   .Bool(b=>b
       .Should(
          o=>o.Term(t=>t.Tag, Value1),
          o=>o.Term(t=>t.Tag, Value2)),
          o=>o.Bool(bo=>bo
            .Must(a=>a.Term(t=>t.Tag, Value3))
        )
    )
)

根据NEST documentation而不是编写如此乏味和冗长的查询,您可以使用NEST的Bitwise运算符,这很简单。

.Query((q=>q.Term(tag, value1) || q.Term(tag, value2)) && q.Term(tag, value3))

答案 1 :(得分:0)

以下是原始数据设置和查询:

PUT hilden1

POST hilden1/type1
{
  "f1": 123,
  "f2": 456,
  "f3": 789
}

GET hilden1/type1/_search
{
  "query": {
    "filtered": {
      "filter": {
        "and": {
          "filters": [
            {
              "term": {
                "f1": "123"
              }
            },
            {
              "or": {
                "filters": [
                  {
                    "term": {
                      "f2": "456"
                    }
                  },
                  {
                    "term": {
                      "f3": "888"
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }
  }
}

这是粗糙的等效物:

    var search = ElasticClient.Search<AuthForReporting>(s=> s
        .Query(q=> q
            .Filtered(fq => fq
                .Filter(f=> f
                    .And(
                        a=> a.Term(t=> t.f1, 123),
                        a => a.Or(
                            o => o.Term(t=>t.f2, 456),
                            o => o.Term(t => t.f3, 888)
                            )
                    )
                )
            )
        )
        );