ElasticSearch学习随笔之java api 操作

ElasticSearch

1、ElasticSearch学习随笔之基础介绍
2、ElasticSearch学习随笔之简单操作
3、ElasticSearch学习随笔之java api 操作
4、ElasticSearch学习随笔之SpringBoot Starter 操作
5、ElasticSearch学习随笔之嵌套操作

ElasticSearch,创始人 Shay Banon(谢巴农)
本文主讲 ElasticSearch Java api 调用操作。


文章目录

  • ElasticSearch
  • 前言
  • 一、引入ES Client jar包
  • 二、操作案例
    • 2.0 实例化 ES Client 客户端
    • 2.1 增
    • 2.2 删
    • 2.3 改
    • 2.4 查
      • 2.4.1 按照 ID 获取
      • 2.4.2 多字段查询
      • 2.4.3 分页查询
      • 2.4.4 按照游标(scroll)查询
      • 2.4.5 分页、游标、高亮查询
  • 总结


前言

本文主要对ElasticSearch 通过java api 操作基础案例。


一、引入ES Client jar包

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

二、操作案例

2.0 实例化 ES Client 客户端

private static final String HOSTNAME = "192.168.0.71";
   private static final int PORT = 9200;
   private static final RestHighLevelClient client = getClient();

   public static RestHighLevelClient getClient(){
       RestClientBuilder builder = RestClient.builder(
               new HttpHost(HOSTNAME, PORT, "http")
       );
       RestHighLevelClient client = new RestHighLevelClient(builder);
       return client;
   }

2.1 增

public static void addIndex(RestHighLevelClient client) throws IOException {
        /*初始化 查询请求操作,指定操作 index 名称*/
        IndexRequest indexRequest = new IndexRequest(INDEX_NAME);
        /*实例化数据*/
        Tender tender = new Tender("鉴定药敏分析仪"
                ,"四川国际招标有限责任公司"
                ,"招标结果"
                ,"5");
        String json = JSONObject.toJSONString(tender);
        /*设置 类型,7.x 不用设置,默认是 _doc*/
        indexRequest.type("data");
        /*数据转换成  json 添加进去*/
        indexRequest.source(json, XContentType.JSON);
        /*添加索引 */
        client.index(indexRequest, RequestOptions.DEFAULT);
        client.close();
    }

2.2 删

public static void deleteById(String id) throws IOException {
        /*初始化 get 请求*/
        GetRequest request = new GetRequest(INDEX_NAME, TYPE, id);
        /*判断是否存在数据,用 id 查询*/
        boolean exists = client.exists(request, RequestOptions.DEFAULT);
        if(exists){
            /*初始化 Delete 请求*/
            DeleteRequest deleteRequest = new DeleteRequest(INDEX_NAME, TYPE, id);
            /*执行 delete 操作*/
            client.delete(deleteRequest, RequestOptions.DEFAULT);
        }
        client.close();
    }

2.3 改

public static void updateById(String id) throws IOException {
        /*初始化 get 请求*/
        GetRequest request = new GetRequest(INDEX_NAME, TYPE, id);
        /*判断是否存在*/
        boolean exists = client.exists(request, RequestOptions.DEFAULT);
        if(exists){
            /*初始化 Update 请求,按照 id更新*/
            UpdateRequest updateRequest = new UpdateRequest(INDEX_NAME, TYPE, id);
            /*组装 数据*/
            Tender tender = new Tender("鉴定药敏分析仪"
                    ,"四川国际招标有限责任公司"
                    ,"招标结果"
                    ,"100");
            updateRequest.doc(JSONObject.toJSONString(tender), XContentType.JSON);
            /*执行更新操作*/
            client.update(updateRequest, RequestOptions.DEFAULT);
        }
        client.close();
    }

2.4 查

2.4.1 按照 ID 获取

public static Tender searchById(String id) throws IOException {
        /*初始化 get  请求*/
        GetRequest request = new GetRequest(INDEX_NAME, TYPE, id);
        /*按照 ID 获取数据*/
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        Tender tender = JSONObject.parseObject(response.getSourceAsString(), Tender.class);
        client.close();
        return tender;
    }

2.4.2 多字段查询

public static List<Tender>  searchList(String keyword) throws IOException {
        /*初始化查询请求*/
        SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
        /*初始化 构建 查询 builder*/
        SearchSourceBuilder builder = new SearchSourceBuilder();
        /*初始化 多字段 查询 builder*/
        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(keyword, "product_agency");
        /*设置 查询 多字段查询*/
        builder.query(multiMatchQueryBuilder);
        /*把 构建好的 查询 封装到 查询请求中*/
        searchRequest.source(builder);
        /*执行查询*/
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = response.getHits().getHits();
        List<Tender> collect = Arrays.stream(hits).map(hit -> JSONObject.parseObject(hit.getSourceAsString(), Tender.class)).collect(Collectors.toList());
        client.close();
        return collect;
    }

