elasticsearch之should查询

should查询在mysql中就好比是or或,但在es中使用should查询必须要和must一起使用才可以,相当于must[should A,should B],中文解释就好比是满足A或者是B条件的数据,如下这一段shoudl语句的大概意思是满足是用户A上传并且permission状态是private或者permission状态是public的

{
  "bool" : {
    "must" : [
      {
        "bool" : {
          "should" : [
            {
              "bool" : {
                "must" : [
                  {
                    "term" : {
                      "upload_user_name" : {
                        "value" : "用户A",
                      }
                    }
                  },
                  {
                    "term" : {
                      "permission" : {
                        "value" : "private",
                        "boost" : 1.0
                      }
                    }
                  }
                ]
              }
            },
            {
              "term" : {
                "permission" : {
                  "value" : "public",
                  "boost" : 1.0
                }
              }
            }
          ]
        }
      }
    ]
  }
}

Java代码展现出来就是

这里使用的es版本是5.2

public void should(){
	// 最外层bool
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	// 使用should的bool
    BoolQueryBuilder shouldBuilder= QueryBuilders.boolQuery();

    BoolQueryBuilder must = QueryBuilders.boolQuery().must(QueryBuilders.termQuery(DocumentFieldEnum.upload_user_name.name(), "用户A"))               .must(QueryBuilders.termQuery(DocumentFieldEnum.permission.name(), PermissionEnum.PRIVATE.getKey()));

    shouldBuilder.should(must);
    shouldBuilder.should(QueryBuilders.termQuery(DocumentFieldEnum.permission.name(), PermissionEnum.PUBLIC.getKey()));
boolQueryBuilder.must(shouldBuilder);
}
Logo

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

更多推荐