关于搜索引擎:中间件ElasticSearch组件RestHighLevelClient用法详解

51次阅读

共计 8040 个字符,预计需要花费 21 分钟才能阅读完成。

本文源码:GitHub·点这里 || GitEE·点这里

一、根底 API 简介

1、RestHighLevelClient

RestHighLevelClient 的 API 作为 ElasticSearch 备受举荐的客户端组件,其封装零碎操作 ES 的办法,包含索引构造治理,数据增删改查治理,罕用查询方法,并且能够联合原生 ES 查问原生语法,性能非常弱小。

在应用 RestHighLevelClient 的语法时,通常波及下面几个方面,在把握根底用法之上能够依据业务特点进行一些自定义封装,这样能够更优雅的解决业务需要。

2、外围依赖

应用 RestHighLevelClient 须要依赖 rest-high-level-client 包,和 ES 相干根底依赖。

<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-client</artifactId>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>

二、索引治理

这里不做过多形容,留神一点:因为 ES 的数据结构特点,所以不须要索引更新办法,新的字段在更新数据时间接写入即可,不须要提前更新索引构造。

@Service
public class EsIndexOperation {

    @Resource
    private RestHighLevelClient client ;
    private final RequestOptions options = RequestOptions.DEFAULT;

    /**
     * 判断索引是否存在
     */
    public boolean checkIndex (String index) {
        try {return client.indices().exists(new GetIndexRequest(index), options);
        } catch (IOException e) {e.printStackTrace();
        }
        return Boolean.FALSE ;
    }

    /**
     * 创立索引
     */
    public boolean createIndex (String indexName ,Map<String, Object> columnMap){
        try {if(!checkIndex(indexName)){CreateIndexRequest request = new CreateIndexRequest(indexName);
                if (columnMap != null && columnMap.size()>0) {Map<String, Object> source = new HashMap<>();
                    source.put("properties", columnMap);
                    request.mapping(source);
                }
                this.client.indices().create(request, options);
                return Boolean.TRUE ;
            }
        } catch (IOException e) {e.printStackTrace();
        }
        return Boolean.FALSE;
    }

    /**
     * 删除索引
     */
    public boolean deleteIndex(String indexName) {
        try {if(checkIndex(indexName)){DeleteIndexRequest request = new DeleteIndexRequest(indexName);
                AcknowledgedResponse response = client.indices().delete(request, options);
                return response.isAcknowledged();}
        } catch (Exception e) {e.printStackTrace();
        }
        return Boolean.FALSE;
    }
}

三、数据管理

这里在更新数据时,能够间接批改索引构造,在 dataMap 中放进新的字段即可。

@Service
public class EsDataOperation {

    @Resource
    private RestHighLevelClient client ;
    private final RequestOptions options = RequestOptions.DEFAULT;

    /**
     * 写入数据
     */
    public boolean insert (String indexName, Map<String,Object> dataMap){
        try {BulkRequest request = new BulkRequest();
            request.add(new IndexRequest(indexName,"doc").id(dataMap.remove("id").toString())
                    .opType("create").source(dataMap,XContentType.JSON));
            this.client.bulk(request, options);
            return Boolean.TRUE ;
        } catch (Exception e){e.printStackTrace();
        }
        return Boolean.FALSE;
    }

    /**
     * 批量写入数据
     */
    public boolean batchInsert (String indexName, List<Map<String,Object>> userIndexList){
        try {BulkRequest request = new BulkRequest();
            for (Map<String,Object> dataMap:userIndexList){request.add(new IndexRequest(indexName,"doc").id(dataMap.remove("id").toString())
                        .opType("create").source(dataMap,XContentType.JSON));
            }
            this.client.bulk(request, options);
            return Boolean.TRUE ;
        } catch (Exception e){e.printStackTrace();
        }
        return Boolean.FALSE;
    }

    /**
     * 更新数据,能够间接批改索引构造
     */
    public boolean update (String indexName, Map<String,Object> dataMap){
        try {UpdateRequest updateRequest = new UpdateRequest(indexName,"doc", dataMap.remove("id").toString());
            updateRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
            updateRequest.doc(dataMap) ;
            this.client.update(updateRequest, options);
            return Boolean.TRUE ;
        } catch (Exception e){e.printStackTrace();
        }
        return Boolean.FALSE;
    }

    /**
     * 删除数据
     */
    public boolean delete (String indexName, String id){
        try {DeleteRequest deleteRequest = new DeleteRequest(indexName,"doc", id);
            this.client.delete(deleteRequest, options);
            return Boolean.TRUE ;
        } catch (Exception e){e.printStackTrace();
        }
        return Boolean.FALSE;
    }
}

四、查问操作

留神:查问总数的 CountRequest 语法,SearchRequest 查问后果中数据转换语法,分页查问中须要指定偏移地位和分页大小。

@Service
public class EsQueryOperation {

    @Resource
    private RestHighLevelClient client ;
    private final RequestOptions options = RequestOptions.DEFAULT;

    /**
     * 查问总数
     */
    public Long count (String indexName){
        // 指定创立工夫
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.termQuery("createTime", 1611378102795L));

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(queryBuilder);

