Elasticsearch(二)集成Spring Boot 基本的API操作

目录

[一、集成Spring Boot](#一、集成Spring Boot)

1、创建项目

[2、pom文件 查看springboot集成的依赖](#2、pom文件 查看springboot集成的依赖)

3、增加es的config类

二、索引相关API

1、创建索引

2、获取索引,判断其是否存在

3、删除索引

三、文档相关API

1、添加文档

2、获取文档,判断是否存在

3、获取文档信息

4、更新文档信息

5、删除文档信息

6、同文档批量导入数据

7、条件查询文档信息


一、集成Spring Boot

Java使用对应的rest风格调用ES是通过client依赖包进行操作的

配置需要的 maven 依赖

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

1、创建项目

如果创建项目后拉取不到对应依赖,springboot 可以选用低一些的稳定版本例如 2.3.2.RELEASE 版本

2、pom文件 查看springboot集成的依赖

(当然也可自定义ES版本)

复制代码
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

3、增加es的config类

java 复制代码
package com.example.elasticsearch_springboot_demo.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchClientConfig {

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http"),
                        new HttpHost("localhost", 9201, "http")));
        return client;
    }
}

二、索引相关API

1、创建索引

java 复制代码
@SpringBootTest
class ElasticSearchSpringbootDemoApplicationTests {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    /**
     * 【索引相关】索引创建
     */
    @Test
    void testCreateIndex() throws IOException {
        // 1、创建索引请求
        CreateIndexRequest request = new CreateIndexRequest("m_index");
        // 2、客户端执行请求 IndicesClient,执行创建请求 并获得响应结果
        CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
        // 3、查看响应结果
        System.out.println(createIndexResponse);
    }
}

2、获取索引,判断其是否存在

java 复制代码
@SpringBootTest
class ElasticSearchSpringbootDemoApplicationTests {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

   /**
     * 【索引相关】获取索引,判断其是否存在
     */
    @Test
    void  testExistIndex() throws IOException {
        // 1、获取索引请求
        GetIndexRequest request = new GetIndexRequest("m_index");
        // 2、客户端执行请求 IndicesClient,执行请求后获得是否存在结果
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        // 3、查看结果
        System.out.println(exists);
    }
}

3、删除索引

java 复制代码
@SpringBootTest
class ElasticSearchSpringbootDemoApplicationTests {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

   /**
     * 【索引相关】删除索引
     */
    @Test
    void  testDeleteIndex() throws IOException {
        // 1、删除索引请求
        DeleteIndexRequest request = new DeleteIndexRequest("m_index");
        // 2、客户端执行请求 IndicesClient,执行删除请求 并获得响应结果
        AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
        // 3、查看结果
        System.out.println(delete.isAcknowledged());
    }
}

三、文档相关API

先定义一个User类

java 复制代码
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class User {

    private String name;

    private Integer age;

}

1、添加文档

java 复制代码
@SpringBootTest
class ElasticSearchSpringbootDemoApplicationTests {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

   /**
     * 【文档相关】添加文档
     */
    @Test
    void  testAddDocument() throws IOException {
        // 1、user对象
        User user = new User("marvin", 26);

        // 2、创建请求对象,并组装文档数据
        IndexRequest request = new IndexRequest("m_index");
        // 定义文档内容
        // 规则 put /m_index/_doc/1
        request.id("1");
        request.timeout(TimeValue.timeValueSeconds(1));
        request.timeout("1s");
        //将user数据放入请求json
        request.source(JSON.toJSONString(user), XContentType.JSON);

        // 3、客户端发送请求,获取响应的结果
        IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
        // 4、查看结果
        System.out.println(indexResponse.toString());// 对应的文档信息
        System.out.println(indexResponse.status());// 执行命令的返回状态

    }
}

2、获取文档,判断是否存在

get /index/doc/1

java 复制代码
@SpringBootTest
class ElasticSearchSpringbootDemoApplicationTests {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

   /**
     * 【文档相关】获取文档,判断是否存在 get /index/doc/1
     */
    @Test
    void testIsExistsDocument() throws IOException {
        GetRequest getRequest = new GetRequest("m_index", "1");
        // 不获取返回的_source 的上下文
        getRequest.fetchSourceContext(new FetchSourceContext(false));
        getRequest.storedFields("_none_");

        boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }
}

3、获取文档信息

java 复制代码
@SpringBootTest
class ElasticSearchSpringbootDemoApplicationTests {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