2.4.3 分页查询

public static List<Tender> searchListByPages(String keyword, int pageNo, int pageSize) throws IOException {
        /*构建查询请求*/
        SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
        /*构建查询条件 builder*/
        SearchSourceBuilder builder = new SearchSourceBuilder();
        /*构建 多字段 查询*/
        builder.query(QueryBuilders.multiMatchQuery(keyword, "product_name","product_agency"));
        /*设置分页 每页大小*/
        builder.size(pageSize);
        /*设置 分页 page no*/
        builder.from(pageNo > 1 ?(pageNo - 1) * pageSize : 0);
        /*把组装好的 查询builder 设置到 查询请求中*/
        searchRequest.source(builder);
        /*执行查询*/
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = response.getHits().getHits();
        List<Tender> collect = Arrays.stream(hits).map(hit -> JSONObject.parseObject(hit.getSourceAsString(), Tender.class)).collect(Collectors.toList());
        System.out.println(response.getHits().getTotalHits());
        client.close();
        return collect;
    }

2.4.4 按照游标(scroll)查询

public static List<Tender> searchListByScrollPages(String keyword, String scrollId, int pageSize) throws IOException {
        SearchResponse response = null;
        if(Objects.nonNull(scrollId)){
            /*如果游标 id 不为空的话,直接按照 游标 获取数据*/
            SearchScrollRequest searchScrollRequest = new SearchScrollRequest(scrollId);
            /*设置游标id, 有效时间 5 分钟*/
            searchScrollRequest.scroll(TimeValue.timeValueMinutes(5));
            response = client.scroll(searchScrollRequest, RequestOptions.DEFAULT);
        }else{
            SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
            SearchSourceBuilder builder = new SearchSourceBuilder();
            builder.query(QueryBuilders.multiMatchQuery(keyword, "product_name","product_agency"));
            builder.size(pageSize);
            searchRequest.source(builder);
            searchRequest.scroll(TimeValue.timeValueMinutes(5));
            response = client.search(searchRequest, RequestOptions.DEFAULT);
        }
        SearchHit[] hits = response.getHits().getHits();
        System.out.println(response.getHits().getTotalHits());
        System.out.println(response.getScrollId());
        List<Tender> collect = Arrays.stream(hits).map(hit -> JSONObject.parseObject(hit.getSourceAsString(), Tender.class)).collect(Collectors.toList());
        client.close();
        return collect;
    }

2.4.5 分页、游标、高亮查询

public static List<Tender> searchListByScrollPageWithHighLight(String keyword, String scrollId, int pageSize) throws IOException {
        SearchResponse response = null;
        if(Objects.nonNull(scrollId)){
            SearchScrollRequest searchScrollRequest = new SearchScrollRequest(scrollId);
            searchScrollRequest.scroll(TimeValue.timeValueMinutes(5));
            response = client.scroll(searchScrollRequest, RequestOptions.DEFAULT);
        }else{
            SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
            SearchSourceBuilder builder = new SearchSourceBuilder();
            builder.query(QueryBuilders.multiMatchQuery(keyword, "product_name","product_agency"));
            //设置高亮查询 初始化 高亮 builder
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            /*设置高亮的 字段*/
            highlightBuilder.field("product_name");
            /*设置高亮标签字段*/
            highlightBuilder.preTags("");
            highlightBuilder.postTags("");
            /*把高亮builder 设置到 查询 builder 里面*/
            builder.highlighter(highlightBuilder);
            builder.size(pageSize);
            searchRequest.source(builder);
            searchRequest.scroll(TimeValue.timeValueMinutes(5));
            response = client.search(searchRequest, RequestOptions.DEFAULT);
        }
        SearchHit[] hits = response.getHits().getHits();
        System.out.println(response.getHits().getTotalHits());
        System.out.println(response.getScrollId());
        List<Tender> collect = Arrays.stream(hits).map(hit -> JSONObject.parseObject(hit.getSourceAsString(), Tender.class)).collect(Collectors.toList());
        for (SearchHit hit : hits) {
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField productName = highlightFields.get("product_name");
            if(Objects.nonNull(productName)){
                System.out.println(productName);
            }
        }
        client.close();
        return collect;
    }

总结

以上是 java api 对 ES 的增删改查的简单案例,方便公司里面临时有需要对ES操作大量数据是,可以直接copy 执行。
SpringBoot整合ES篇

你可能感兴趣的:(搜索引擎,JAVA后台,java,elasticsearch,分布式,中间件)