spring cloud 整合elasticsearch 单个、批量添加文档

创建完索引后,我们就要添加数据开始处理业务了,不知道如何创建索引的同学可以看这篇文章

spring cloud 整合elasticsearch 创建索引支持ik中文分词和拼音分词_u010401588的博客-CSDN博客​​​​​​

 添加有两种:单个(同步),批量(异步)添加文档

1.单个同步添加数据

/**
     * 单条添加文档
     * @param indexEnum 索引
     * @param key id
     * @param jsonValue  文档json
     * @param xContentBuilder  索引信息
     * @return
     */
    public boolean addOne(IndexEnum indexEnum, String key, String jsonValue, XContentBuilder xContentBuilder) {
        //获得连接
        RestHighLevelClient client=this.restHighLevelClient();
        try {
            //创建索引
            createIndex(indexEnum, xContentBuilder);
            IndexRequest indexRequest = new IndexRequest(indexEnum.getCode());
            //将文档源设置为索引,文档内容类型
            indexRequest.source(jsonValue, XContentType.JSON);
            indexRequest.id(key);
            //添加数据
            IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
            log.info("add doc status:{} ,mas:{}", indexResponse.status(), JSON.toJSONString(indexResponse));
            return indexResponse != null && indexResponse.status() == RestStatus.OK;
        } catch (Exception e) {
            log.info("addOne doc 异常! info:{}",jsonValue);
            return false;
        }finally {
            try {
                //关闭连接
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 调用测试

public void  create( ){

        ProductIndex productIndex = new ProductIndex();
        productIndex.setProductName("美国雅诗兰黛特润修护肌透精华露小棕瓶精华(七代)100ml");
        productIndex.setBrandName("雅诗兰黛");
        productIndex.setProductId(12345678987654321L);
        String key = productIndex.getProductId().toString();
        XContentBuilder xContentBuilder = ElasticsearchConfig.generateBuilder(ProductIndex.class);
        boolean status = esService.addOne(IndexEnum.TEST, key, JSON.toJSONString(productIndex), xContentBuilder);
        log.info("添加文档{}结果:{}",key,status?"成功":"失败");
    }

2.批量添加文档

   /**
     * 批量添加索引文档
     * @param indexEnum 索引
     * @param entities 文档
     * @param xContentBuilder 索引mapping
     * @return
     */
    public  boolean addBatch(IndexEnum indexEnum, List entities, XContentBuilder xContentBuilder) {
        RestHighLevelClient client=this.restHighLevelClient();
        try {
            Long startTime = System.currentTimeMillis();
            log.info("增加记录 {}条 start date :{}", entities.size(), startTime);
            BulkRequest bulkRequest = new BulkRequest();
            this.createIndex(indexEnum, xContentBuilder);
            List productIds = Lists.newArrayList();
            for (int i = 0; i < entities.size(); i++) {
                T entity = entities.get(i);
                String jsonValue = JSON.toJSONString(entity);
                String key = this.getId(entity);
                IndexRequest indexRequest = new IndexRequest(indexEnum.getCode());
                indexRequest.source(jsonValue, XContentType.JSON);
                indexRequest.id(key);
                bulkRequest.add(indexRequest);
                productIds.add(Long.valueOf(key));

            }
            log.info("执行add-ids:[{}]",JSON.toJSONString(productIds));
            BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            /** 获得失败标准**/
            if (bulkResponse.hasFailures()) {
                log.info("创建失败:" + indexEnum.getCode() + ":" + bulkResponse.buildFailureMessage());
                productService.mqId(productIds);
            }
            Long endTime = System.currentTimeMillis();
            log.info("增加记录 end date :{} ,耗时{}毫秒", endTime, endTime - startTime);
            return true;
        } catch (Exception e) {
            log.info("创建商品引擎失败:" + indexEnum.getCode() + ":" + e.getMessage());
            return false;
        }finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

调用测试

    public void  createBatch( ){
        List productIndexList = Lists.newArrayList();
        ProductIndex productIndex = new ProductIndex();
        productIndex.setProductName("美国Estee Lauder雅诗兰黛鲜活亮采红石榴二合一洁面乳125ml两支装");
        productIndex.setBrandName("雅诗兰黛");
        productIndex.setProductId(12345678987654321L);
        String key = productIndex.getProductId().toString();
        productIndexList.add(productIndex);
        XContentBuilder xContentBuilder = ElasticsearchConfig.generateBuilder(ProductIndex.class);
        boolean status = esService.addBatch(IndexEnum.TEST, productIndexList, xContentBuilder);
        log.info("添加文档{}结果:{}",key,status?"成功":"失败");
    }

你可能感兴趣的:(elasticsearch,spring,elasticsearch,spring,cloud,搜索引擎)