Java-Elasticsearch的增删查以及所需配置

1.引入Elasticsearch依赖

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

2.创建Elasticsearch客户端

RestHighLevelClient client = new RestHighLevelClient(
            RestClient.builder(new HttpHost("ruowu.com", 9200, "http"))
    );

3.实际使用

(1).批量添加

public R<Boolean> insert(@RequestBody EsInsertListVo esInsertListVo) {
        // 获取插入数据的索引名称和数据
        String indexName = esInsertListVo.getIndexName();
        List<EsInsertVo> list = esInsertListVo.getList();
        // 检查索引是否存在,如果不存在则抛出异常或返回错误信息
        esIndexService.checkParms(indexName, true);
        // 查询索引是否存在,如果不存在则返回错误信息
        R<Boolean> booleanR = esIndexService.selectEsIndex(new SelectEsIndex(indexName));
        if (!booleanR.getData()){
            return R.ok(false,"索引不存在,请先创建索引");
        }
        // 判断list是否为空,如果为空将抛出异常
        if (CollectionUtils.isEmpty(list)){
            throw new ServiceException("添加数据不能为空");
        }
        // 创建 BulkRequest 对象,用于批量处理请求
        BulkRequest bulkRequest = new BulkRequest();
        // 遍历list,将每个EsInsertVo对象封装成对应的IndexRequest请求,并添加到BulkRequest中
        list.stream().forEach(res -> {
            IndexRequest indexRequest = new IndexRequest(indexName);
            // 获取文档ID,并设置到IndexRequest对象中
            String indexId = res.getIndexId();
            if (StringUtils.isNotEmpty(indexId)){
                indexRequest.id(indexId);
            }
            // 获取文档内容,并设置到IndexRequest对象中
            Map<String, Object> parms = res.getParms();
            indexRequest.source(parms);
            bulkRequest.add(indexRequest);
        });
        try {
            // 使用BulkRequest对象发送请求,获取Elasticsearch服务返回的响应
            BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            // 判断响应中是否包含失败信息,如果有则返回错误信息
            if (bulk.hasFailures()){
                return R.ok(false,"添加失败");
            }
        } catch (Exception e) {
            // 发生异常时,抛出ServiceException并返回错误信息
            throw new ServiceException("批添错误");
        }
        // 如果所有文档都成功插入,则返回成功信息
        return R.ok(true,"添加成功");
    }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值