SpringBoot集成ElasticSearch

在SpringBoot集成ElasticSearch


在上一章我们已经学习了ElasticSearch基本使用,现在我们来看看如何在java中使用ElasticSearch。使用前先启动ElasticSearch和ElasticSearch-Head(为了方便我们查看数据),不知道怎么做的可以参考上一章(注意:本次测试环境使用的是JDK1.8+SpringBoot2.2.5.RELEASE+ElasticSearch7.6.1)

1.导入maven依赖

<properties>
    <java.version>1.8</java.version>
    <elasticsearch.version>7.6.1</elasticsearch.version>
</properties>

<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.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.62</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

2.将我们的ElasticSearch注入到SpringBoot中

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

3.测试ElasticSearch在java中的使用

  1. 对索引的相关操作

    创建ES索引

    @Resource
    private RestHighLevelClient client;
    
    @Test
    void testCreateIndex() throws IOException {
        //1.创建索引的请求,如果该索引已存在则会报错
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("aaron_index");
        //2.执行请求返回一个地址值
        CreateIndexResponse createIndexResponse = client.indices()
                .create(createIndexRequest, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse);
    }
    

    获取ES索引,判断是否存在

    @Test
    void testGetIndex() throws IOException {
        //1.获取索引的请求
        GetIndexRequest getIndexRequest = new GetIndexRequest("aaron_index");
        //2.执行请求返回boolean
        boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        if (exists) {
            System.out.println("该索引已存在");
        } else {
            System.out.println("该索引还未创建");
        }
    }
    

    删除ES索引

    @Test
    void testDeleteIndex() throws IOException {
        //1.删除索引的请求
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("aaron_index");
        //2.执行请求后返回删除的状态
        AcknowledgedResponse delete = client.indices()
                    .delete(deleteIndexRequest, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }
    
  2. 对文档的相关操作

    添加一条文档信息

    @Test
    void testAddDocument() throws IOException {
        //1.创建对象
        User user = new User("Aaron", 20);
        //2.创建请求
        IndexRequest request = new IndexRequest("aaron_index");
        //3.设置一些规则(PUT /aaron_index/_doc/1)
        request.id("1");
        request.timeout(TimeValue.timeValueSeconds(1));
        //4.将我们的数据放入请求
        request.source(JSON.toJSONString(user), XContentType.JSON);
        //5.客户端发送请求,获取响应的结果
        IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
        System.out.println(indexResponse.toString());
        System.out.println(indexResponse.status());
    }
    

    添加多条文档信息

    @Test
    void testInsertDataInBulk() throws IOException {
        //1.创建BulkRequest对象,并设置超时时间
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");
        //2.创建多个对象
        List<User> userList = new ArrayList<>();
        userList.add(new User("aaron1",18));
        userList.add(new User("aaron2",19));
        userList.add(new User("aaron3",20));
        userList.add(new User("aaron4",21));
        //3.批处理请求(PUT /aaron_index/_doc/1)
        for (int i = 0; i <userList.size() ; i++) {
            bulkRequest.add(
                    //3.1.要插入的索引
                    new IndexRequest("aaron_index")
                    //3.2.设置id为(i+1)
                    .id(""+(i+1))
                    //3.3.放入我们要插入的数据
                    .source(JSON.toJSONString(userList.get(i)),XContentType.JSON)
            );
        }
        //4.执行批量插入的请求
        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        //5.输出是否失败,返回false代表成功
        System.out.println(bulkResponse.hasFailures());
    }
    

    判断文档是否存在

    @Test
        void testIsDocument() throws IOException {
            //1.获取文档,判断是否存在(GET /aaron_index/1)
            GetRequest getRequest = new GetRequest("aaron_index","1");
            //2.不获取返回的_source上下文
            getRequest.fetchSourceContext(new FetchSourceContext(false));
            boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
            if (exists) {
                System.out.println("该文档已存在");
            } else {
                System.out.println("该文档不存在");
            }
        }
    
    
    

    获取文档信息

    @Test
    void testGetDocument() throws IOException {
        //1.获取文档(GET /aaron_index/1)
        GetRequest getRequest = new GetRequest("aaron_index","1");
        //2.发送请求打印返回结果
        GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);
        System.out.println(documentFields.getSourceAsString());
        System.out.println(documentFields);
    }
    

    根据条件获取文档信息

    @Test
    void testSearch() throws IOException {
        //1.创建搜索请求
        SearchRequest searchRequest = new SearchRequest("aaron_index");
        //2.构建搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //3.查询条件,我们可以使用QueryBuilders工具来实现
            //QueryBuilders.termQuery("name", "aaron1"):精确查找
            //QueryBuilders.matchAllQuery():匹配所有
        //TermQueryBuilder queryBuilder = QueryBuilders.termQuery("name", "aaron1");
        MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
        searchSourceBuilder.query(matchAllQueryBuilder);
        //4.设置超时时间
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //5.将我们的搜索条件放入到请求当中
        searchRequest.source(searchSourceBuilder);
        //6.客户端执行搜索请求,返回搜索结果
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        //7.循环打印搜索结果
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }
    

    更新文档信息

    @Test
    void testUpdateDocument() throws IOException {
        //1.创建一个更新文档的请求
        UpdateRequest updateRequest = new UpdateRequest("aaron_index", "1");
        //2.设置超时时间(可以不写)
        updateRequest.timeout("1s");
        //3.创建一个新的对象,将对象放到请求当中
        User user = new User("Aaron", 18);
        updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
        //4.执行修改操作
        UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println(updateResponse);
    }
    

    删除文档信息

    @Test
    void testDeleteDocument() throws IOException {
        //1.创建一个删除文档的请求
        DeleteRequest deleteRequest = new DeleteRequest("aaron_index", "1");
        //2.设置超时时间(可以不写)
        deleteRequest.timeout("1s");
        //3.执行删除操作
        DeleteResponse deleteResponse = client.delete(deleteRequest,RequestOptions.DEFAULT);
        System.out.println(deleteResponse);
    }
    
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值