【Elasticsearch】04-RestAPI

1. 引入依赖

java 复制代码
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>

2. 覆盖SpringBoot中的版本

需要在父工程里面进行修改,防止版本覆盖。

java 复制代码
  <properties>
      <maven.compiler.source>11</maven.compiler.source>
      <maven.compiler.target>11</maven.compiler.target>
      <elasticsearch.version>7.12.1</elasticsearch.version>
  </properties>

3. 初始化RestHighLevelClient

java 复制代码
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
        HttpHost.create("http://192.168.150.101:9200")
));

4. 创建索引

java 复制代码
    @Test
    void testCreate() {
        // 1. 准备 Request对象
        CreateIndexRequest request = new CreateIndexRequest("items");

        // 2. 准备请求参数
        request.source(MAPPING_TEMPLATE, XContentType.JSON);

        // 3. 发送请求
        try {
            restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

5. Mapping操作

java 复制代码
    @Test
    void testCreate() {
        // 1. 准备 Request对象
        CreateIndexRequest request = new CreateIndexRequest("items");

        // 2. 准备请求参数
        request.source(MAPPING_TEMPLATE, XContentType.JSON);

        // 3. 发送请求
        try {
            restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    void testGet() {
        GetIndexRequest request = new GetIndexRequest("items");
        try {
            // GetIndexResponse getIndexResponse = restHighLevelClient.indices().get(request, RequestOptions.DEFAULT);
            boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
            System.out.println(exists);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    void testDelete() {
        DeleteIndexRequest request = new DeleteIndexRequest("items");
        try {
            restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

6. 文档操作

java 复制代码
@SpringBootTest(properties = "spring.profiles.active=local")
public class ElasticDocumentTest {
    private RestHighLevelClient client;

    @Resource
    private IItemService itemService;

    @BeforeEach
    public void init() {
        client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://nuaamvp.cn:9200")
        ));
    }

    @AfterEach
    void tearDown() {
        if (client!=null) {
            try {
                client.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Test
    void testIndexDoc() {
        Item item = itemService.getById(317578L);
        ItemDoc itemDoc = BeanUtil.copyProperties(item, ItemDoc.class);
        // 1. 创建对象
        IndexRequest request = new IndexRequest("items").id(itemDoc.getId());

        // 2. 准备请求参数
        request.source(JSONUtil.toJsonStr(itemDoc), XContentType.JSON);
        try {
            // 3. 发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    void testGetDoc() throws IOException {
        // 1. 准备请求对象
        GetRequest request = new GetRequest("items", "317578");
        // 2. 发送请求
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        // 3. 获取响应结果
        String json = response.getSourceAsString();

        ItemDoc itemDoc = JSONUtil.toBean(json, ItemDoc.class);
        System.out.println(itemDoc);
    }

    @Test
    void testDeleteDoc() throws IOException {
        DeleteRequest request = new DeleteRequest("items", "317578");
        client.delete(request, RequestOptions.DEFAULT);
    }

    @Test
    void testUpdateDoc() throws IOException {
        UpdateRequest request = new UpdateRequest("items", "317578");
        request.doc(
                "price", 198,
                "commentCount", 128
        );
        client.update(request, RequestOptions.DEFAULT);
    }
}

7.数据批量导入

java 复制代码
    @Test
    void testLoadItemDocs() throws IOException {
        // 分页查询商品数据
        int pageNo = 1;
        int size = 1000;
        while (true) {
            Page<Item> page = itemService.lambdaQuery().eq(Item::getStatus, 1).page(new Page<Item>(pageNo, size));
            // 非空检验
            List<Item> items = page.getRecords();
            if (CollUtils.isEmpty(items)) {
                return ;
            }
            log.info("加载第{}页数据,共{}条",pageNo, items.size());
            // 1. 创建请求对象
            BulkRequest request = new BulkRequest("items");
            for(Item item:items) {
                // 2.1 itemDoc
                ItemDoc itemDoc = BeanUtil.copyProperties(item, ItemDoc.class);
                request.add(new IndexRequest()
                        .id(itemDoc.getId())
                        .source(JSONUtil.toJsonStr(itemDoc), XContentType.JSON));
            }
            // 3. 发送请求
            client.bulk(request, RequestOptions.DEFAULT);
            // 翻页
            pageNo ++;
        }
    }
相关推荐
一瓣橙子几秒前
缺少关键的 MapReduce 框架文件
大数据·mapreduce
永洪科技7 小时前
永洪科技荣获商业智能品牌影响力奖,全力打造”AI+决策”引擎
大数据·人工智能·科技·数据分析·数据可视化·bi
weixin_307779138 小时前
Hive集群之间迁移的Linux Shell脚本
大数据·linux·hive·bash·迁移学习
大只鹅8 小时前
解决 Spring Boot 对 Elasticsearch 字段没有小驼峰映射的问题
spring boot·后端·elasticsearch
上海锝秉工控10 小时前
防爆拉线位移传感器:工业安全的“隐形守护者”
大数据·人工智能·安全
cv高级工程师YKY11 小时前
SRE - - PV、UV、VV、IP详解及区别
大数据·服务器·uv
bxlj_jcj12 小时前
深入Flink核心概念:解锁大数据流处理的奥秘
大数据·flink
云资源服务商12 小时前
阿里云Flink:开启大数据实时处理新时代
大数据·阿里云·云计算
Aurora_NeAr13 小时前
Spark SQL架构及高级用法
大数据·后端·spark
王小王-12313 小时前
基于Hadoop的公共自行车数据分布式存储和计算平台的设计与实现
大数据·hive·hadoop·分布式·hadoop公共自行车·共享单车大数据分析·hadoop共享单车