elasticsearch(RestHighLevelClient API操作)(黑马)

操作全是换汤不换药,创建一个request,然后使用client发送就可以了

一、增加索引库数据

java 复制代码
    @Test
    void testAddDocument() throws IOException {
        //从数据库查出数据
        Writer writer = writerService.getById(199);
        //将查出来的数据处理成json字符串
        String json = JSON.toJSONString(writer);

        // 1.准备Request
        IndexRequest request = new IndexRequest("writer").id(String.valueOf(writer.getId()));
        // 2.准备请求参数DSL,其实就是文档的JSON字符串
        request.source(json, XContentType.JSON);
        // 3.发送请求
        client.index(request, RequestOptions.DEFAULT);
    }

二、查询索引库顺序

java 复制代码
    @Test
    void testGetDocumentById() throws IOException {
        // 1.准备Request      // GET /hotel/_doc/{id}
        GetRequest request = new GetRequest("writer", "199");
        // 2.发送请求
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        // 3.解析响应结果
        String json = response.getSourceAsString();

        Writer writer = JSON.parseObject(json, Writer.class);
        System.out.println("writerDoc = " + writer);
    }

三、删除索引库数据

java 复制代码
@Test
    void testDeleteDocumentById() throws IOException {
        // 1.准备Request      // DELETE /hotel/_doc/{id}
        DeleteRequest request = new DeleteRequest("hotel", "61083");
        // 2.发送请求
        client.delete(request, RequestOptions.DEFAULT);
    }

四、修改索引库数据

java 复制代码
@Test
    void testUpdateById() throws IOException {
        // 1.准备Request
        UpdateRequest request = new UpdateRequest("hotel", "61083");
        // 2.准备参数
        request.doc(
                "price", "870"
        );
        // 3.发送请求
        client.update(request, RequestOptions.DEFAULT);
    }

五、批量导入数据

java 复制代码
@Test
    void testBulkRequest() throws IOException {
        List<Writer> list = writerService.list();
        BulkRequest request = new BulkRequest();
        for (Writer writer : list) {
            HotelDoc hotelDoc = new HotelDoc(hotel);
            String json = JSON.toJSONString(writer);
            request.add(new IndexRequest("writer").id(String.valueOf(writer.getId())).source(json, XContentType.JSON));
        }

        client.bulk(request, RequestOptions.DEFAULT);
    }
相关推荐
Elasticsearch7 分钟前
悦高软件带你体验 ES9.5 的性能跃升之路
elasticsearch
渣渣盟19 分钟前
Flink 流式写入文件终极指南:从 Row Format 到 Bucket 分区的深度剖析
大数据·flink
Elastic 中国社区官方博客36 分钟前
跳过 mapping 爆炸:ES|QL 无需动态 mapping 即可查询无 schema JSON key
大数据·人工智能·sql·elasticsearch·搜索引擎·json·全文检索
chaochaoIT1231 小时前
2026中小企业进销存技术选型标准|从架构、数据、运维多维度商用能力核验
大数据·运维·架构·能源·制造·零售·交通物流
小白一枚131 小时前
[学习笔记]Kafka 篇:从原理到实战的一站式指南
大数据·运维·elk·kafka·个人开发
CIO_Alliance1 小时前
AI算法系列(3)| 实时数据管道:CDC+Flink实现库存异动秒级响应
大数据·人工智能·flink
Gavynlee1 小时前
Git 操作问题排查与解决方案记录(Gitee 实战)
git·elasticsearch·gitee
每日新鲜事1 小时前
北大医院引入WPS Comate智能助手,加速医院管理智能化进程
大数据·人工智能·wps
V哥AI增长14 小时前
宠物行业GEO机制:AI如何推荐医院与产品
人工智能·搜索引擎·宠物