Springboot 整合 Elasticsearch(三):使用RestHighLevelClient操作ES ①

本文详细介绍了如何在Springboot应用中整合Elasticsearch8.x,包括添加依赖、配置连接、使用RestHighLevelClient进行CRUD操作以及刷新策略的选择。涵盖了创建索引、检查索引、删除索引、增加和更新文档,以及批量添加文档等内容。
摘要由CSDN通过智能技术生成

📁 前情提要:

Springboot 整合 Elasticsearch(一):Linux下安装 Elasticsearch 8.x

Springboot 整合 Elasticsearch(二):使用HTTP请求来操作ES

目录

一、Springboot 整合 Elasticsearch

1、pom.xml 中添加依赖

2、application.yml 中添加配置项

3、RestHighLevelClient API介绍

3.1、连接配置类

3.2、检查索引是否存在

3.2、创建索引

3.3、删除索引

3.4、增加文档

3.5、按主键更新文档内容

3.6、按主键删除文档内容

3.7、批量添加文档


一、Springboot 整合 Elasticsearch

1、pom.xml 中添加依赖

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

2、application.yml 中添加配置项

spring:
  elasticsearch:
    rest:
      uris: 192.168.1.250:9200

3、RestHighLevelClient API介绍

3.1、连接配置类

@Component
public class EsConfig {

    @Value("${spring.elasticsearch.rest.uris}")
    private String uris;

    /**
     * 高版本客户端
     *
     * @return
     */
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        String[] split = uris.split(",");
        HttpHost[] httpHostArray = new HttpHost[split.length];
        for (int i = 0; i < split.length; i++) {
            String item = split[i];
            httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");
        }
        // 创建RestHighLevelClient客户端
        return new RestHighLevelClient(RestClient.builder(httpHostArray));
    }
}

