ES查询技巧:实现复杂条件组合搜索
当你的需求是 condition A & condition B & (condition C || condition D)时,在 ES 中使用 must 与 should 组合可解决,话不都说,直接上正确的查询语句:
-
- {
- "query": {
- "bool": {
- "must": [
- {
- "bool": {
- "should": [
- {
- "match": {
- "conditionA": {
- "query": "A"
- }
- }
- }
- ]
- }
- },
- {
- "bool": {
- "should": [
- {
- "match": {
- "conditionB": {
- "query": "B"
- }
- }
- }
- ]
- }
- },
- {
- "bool": {
- "should": [
- {
- "constant_score": {
- "filter": {
- "match": {
- "conditionC": {
- "query": "C"
- }
- }
- }
- }
- },
- {
- "constant_score": {
- "filter": {
- "match": {
- "conditionD": {
- "query": "D"
- }
- }
- }
- }
- }
- ]
- }
- }
- ]
- }
- }
- }
复制代码
重点就是所有条件都包含在must中,将or的条件放到一个should中,而不是must和should平级。
|