        CountRequest countRequest = new CountRequest(indexName);
        countRequest.source(sourceBuilder);
        try {CountResponse countResponse = client.count(countRequest, options);
            return countResponse.getCount();} catch (Exception e) {e.printStackTrace();
        }
        return 0L;
    }

    /**
     * 查问汇合
     */
    public List<Map<String,Object>> list (String indexName) {
        // 查问条件, 指定工夫并过滤指定字段值
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.termQuery("createTime", 1611378102795L));
        queryBuilder.mustNot(QueryBuilders.termQuery("name","北京 - 李四"));
        sourceBuilder.query(queryBuilder);
        SearchRequest searchRequest = new SearchRequest(indexName);
        searchRequest.source(sourceBuilder);
        try {SearchResponse searchResp = client.search(searchRequest, options);
            List<Map<String,Object>> data = new ArrayList<>() ;
            SearchHit[] searchHitArr = searchResp.getHits().getHits();
            for (SearchHit searchHit:searchHitArr){Map<String,Object> temp = searchHit.getSourceAsMap();
                temp.put("id",searchHit.getId()) ;
                data.add(temp);
            }
            return data;
        } catch (Exception e) {e.printStackTrace();
        }
        return null ;
    }

    /**
     * 分页查问
     */
    public List<Map<String,Object>> page (String indexName,Integer offset,Integer size) {
        // 查问条件, 指定工夫并过滤指定字段值
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.from(offset);
        sourceBuilder.size(size);
        sourceBuilder.sort("createTime", SortOrder.DESC);
        SearchRequest searchRequest = new SearchRequest(indexName);
        searchRequest.source(sourceBuilder);
        try {SearchResponse searchResp = client.search(searchRequest, options);
            List<Map<String,Object>> data = new ArrayList<>() ;
            SearchHit[] searchHitArr = searchResp.getHits().getHits();
            for (SearchHit searchHit:searchHitArr){Map<String,Object> temp = searchHit.getSourceAsMap();
                temp.put("id",searchHit.getId()) ;
                data.add(temp);
            }
            return data;
        } catch (Exception e) {e.printStackTrace();
        }
        return null ;
    }
}

五、排序形式

排序除了惯例的指定字段升序降序规定之外,还能够基于原生的脚本语法,基于自定义规定排序让一些特定的数据沉底或者置顶。

@Service
public class EsSortOperation {

    @Resource
    private RestHighLevelClient client ;
    private final RequestOptions options = RequestOptions.DEFAULT;

    /**
     * 排序规定
     */
    public List<Map<String,Object>> sort (String indexName) {
        // 先升序工夫,在倒序年龄
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.sort("createTime", SortOrder.ASC);
        sourceBuilder.sort("age",SortOrder.DESC) ;
        SearchRequest searchRequest = new SearchRequest(indexName);
        searchRequest.source(sourceBuilder);
        try {SearchResponse searchResp = client.search(searchRequest, options);
            List<Map<String,Object>> data = new ArrayList<>() ;
            SearchHit[] searchHitArr = searchResp.getHits().getHits();
            for (SearchHit searchHit:searchHitArr){Map<String,Object> temp = searchHit.getSourceAsMap();
                temp.put("id",searchHit.getId()) ;
                data.add(temp);
            }
            return data;
        } catch (Exception e) {e.printStackTrace();
        }
        return null ;
    }

    /**
     * 自定义排序规定
     */
    public List<Map<String,Object>> defSort (String indexName) {
        // 指定置换程序的规定
        // [age 12-->60]\[age 19-->10]\[age 13-->30]\[age 18-->40],age 其余值疏忽为 1
        Script script = new Script("def _ageSort = doc['age'].value == 12?60:" +
                                                            "(doc['age'].value == 19?10:" +
                                                            "(doc['age'].value == 13?30:" +
                                                            "(doc['age'].value == 18?40:1)));" + "_ageSort;");
        ScriptSortBuilder sortBuilder = SortBuilders.scriptSort(script,ScriptSortBuilder.ScriptSortType.NUMBER);
        sortBuilder.order(SortOrder.ASC);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.sort(sortBuilder);
        SearchRequest searchRequest = new SearchRequest(indexName);
        searchRequest.source(sourceBuilder);
        try {SearchResponse searchResp = client.search(searchRequest, options);
            List<Map<String,Object>> data = new ArrayList<>() ;
            SearchHit[] searchHitArr = searchResp.getHits().getHits();
            for (SearchHit searchHit:searchHitArr){Map<String,Object> temp = searchHit.getSourceAsMap();
                temp.put("id",searchHit.getId()) ;
                data.add(temp);
            }
            return data;
        } catch (Exception e) {e.printStackTrace();
        }
        return null ;
    }
}

六、源代码地址

GitHub·地址
https://github.com/cicadasmile/data-manage-parent
GitEE·地址
https://gitee.com/cicadasmile/data-manage-parent

举荐浏览:编程体系整顿

序号 项目名称 GitHub 地址 GitEE 地址 举荐指数
01 Java 形容设计模式, 算法, 数据结构 GitHub·点这里 GitEE·点这里 ☆☆☆☆☆
02 Java 根底、并发、面向对象、Web 开发 GitHub·点这里 GitEE·点这里 ☆☆☆☆
03 SpringCloud 微服务根底组件案例详解 GitHub·点这里 GitEE·点这里 ☆☆☆
04 SpringCloud 微服务架构实战综合案例 GitHub·点这里 GitEE·点这里 ☆☆☆☆☆
05 SpringBoot 框架根底利用入门到进阶 GitHub·点这里 GitEE·点这里 ☆☆☆☆
06 SpringBoot 框架整合开发罕用中间件 GitHub·点这里 GitEE·点这里 ☆☆☆☆☆
07 数据管理、分布式、架构设计根底案例 GitHub·点这里 GitEE·点这里 ☆☆☆☆☆
08 大数据系列、存储、组件、计算等框架 GitHub·点这里 GitEE·点这里 ☆☆☆☆☆

正文完
 0