参考:https://blog.csdn.net/andy_5826_liu/article/details/103161654

 

我本意上想做到像这个sql一样

select * from table 

where

( dynamicType = '201' and viewTime = '2019-10-11' ) 

 and 

( uniqueKey = 'xxx'    or    uniqueKey = 'zzz' )

 

1、出现问题的写法,在bool下面有must和should同级的两个属性,像下面这样下就会导致should的筛选失效,只有must生效

{
	"query": {
		"bool": {
			"must": [{
				"term": {
					"dynamicType": "201"
				}
			}, {
				"term": {
					"viewTime": "2019-10-11"
				}
			}],

			"should": [{
				"term": {
					"uniqueKey": "xxx"
				}
			}, {
				"term": {
					"uniqueKey": "zzz"
				}
			}]
		}
	}
}

2、正确写法

也就是在must内再加一个bool查询,然后这个嵌套的bool查询中写一个should

关系的理解:

(1)首先,在must数组中的两个term(暂时称为term1和term2)和一个bool是and关系,

即(term1返回true) 且 (term2返回true) 且 (bool返回true时),这条数据才匹配。

(2)然后这个嵌套的bool下又有一个shoudd数组

所以这个bool是需要should返回true才为treu,

而should则需要数组中某一个条件匹配成功才返回true(或者关系)

所以下面这个最终组成sql的条件是

where

dynamicType = '201' 

and viewTime = '2019-10-11' 

and  ( uniqueKey = 'xxx'  or  uniqueKey = 'zzz' )

 

{
	"query": {
		"bool": {
			"must": [{
					"term": {
						"dynamicType": "201"
					}
				},
				{
					"term": {
						"viewTime": "2019-10-11"
					}
				},
				{
					"bool": {

						"should": [{
							"term": {
								"uniqueKey": "xxx"
							}
						}, {
							"term": {
								"uniqueKey": "zzz"
							}
						}]
					}
				}
			]

		}
	}
}

 

参考:

https://blog.csdn.net/andy_5826_liu/article/details/103161654

https://blog.csdn.net/zhnegyeshi/article/details/102584708

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