有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

elasticsearch中的java“匹配或空”查询

假设我有一个索引,列出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”(必须不存在)子句,查询会很好地工作,并为我提供有我想要的主要演员的动作片,但我也想要没有主要演员的动作片


共 (1) 个答案

  1. # 1 楼答案

    到目前为止,这是一个很好的开始!!你就快到了,请看下面的查询,它应该能满足你的期望:

    {
      "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
        }
      }
    }