请问 es should 下嵌套多个 must 怎么写?

请问下如下 sql 语句如何转换为 ES 的 DSL 语句:

select * from table where ( 

( sex = 1 or sex = 2 ) and ( color = 226 or color = 229 ) 

) OR (

( sex = 0 or sex = 3 ) and ( color = 226 ) 

);

按我的理解,我写了下面一个 dsl 查询语句,但是报错:

{
    "query": {
        "bool": {
            "should": [{
                "must": [{
                    "bool": {
                        "should": [{
                            "match": {
                                "tags": "1"
                            }
                        }]
                    }
                }]
            }]
        }
    },
    "size": 2
}

报错内容:

{
  "error": {
    "root_cause": [
      {
        "type": "parsing_exception",
        "reason": "[must] query malformed, no start_object after query name",
        "line": 5,
        "col": 13
      }
    ],
    "type": "x_content_parse_exception",
    "reason": "[5:13] [bool] failed to parse field [should]",
    "caused_by": {
      "type": "parsing_exception",
      "reason": "[must] query malformed, no start_object after query name",
      "line": 5,
      "col": 13
    }
  },
  "status": 400
}
阅读 935
avatarAI BotBETA

你的 SQL 查询语句和尝试的 Elasticsearch 查询语句有些混淆。在 Elasticsearch 中,我们需要将查询条件组合在一个对象中,如 bool 对象。对于你的 SQL 查询,你应该将其转化为如下的 Elasticsearch 查询语句:

{
  "query": {
    "bool": {
      "must": [
        {
          "bool": {
            "must": [
              { "match": { "sex": "1" } },
              { "match": { "color": "226" } }
            ],
            "should": [
              { "match": { "sex": "2" } },
              { "match": { "color": "229" } }
            ]
          }
        },
        {
          "bool": {
            "must": [
              { "match": { "sex": "0" } },
              { "match": { "color": "226" } }
            ],
            "should": [
              { "match": { "sex": "3" } },
              { "match": { "color": "226" } }
            ]
          }
        }
      ]
    }
  },
  "size": 2
}

以上这段代码应该可以正确地模拟你的 SQL 查询。这段代码的意思是有多个 bool 查询,每个 bool 查询都包含一个 must 查询和一个 should 查询。在 should 查询中,只需要匹配其中的一项就可以。所以,第一个 should 查询表示的是 sex 为 1 或 2,且颜色为 226 或 229。第二个 should 查询表示的是 sex 为 0 或 3,且颜色为 226。只有当所有的 must 查询和至少一个 should 查询匹配时,这个记录才会被返回。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题