首页 > 解决方案 > elasticsearch中的“匹配或空”查询

问题描述

假设我有一个包含 2010 年到 2019 年上映的所有电影的索引;如何在 SQL 中将此查询转换为 ElasticSearch?

Select *
From movies
Where 
    releaseDate between '2018-01-01' and '2019-01-01' and
    gender is like 'action' and
    (mainActorId = 42 or mainActorId is null)

我想要 2018 年的所有动作片,有特定的主要演员或根本没有主要演员。我如何将其转换为 ElasticSearch 查询?

从我目前在文档中阅读的内容来看,我可以使用如下内容:

{  
   "size":0,
   "query":{  
      "bool":{  
         "must":[  
            {  
               "range":{  
                  "releaseDate":{  
                     "from":"2018-01-01T00:00:01.531Z",
                     "to":"2019-01-01T00:00:01.531Z",
                     "include_lower":true,
                     "include_upper":true,
                     "boost":1.0
                  }
               }
            },
            {  
               "terms":{  
                  "gender":[  
                     "action"
                  ],
                  "boost":1.0
               }
            },
            {  
               "terms":{  
                  "mainActorId":[  
                     42,
                     56
                  ],
                  "boost":1.0
               }
            }
         ],
         "must_not":[  
            {  
               "exists":{  
                  "field":"mainActorId",
                  "boost":1.0
               }
            }
         ],
         "adjust_pure_negative":true,
         "boost":1.0
      }
   }
}

但这并没有给我带来任何成功,即使 2018 年上映的动作片中有我想要的主要演员(或者根本没有主要演员)。如果我去掉“must_not exist”子句,查询就可以正常工作,并为我提供我想要的主要演员的动作片,但我也想要没有主要演员的动作片......

标签: javaelasticsearch

解决方案


到目前为止很好的开始!您快到了,请参阅下面的查询,它应该符合您的预期:

{
  "size": 0,
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "releaseDate": {
              "from": "2018-01-01T00:00:01.531Z",
              "to": "2019-01-01T00:00:01.531Z",
              "include_lower": true,
              "include_upper": true,
              "boost": 1
            }
          }
        },
        {
          "terms": {
            "gender": [
              "action"
            ],
            "boost": 1
          }
        }
      ],
      "should": [
        {
          "bool": {
            "must_not": [
              {
                "exists": {
                  "field": "mainActorId"
                }
              }
            ]
          }
        },
        {
          "terms": {
            "mainActorId": [
              42,
              56
            ]
          }
        }
      ],
      "minimum_should_match": 1,
      "adjust_pure_negative": true,
      "boost": 1
    }
  }
}

推荐阅读