【ElasticSearch8】SpringBoot集成ElasticSearch8.x 基本应用 CRUD操作 环境安装

前言

最近在研究es的时候发现官方已经在7.15.0放弃对旧版本中的Java REST Client (High Level Rest Client (HLRC))的支持,从而替换为推荐使用的Java API Client 8.x

查看SpringBoot2.6.4的依赖,其中es的版本仅为7.15.2

  
        org.springframework.boot
        spring-boot-starter-data-elasticsearch
  

  7.15.2

因此这里我就按照官方文档使用了推荐的


      co.elastic.clients
      elasticsearch-java
      8.1.0

鉴于es8.x的资料文档目前并不是很齐全,本文中如有错误,欢迎各位指出。本文将记录一些es8.x api下的简单CRUD操作。

环境

SpringBoot 2.6.4 + ElasticSearch 8.1.0

安装

首先去官网下载最新的安装包Download Elasticsearch | Elastic

解压即可,进入/bin,启动elasticsearch.bat

访问 127.0.0.1:9200,出现es的集群信息即安装成功

可视化界面elasticsearch-head安装

在github上搜索elasticsearch-head,下载他的源码

进入源码目录执行(需安装Node.js)

npm install
npm run start

Running "connect:server" (connect) task                                                                                 
Waiting forever...                                                                                                      
Started connect web server on http://localhost:9100                                                                                                                               

即可访问9100端口访问

依赖导入

  
        com.fasterxml.jackson.core
        jackson-databind
        2.13.2
  

  
        org.glassfish
        jakarta.json
        2.0.1
  
       
  
        co.elastic.clients
        elasticsearch-java
        8.1.0
  

配置类

@Configuration
public class ElasticSearchConfig {

    //注入IOC容器
    @Bean
    public ElasticsearchClient elasticsearchClient(){
        RestClient client = RestClient.builder(new HttpHost("localhost", 9200,"http")).build();
        ElasticsearchTransport transport = new RestClientTransport(client,new JacksonJsonpMapper());
        return new ElasticsearchClient(transport);
    }
}

索引CRUD

增加index

  @Autowired
  private ElasticsearchClient client;
  
  @Test
    public void createTest() throws IOException {
        
        //写法比RestHighLevelClient更加简洁
        CreateIndexResponse indexResponse = client.indices().create(c -> c.index("user"));
    }

查询Index

    @Test
    public void queryTest() throws IOException {
        GetIndexResponse getIndexResponse = client.indices().get(i -> i.index("user"));
    }

判断index是否存在

    @Test
    public void existsTest() throws IOException {
        BooleanResponse booleanResponse = client.indices().exists(e -> e.index("user"));
        System.out.println(booleanResponse.value());
    }

删除index

@Test
    public void deleteTest() throws IOException {
        DeleteIndexResponse deleteIndexResponse = client.indices().delete(d -> d.index("user"));
        System.out.println(deleteIndexResponse.acknowledged());
    }

Document CRUD

这里准备了一个简单的实体类User用于测试

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private Integer age;
}

插入document

    @Test
    public void addDocumentTest() throws IOException {

        User user = new User("user1", 10);
        IndexResponse indexResponse = client.index(i -> i
                .index("user")

                //设置id
                .id("1")

                //传入user对象
                .document(user));

    }

进入可视化插件,可以看到数据已经成功插入

更新Document

    @Test
    public void updateDocumentTest() throws IOException {
        UpdateResponse updateResponse = client.update(u -> u
                        .index("user")
                        .id("1")
                        .doc(new User("user2", 13))
                , User.class);
    }

判断Document是否存在

    @Test
    public void existDocumentTest() throws IOException {
        BooleanResponse indexResponse = client.exists(e -> e.index("user").id("1"));
        System.out.println(indexResponse.value());
    }

查询Document

    @Test
    public void getDocumentTest() throws IOException {
        GetResponse getResponse = client.get(g -> g
                        .index("user")
                        .id("1")
                , User.class
        );
        System.out.println(getResponse.source());
    }

返回

User(name=user2, age=13)

删除Document

    @Test
    public void deleteDocumentTest() throws IOException {
        DeleteResponse deleteResponse = client.delete(d -> d
                .index("user")
                .id("1")
        );
        System.out.println(deleteResponse.id());
    }

批量插入Document

    @Test
    public void bulkTest() throws IOException {
        List userList = new ArrayList<>();
        userList.add(new User("user1", 11));
        userList.add(new User("user2", 12));
        userList.add(new User("user3", 13));
        userList.add(new User("user4", 14));
        userList.add(new User("user5", 15));
        List bulkOperationArrayList = new ArrayList<>();
        //遍历添加到bulk中
        for(User user : userList){
            bulkOperationArrayList.add(BulkOperation.of(o->o.index(i->i.document(user))));
        }
     
        BulkResponse bulkResponse = client.bulk(b -> b.index("user")
                .operations(bulkOperationArrayList));

    }

查询

    @Test
    public void searchTest() throws IOException {
        SearchResponse search = client.search(s -> s
                .index("user")
                //查询name字段包含hello的document(不使用分词器精确查找)
                .query(q -> q
                        .term(t -> t
                                .field("name")
                                .value(v -> v.stringValue("hello"))
                        ))
                //分页查询,从第0页开始查询3个document
                .from(0)
                .size(3)
                //按age降序排序
                .sort(f->f.field(o->o.field("age").order(SortOrder.Desc))),User.class
        );
        for (Hit hit : search.hits().hits()) {
            System.out.println(hit.source());
        }
    }

为了测试,我们先添加以下数据

        List userList = new ArrayList<>();
        userList.add(new User("hello world", 11));
        userList.add(new User("hello java", 12));
        userList.add(new User("hello es", 13));
        userList.add(new User("hello spring", 14));
        userList.add(new User("user", 15));

查询结果:

User(name=hello spring, age=14)
User(name=hello es, age=13)
User(name=hello java, age=12)

先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦

你可能感兴趣的:(面试,学习路线,阿里巴巴,android,前端,后端)