Elasticsearch同时使用should和must

问题及解决方法

must和should组合查询,should失效。使用must嵌套查询,将should组成的bool查询包含在其中一个must查询中。

SearchRequest request = new SearchRequest();
request.indices("function_log");

SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
if (StringUtils.hasText(schoolName)) {
    boolQueryBuilder.must(QueryBuilders.termQuery("schoolName.keyword", schoolName));
}
if (StringUtils.hasText(typeFunction)) {
    boolQueryBuilder.must(QueryBuilders.termQuery("typeFunction.keyword", typeFunction));
}
if (StringUtils.hasText(startTime) && StringUtils.hasText(endTime)) {
    boolQueryBuilder.must(QueryBuilders.rangeQuery("createDate").gte(startTime + "T00:00:00.000Z").lte(endTime + "T23:59:59.000Z"));
}
BoolQueryBuilder shouldQuery = QueryBuilders.boolQuery();
shouldQuery.should().add(QueryBuilders.termQuery("description.keyword","查询学生信息表"));
shouldQuery.should().add(QueryBuilders.termQuery("description.keyword","获取学校访客数据"));
boolQueryBuilder.must(shouldQuery);

sourceBuilder.query(boolQueryBuilder);
request.source(sourceBuilder);
System.out.println(sourceBuilder.toString());

Elasticsearch同时使用should和must_第1张图片

GET /function_log/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "schoolName.keyword": {
              "value": "测试学校",
              "boost": 1
            }
          }
        },
        {
          "term": {
            "typeFunction.keyword": {
              "value": "教师端功能",
              "boost": 1
            }
          }
        },
        {
          "range": {
            "createDate": {
              "from": "2023-08-01T00:00:00.000Z",
              "to": "2023-08-07T23:59:59.000Z",
              "include_lower": true,
              "include_upper": true,
              "boost": 1
            }
          }
        },
        {
          "bool": {
            "should": [
              {
                "term": {
                  "description.keyword": {
                    "value": "查询学生信息表",
                    "boost": 1
                  }
                }
              },
              {
                "term": {
                  "description.keyword": {
                    "value": "获取学校访客数据",
                    "boost": 1
                  }
                }
              }
            ],
            "adjust_pure_negative": true,
            "boost": 1
          }
        }
      ],
      "adjust_pure_negative": true,
      "boost": 1
    }
  }
}

你可能感兴趣的:(#,Elasticsearch,elasticsearch)