JAVA操作ES中的BoolQueryBuilder 查询方法

2年前 (2022) 程序员胖胖胖虎阿
324 0 0

一,创建es的连接
public TransportClient transportClient(){
    Settings settings = Settings.builder()
            .put("cluster.name", "elasticsearch")
            .build();
    TransportClient client  = new PreBuiltTransportClient(settings);
    TransportAddress transportAddress = null;
    try {
        transportAddress = new TransportAddress(InetAddress.getByName(host), Integer.valueOf(port));
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    client.addTransportAddress(transportAddress);
    return client;
}
 

二,java es api的添加操作

transportClient.prepareIndex("search_index", "doc").setSource(json, XContentType.JSON).get();

三,java es api的修改操作

transportClient.prepareUpdate("search_index", "doc","gug4u3EBSHOgAqyn-5aI").setSource(json, XContentType.JSON).get();

四,java es api的删除操作

transportClient.prepareDelete("search_index", "doc", "gug4u3EBSHOgAqyn-5aI").get();
 

五,查询QueryBuilders

BoolQueryBuilder queryBuilder= QueryBuilders.boolQuery();
1,matchAllQuery匹配所有

queryBuilder.matchAllQuery();
2,termQuery精准匹配,大小写敏感且不支持

queryBuilder.termQuery("key", value) 一次匹配一个值,完全匹配
queryBuilder.termsQuery("key", obj1, obj2..)   一次匹配多个值
3,matchPhraseQuery对中文精确匹配

queryBuilder.matchPhraseQuery("key", value)

4,matchQuery("key", Obj) 单个匹配, field不支持通配符, 前缀具高级特性

queryBuilder.matchQuery(key, value);
5,multiMatchQuery("text", "field1", "field2"..); 匹配多个字段, field有通配符忒行

queryBuilder.multiMatchQuery(value, key1, key2, key3);
6,组合查询

   * must:   AND
   * mustNot: NOT
   * should:: OR
 queryBuilder.must(QueryBuilders.termQuery("user", "kimchy"))
            .mustNot(QueryBuilders.termQuery("message", "nihao"))
            .should(QueryBuilders.termQuery("gender", "male"));

7.should和must

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

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);
}
 

版权声明:程序员胖胖胖虎阿 发表于 2022年10月1日 下午5:16。
转载请注明:JAVA操作ES中的BoolQueryBuilder 查询方法 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...