2015-02-24 23 views

回答

2

那麼在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)) 
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) 
          ) 
        ) 
       ) 
      ) 
     ) 
     ); 
+1

AND()和OR()過濾器是不等同於位運算和或者在大多數情況下你想要布爾過濾器/查詢。在這裏閱讀所有內容:http://www.elasticsearch.org/blog/all-about-elasticsearch-filter-bitsets/ – 2015-03-05 16:04:32