   /**
     * 【文档相关】获取文档信息
     */
    @Test
    void testGetDocument() throws IOException {
        GetRequest getRequest = new GetRequest("m_index", "1");
        GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);
        System.out.println(documentFields.getSourceAsString());// 打印文档内容
        System.out.println(documentFields);// 返回的全部内容和命令是一样的
    }
}

4、更新文档信息

java 复制代码
@SpringBootTest
class ElasticSearchSpringbootDemoApplicationTests {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

   /**
     * 【文档相关】更新文档信息
     */
    @Test
    void testUpdateDocument() throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("m_index", "1");
        updateRequest.timeout("1s");

        User user = new User("jerry", 28);
        updateRequest.doc(JSON.toJSONString(user), XContentType.JSON);

        UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println(updateResponse.status());
    }
}

5、删除文档信息

java 复制代码
@SpringBootTest
class ElasticSearchSpringbootDemoApplicationTests {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

   /**
     * 【文档相关】删除文档信息
     */
    @Test
    void testDeleteDocument() throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest("m_index", "1");
        deleteRequest.timeout("1s");

        DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(deleteResponse.status());
    }
}

6、同文档批量导入数据

java 复制代码
@SpringBootTest
class ElasticSearchSpringbootDemoApplicationTests {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

   /**
     * 【文档相关】特殊的,批量导入数据
     */
    @Test
    void  testBulkDocument() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");

        List<User> userList = new ArrayList<>();
        userList.add(new User("marvin1", 26));
        userList.add(new User("marvin2", 26));
        userList.add(new User("marvin3", 26));
        userList.add(new User("marvin4", 26));
        userList.add(new User("marvin5", 26));
        userList.add(new User("marvin6", 26));

        // 批处理请求
        for (int i=0; i<userList.size();i++){
            // 批量更新和批量删除,就再这里修改对应请求就可以了
            bulkRequest.add(new IndexRequest("m_index")
                    .id(""+(i+1))
                    .source(JSON.toJSONString(userList.get(i)), XContentType.JSON));
        }
        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulkResponse.hasFailures());// 是否失败,返回false 代表成功!

    }
}

7、条件查询文档信息

java 复制代码
@SpringBootTest
class ElasticSearchSpringbootDemoApplicationTests {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

   /**
     * 查询
     * searchRequest 搜索请求
     * SearchSourceBuilder 搜索条件构造
     */
    @Test
    void testSearch() throws IOException {
        // 1、创建搜索请求
        SearchRequest searchRequest = new SearchRequest("m_index");

        // 2、构建搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        /**
         * 查询条件,可以使用QueryBuilders快速匹配
         */
        //精确匹配:termQuery
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "marvin");
        //匹配所有
        MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();

        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));


        // 3、将查询条件放入请求
        searchRequest.source(sourceBuilder);
        // 4、执行请求
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        // 5、所有结果都封装在 SearchHits 里面,通过getHits()得到
        System.out.println(JSON.toJSONString(searchResponse.getHits()));
        System.out.println("===================================");

        //循环输出每一条数据结果为map结构
        for (SearchHit documentFields : searchResponse.getHits().getHits()){
            System.out.println(documentFields.getSourceAsMap());// 转换为map结构
        }

    }
}
相关推荐
IT毕设实战小研2 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
一只爱撸猫的程序猿3 小时前
使用Spring AI配合MCP(Model Context Protocol)构建一个"智能代码审查助手"
spring boot·aigc·ai编程
甄超锋4 小时前
Java ArrayList的介绍及用法
java·windows·spring boot·python·spring·spring cloud·tomcat
武昌库里写JAVA6 小时前
JAVA面试汇总(四)JVM(一)
java·vue.js·spring boot·sql·学习
Pitayafruit7 小时前
Spring AI 进阶之路03:集成RAG构建高效知识库
spring boot·后端·llm
zru_96027 小时前
Spring Boot 单元测试:@SpyBean 使用教程
spring boot·单元测试·log4j
甄超锋8 小时前
Java Maven更换国内源
java·开发语言·spring boot·spring·spring cloud·tomcat·maven
还是鼠鼠9 小时前
tlias智能学习辅助系统--Maven 高级-私服介绍与资源上传下载
java·spring boot·后端·spring·maven
水无痕simon12 小时前
5 索引的操作
数据库·elasticsearch
舒一笑13 小时前
Started TttttApplication in 0.257 seconds (没有 Web 依赖导致 JVM 正常退出)
jvm·spring boot·后端