Elasticsearch进行and,or多条件嵌套组合DSL结构化查询

业务需求中有如下查询:

( a=1 and (b=2 or b=3) ) or (a=2 and (b=1 or b =2))

网上找了大半天没找到结果,只能自己尝试拼写DSL语句,功夫不负有心人,果然找到了正确的写法,现分享给有需要的同学(使用的es版本:6.8.0)

https://github.com/memoryFuhao/elasticsearch_client (打个广告 以上链接是本人开发的一个es客户端工具,支持es大部分 CRUD操作 分页、分组、嵌套分组、and or ···,有需要的朋友可以pull代码直接使用)

参考以下DSL语句:

should数组中的一个元素即为一个 ( a=1 and (b=2 or b=3) ) 查询 ,多个or则在数组中加入多个元素即可.

{
    "query": {
        "bool": {
            "should": [
                {
                    "bool": {
                        "must": [
                            {
                                "term": {
                                    "cameraId": "931"
                                }
                            },
                            {
                                "bool": {
                                    "should": [
                                        {
                                            "term": {
                                                "captureTime": 1590943274722
                                            }
                                        },
                                        {
                                            "term": {
                                                "captureTime": 1590995728554
                                            }
                                        }
                                    ]
                                }
                            }
                        ]
                    }
                },
                {
                    "bool": {
                        "must": [
                            {
                                "term": {
                                    "cameraId": "690"
                                }
                            },
                            {
                                "bool": {
                                    "should": [
                                        {
                                            "term": {
                                                "captureTime": 1590943274722
                                            }
                                        },
                                        {
                                            "term": {
                                                "captureTime": 1593512659228
                                            }
                                        }
                                    ]
                                }
                            }
                        ]
                    }
                }
            ]
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_46742102/article/details/121431333