3.2、检查索引是否存在

    @Test
    public void checkIndex() {
        try {
            String indexName = "forest";
            boolean exists = esConfig.restHighLevelClient().indices().exists(new GetIndexRequest(indexName), RequestOptions.DEFAULT);
            System.out.println("exists:" + exists);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

3.2、创建索引

    @Test
    public void createIndex() {
        try {
            // 创建名为“森林”的索引
            String indexName = "forest";
            if (checkIndex(indexName)) {
                log.info("已存在名为{}的索引", indexName);
                return;
            }
            CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
            CreateIndexResponse createIndexResponse = esConfig.restHighLevelClient().indices().create(createIndexRequest, RequestOptions.DEFAULT);
            System.out.println("已创建索引:" + createIndexResponse.index());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public boolean checkIndex(String indexName) {
        boolean exists = false;
        try {
            exists = esConfig.restHighLevelClient().indices().exists(new GetIndexRequest(indexName), RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return exists;
    }

3.3、删除索引

    @Test
    public void deleteIndex() {
        String indexName = "forest";
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexName);
        // 发送delete请求
        try {
            AcknowledgedResponse response = esConfig.restHighLevelClient().indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
            System.out.println("是否已删除:" + response.isAcknowledged());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

3.4、增加文档

    @Test
    public void createDoc() {
        try {
            String indexName = "forest";
            ForestDoc forestDoc = new ForestDoc();
            forestDoc.setId(001L).setTitle("枫树").setImages("http://fengshu.jpg").setPrice(300.00).setInventory(600);

            // 创建索引请求对象
            IndexRequest indexRequest = new IndexRequest(indexName);
            indexRequest.id(forestDoc.getId().toString());
            indexRequest.source(JSON.toJSONString(forestDoc), XContentType.JSON);
            // 设置数据刷新策略
            indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);

            IndexResponse index = esConfig.restHighLevelClient().index(indexRequest, RequestOptions.DEFAULT);
            System.out.println("状态:" + index.status().getStatus());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 ⚠️​​​​​RefreshPolicy 刷新策略,是WriteRequest接口中的一个内部枚举
 ① IMMEDIATE:
    请求向ElasticSearch提交了数据,立即进行数据刷新,然后再结束请求。
    优点:实时性高、操作延时短。
    缺点:资源消耗高。
 ② WAIT_UNTIL:
    请求向ElasticSearch提交了数据,等待数据完成刷新,然后再结束请求。
    优点:实时性高、操作延时长。
    缺点:资源消耗低。
 ③ NONE:
    默认策略。
    请求向ElasticSearch提交了数据,不关系数据是否已经完成刷新,直接结束请求。
    优点:操作延时短、资源

3.5、按主键更新文档内容

修改 id 为 2 的 images字段内容

    @Test
    public void updateDocById() {
        try {
            String indexName = "forest";
            String id = "2";
            UpdateRequest updateRequest = new UpdateRequest(indexName, id);
            Map<String, Object> map = new HashMap<>();
            map.put("images", "http://baihuashu.jpg");
            updateRequest.doc(map);
            UpdateResponse update = esConfig.restHighLevelClient().update(updateRequest, RequestOptions.DEFAULT);
            System.out.println("状态:" + update.status().getStatus());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

3.6、按主键删除文档内容

    @Test
    public void deleteDocById() {
        String indexName = "forest";
        String id = "5";
        DeleteRequest deleteRequest = new DeleteRequest(indexName,id);
        try {
            DeleteResponse delete = esConfig.restHighLevelClient().delete(deleteRequest, RequestOptions.DEFAULT);
            System.out.println("状态:" + delete.status().getStatus());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

3.7、批量添加文档

    @Test
    public void batchCreateDoc() {
        try {
            String indexName = "forest";

            List<ForestDoc> list = new ArrayList<>();

            ForestDoc forestDoc = new ForestDoc();
            forestDoc.setId(6L).setTitle("批量_柏树").setImages("http://baishu.jpg").setPrice(1100.00).setInventory(1200);
            list.add(forestDoc);

            ForestDoc forestDoc2 = new ForestDoc();
            forestDoc2.setId(7L).setTitle("批量_苹果树").setImages("http://pingguoshu.jpg").setPrice(1200.00).setInventory(1300);
            list.add(forestDoc2);

            ForestDoc forestDoc3 = new ForestDoc();
            forestDoc3.setId(8L).setTitle("批量_海棠树").setImages("http://haitangshu.jpg").setPrice(1300.00).setInventory(1400);
            list.add(forestDoc3);

            //批量导入
            BulkRequest bulk = new BulkRequest(indexName);

            for (ForestDoc doc : list) {
                IndexRequest indexRequest = new IndexRequest();
                indexRequest.id(doc.getId().toString());
                indexRequest.source(JSON.toJSONString(doc), XContentType.JSON);
                bulk.add(indexRequest);
            }
            BulkResponse bulkResponse = esConfig.restHighLevelClient().bulk(bulk, RequestOptions.DEFAULT);
            System.out.println("状态:" + bulkResponse.status().getStatus());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


  • 20
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBoot整合Elasticsearch常用API主要包括以下几个方面: 1. 配置Elasticsearch信息 首先需要在application.yml中配置Elasticsearch的连接信息: ``` spring: data: elasticsearch: cluster-name: elasticsearch cluster-nodes: 127.0.0.1:9300 ``` 2. 创建ElasticsearchRepository 在SpringBoot中,可以通过ElasticsearchRepository来访问Elasticsearch,只需要继承该接口即可。 ``` public interface UserRepository extends ElasticsearchRepository<User, Long> { } ``` 其中,User是实体类,Long是主键类型。 3. 创建实体类 创建实体类,使用注解来映射Elasticsearch中的索引和字段。 ``` @Document(indexName = "user", type = "_doc") public class User { @Id private Long id; @Field(type = FieldType.Keyword) private String name; @Field(type = FieldType.Integer) private Integer age; // getter and setter } ``` 4. 增删改查 通过ElasticsearchRepository提供的方法,可以实现增删改查的操作。如下: ``` @Autowired UserRepository userRepository; // 新增 userRepository.save(user); // 删除 userRepository.deleteById(id); // 修改 userRepository.save(user); // 查询 Optional<User> optional = userRepository.findById(id); ``` 5. 搜索 Elasticsearch提供了丰富的搜索API,可以通过QueryBuilder来构建查询条件,通过SearchRequest来执行搜索操作。如下: ``` @Autowired RestHighLevelClient restHighLevelClient; // 构建查询条件 QueryBuilder queryBuilder = QueryBuilders.matchQuery("name", "张"); // 构建SearchRequest SearchRequest searchRequest = new SearchRequest("user"); searchRequest.types("_doc"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(queryBuilder); searchRequest.source(searchSourceBuilder); // 执行搜索 SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); // 处理搜索结果 SearchHits hits = searchResponse.getHits(); for (SearchHit hit : hits) { String sourceAsString = hit.getSourceAsString(); User user = JSON.parseObject(sourceAsString, User.class); System.out.println(user); } ``` 以上就是SpringBoot整合Elasticsearch常用API的介绍。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值