如何在Elasticsearch查询中组合“必须”和“应该”?

时间:2018-07-31 15:18:26

标签: elasticsearch

我需要在Elasticsearch查询DSL中“翻译”此伪SQL查询:

  

从发票中选择,其中invoiceType ='REGULAR'和接收方=   'CUSTOMER'和(invoiceStatus ='DISPATCHED'或invoiceStatus ='PAYED')

我有这个:

{
  "query": {
    "bool": {
      "must": [
        { "match": { "invoiceType":  "REGULAR" }},
        { "match": { "receiver": "CUSTOMER" }},
        { "bool" : {
            "should": [
                {"match" : {"invoiceStatus": "DISPATCHED"}},
                {"match" : {"invoiceStatus": "PAYED"}}
            ]
          }
        }
      ]
    }
  }
}

该查询返回0个结果,但我知道有许多匹配我要搜索的内容。 AFAIK,must类似于“ AND”,should类似于“ OR”。我想念什么?

1 个答案:

答案 0 :(得分:0)

不确定它是否对您有用,但是您可以尝试看看会得到什么?尽管我将match更改为term。希望对您有帮助。

GET /invoice/_search
{
   "query" : {
      "constant_score" : {
         "filter" : {
            "bool" : {
              "must" : [
                { "term" : {"invoiceType" : "REGULAR"}}, 
                { "term": { "receiver": "CUSTOMER" }},
                { "bool" : { 
                  "should" : [
                      {"terms": {"invoiceStatus": ["DISPATCHED","PAYED"]}}   
                  ]
                }}
              ]
           }
         }
      }
   }
}

OR

GET /invoice/_search
{
   "query" : {
      "constant_score" : {
         "filter" : {
            "bool" : {
              "must" : [
                { "term" : {"invoiceType" : "REGULAR"}}, 
                { "term": { "receiver": "CUSTOMER" }},
                { "bool" : { 
                  "should" : [
                    {"term": {"invoiceStatus": "DISPATCHED"}},
                    {"term": {"invoiceStatus": "PAYED"}}     
                  ]
                }}
              ]
           }
         }
      }
   }
}
相关问题