Bootstrap

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

目录

一、集成Spring Boot

 1、创建项目

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类

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、创建索引

@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、获取索引,判断其是否存在

@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、删除索引

@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类

@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class User {

    private String name;

    private Integer age;

}

1、添加文档

@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

@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、获取文档信息

@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、更新文档信息

@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、删除文档信息

@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、同文档批量导入数据

@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、条件查询文档信息

@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结构
        }

    }
}

;