SpringBoot集成ElasticSearch

2023-10-27

学习网站:官网

参考视频(狂神)
依赖导入
在这里插入图片描述在这里插入图片描述

创建一个SpringBoot项目,加进入依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

设置js版本是6
在这里插入图片描述
由于我们的elasticSearch安装的是7.6.1,为了保证版本不正确,先修改版本。
在这里插入图片描述

测试API

  • 创建一个索引
package com.dongmu.elasticsearchapi;

import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;

@SpringBootTest
class ElasticSearchApiApplicationTests {

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

    @Test
    void contextLoads() throws IOException {
//        创建一个创建索引的请求的对象
        CreateIndexRequest request = new CreateIndexRequest("dongmu_index");
//        执行创建请求
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse);
    }
}

在这里插入图片描述
在这里插入图片描述

  • 判断某一个索引是否存在
@Test
    void testExist() throws IOException {
        GetIndexRequest dongmu_index = new GetIndexRequest("dongmu_index");
        //判断是否存在某一个索引
        boolean exists = restHighLevelClient.indices().exists(dongmu_index, RequestOptions.DEFAULT);

        System.out.println(exists);
    }
  • 测试删除一个索引
@Test
    void testDelete() throws IOException {
        DeleteIndexRequest dongmu_index = new DeleteIndexRequest("dongmu_index");
        //删除一个索引
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(dongmu_index, RequestOptions.DEFAULT);
        //输出查看是否删除成功
        System.out.println(delete.isAcknowledged());
    }
  • 添加文档
@Test
    void testAddDoc() throws IOException {
//        创建对象
        User user = new User("dongmu",22);
//      创建请求
        IndexRequest request = new IndexRequest("dongmu");

        //定义规则
        //  put /dongmu/_doc/5
        request.id("5");
        //设置超时时间
        request.timeout(new TimeValue(1, TimeUnit.SECONDS));

        //把数据放入请求
        request.source(JSON.toJSONString(user), XContentType.JSON);
//        客户端发送请求,获取响应结果
        IndexResponse index = restHighLevelClient.index(request, RequestOptions.DEFAULT);

        System.out.println(index.toString());
        System.out.println(index.status());

    }

User类里面只有name和age属性。
在这里插入图片描述

  • 查询文档的信息
@Test
    void testGetDoc() throws IOException {
        GetRequest dongmu = new GetRequest("dongmu","1");

        //不获取返回的上下文了,效率更高。
//        dongmu.fetchSourceContext(new FetchSourceContext(false));
//        dongmu.storedFields("_none_");

        boolean exists = restHighLevelClient.exists(dongmu, RequestOptions.DEFAULT);

        //判断文档是否存在
        System.out.println(exists);

        //获取文档信息
        GetResponse documentFields = restHighLevelClient.get(dongmu, RequestOptions.DEFAULT);
        //打印文档的内容
        System.out.println(documentFields.getSourceAsString());
        System.out.println(documentFields);
    }
  • 更新文档信息
 @Test
    void testUpdateDoc() throws IOException {
        UpdateRequest dongmu = new UpdateRequest("dongmu","1");

        //设置超时时间
        dongmu.timeout("1s");

        User user = new User("冬木",18);

        //设置更新的数据
        dongmu.doc(JSON.toJSONString(user),XContentType.JSON);

        //执行请求

        UpdateResponse update = restHighLevelClient.update(dongmu, RequestOptions.DEFAULT);

        System.out.println(update.toString());
        System.out.println(update.status());


    }

这个更新相当于是post,不是put,所以只是更细粒度的修改而不是覆盖。

  • 批量插入数据
@Test
    void testQueryDoc() throws IOException {
        //批量导入数据
        BulkRequest bulkRequest = new BulkRequest();

        bulkRequest.timeout("10s");

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

        for (int i = 0; i < 10; i++) {
            list.add(new User("冬木"+i,i));
        }


        for (int i = 0; i < list.size(); i++) {
            bulkRequest.add(new IndexRequest("dongmu")
                    .id(i+5+"")
                    .source(JSON.toJSONString(list.get(i)),XContentType.JSON));
        }


        //执行批处理请求
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

        //查看是否执行成功,false表示成功
        System.out.println(bulk.hasFailures());
    }
  • 批量更新和批量删除
 for (int i = 0; i < list.size(); i++) {
            bulkRequest.add(new IndexRequest("dongmu")
                    .id(i+5+"")
                    .source(JSON.toJSONString(list.get(i)),XContentType.JSON));
        }

在add方法中添加不同的请求即可。

  • 搜索
@Test
    void testBatchQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("dongmu");

        //构建搜索的条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //使用QueryBuilders构建工具来实现

        //精确查询
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("age", "18");
//        MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
        searchSourceBuilder.query(termQueryBuilder);

        //对查询结果进行分页
//        searchSourceBuilder.from(1);

        //对查询设置超时时间
        searchSourceBuilder.timeout(new TimeValue(60,TimeUnit.SECONDS));

//        searchSourceBuilder.size(5);

        searchRequest.source(searchSourceBuilder);

        //执行查询,获取查询结果
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        SearchHits hits = search.getHits();

        System.out.println(JSON.toJSONString(hits));

        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsMap());
        }


    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringBoot集成ElasticSearch 的相关文章

随机推荐