ElasticSearch嵌套必须和应该

时间:2019-06-14 17:32:20

标签: elasticsearch

我正在尝试为Web应用程序创建一些过滤器。用户需要能够按用户(复选框)和类型(也就是复选框)进行过滤。

我在Elasticsearch中需要这样的东西(在T-SQL中):

SELECT * from documents d
WHERE (
    d.user = 'user1' OR
    d.user = 'user2'
) AND (
    d.type = 'type1ID' OR 
    d.type = 'type2ID'
)

2 个答案:

答案 0 :(得分:1)

未经测试,但是您需要类似的东西

带有library(tidyverse) testframe1 = data.frame(Date = seq(ymd('2000-01-01'),ymd('2003-12-31'),by='day')) %>% mutate(Day = substr(Date, start = 6, stop = 10), ABC = rnorm(1461), Year = as.numeric(format(Date,'%Y')), Date = NULL) %>% select(Year, Day, ABC) testframe2 = data.frame(Date = seq(ymd('2004-01-01'),ymd('2007-12-31'),by='day')) %>% mutate(Day = substr(Date, start = 6, stop = 10), ABC = rnorm(1461), Year = as.numeric(format(Date,'%Y')), Date = NULL) %>% select(Year, Day, ABC) df_list = list(testframe1, testframe2) df = map_dfr(df_list, ~.x %>% spread(Day, ABC))

term

或与GET documents/_search { "query" : { "constant_score" : { "filter" : { "bool" : { "should" : [ { "term" : {"user" : "user1"}}, { "term" : {"user" : "user2"}} ], "should" : { { "term" : {"type" : "type1ID"}}, { "term" : {"type" : "type2ID"}} } } } } } }

terms

答案 1 :(得分:0)

您必须结合必须和应该子句才能实现您想要的目标:

{
   "query":{
      "bool":{ 
         "must":{
            "match_all":{}
         },
         "filter":{
            "bool":{
               "must":[
                  {
                     "bool":{
                        "should":[
                           {
                              "term":{
                                 "user":"user1"
                              }
                           },
                           {
                              "term":{
                                 "user":"user2"
                              }
                           }
                        ]
                     }
                  },
                  {
                     "bool":{
                        "should":[
                           {
                              "term":{
                                 "type":"type1ID"
                              }
                           },
                           {
                              "term":{
                                 "type":"type2ID"
                              }
                           }
                        ]
                     }
                  }
               ]
            }
         }
      }
   }
}

在此示例中,过滤器应用于match_all子句,即您的``SELECT *''。第一级``必须''的行为类似于``AND'',而第二级``应该''的行为都与您的``OR''类似。< / p>