SpringBoot集成Elasticsearch


一、使用步骤

1.加入依赖

	 <!--elasticsearch高级客户端-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.13.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>

2.创建配置类

package com.it.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 ElasticClientConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")));
        return restHighLevelClient;
    }
}

3.测试

package com.it;
import com.alibaba.fastjson.JSON;
import com.it.mapper.JprecommendMapper;
import com.it.pojo.Jprecommend;
import com.it.pojo.User;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;


import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Data:2021/6/29 8:35
 * @Author:胡萝卜
 */
@SpringBootTest
public class Expert_lecture_ApplicationTest {
    @Resource
    private RestHighLevelClient restHighLevelClient;
    @Resource
    private JprecommendMapper jprecommendMapper;

    /**
     * 功能描述:existsIndexTest 判断索引是否存在 <br>
     */
    @Test
    void createIndexTest() throws IOException {
        // 1. 创建索引请求
        CreateIndexRequest firstIndex = new CreateIndexRequest("jprecommend");
        // 2. 客户端执行创建索引的请求
        CreateIndexResponse response = restHighLevelClient.indices().create(firstIndex, RequestOptions.DEFAULT);
        System.out.println(response);
    }

    /**
     * 功能描述:deleteIndexTest 删除指定的索引 <br>
     */
    @Test
    void deleteIndexTest() throws IOException {
        // 1. 创建一个delete请求,用于删除索引信息
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("jprecommend");

        // 2. 客户端执行删除请求
        AcknowledgedResponse result = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        System.out.println(JSON.toJSON(result));
    }

    /**
     * 功能描述:创建文档
     */
    @Test
    void addDocumentTest() throws IOException {
        // 1. 创建对象
        User user = new User();
        user.setId(1);
        user.setCreateTime(new Date());
        user.setUAge(21);
        user.setUSex("男");

        // 2. 创建请求并指定索引
        IndexRequest indexRequest = new IndexRequest("jprecommend");

        // 3. 创建的规则:put /xununan_index/_doc/1
        indexRequest.id("1");            // 设置ID
        indexRequest.timeout("1s");      // 设置超时时间

        // 4. 将数据放入到请求中
        indexRequest.source(JSON.toJSONString(user), XContentType.JSON);

        // 5. 使用客户端发送请求
        IndexResponse index = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);

        System.out.println(JSON.toJSONString(index));
    }

    /**
     * 功能描述:getDocumentTest 获取文档信息
     */
    @Test
    void getDocumentTest() throws IOException {
        // 1. 创建请求信息绑定索引和指定需要查询的文档id
        GetRequest getRequest = new GetRequest("jprecommend", "1");
        // 设置不获取的返回时的_source的上下文,一般情况是不需要设置的
//        getRequest.fetchSourceContext(new FetchSourceContext(false)).storedFields("_none_");

        // 2. 判断指定的索引和id是否存在
        boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
        if (!exists) {
            System.out.println(">>>>>>>> 当前索引:jprecommend对应的id:1 不存在");
            return;
        }
        System.out.println(">>>>>>>> 当前索引:jprecommend对应的id:1 存在");
        // 3. 获取指定ID的资源信息
        GetResponse response = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        // 4. 打印获取到的资源信息
        System.out.println(response.getSourceAsString());
        System.out.println(JSON.toJSONString(response));
    }

    /**
     * 功能描述:updateDocmentTest 更新文档信息 <br>
     */
    @Test
    void updateDocmentTest() throws IOException {
        // 1. 创建一个更新请求的信息,绑定索引名称和需要更新的文档ID
        UpdateRequest updateRequest = new UpdateRequest("jprecommend", "1");
        updateRequest.timeout("1s");     // 设置超时时间
        User user = new User();
        user.setId(1);
        user.setCreateTime(new Date());
        user.setUAge(21);
        user.setUSex("男");
        // 2. 封装需要更新的文档信息
        updateRequest.doc(JSON.toJSONString(user), XContentType.JSON);

        // 3. 使用update更新文档
        UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);

        System.out.println(JSON.toJSONString(updateResponse));
    }

    /**
     * 功能描述:deleteDocmentTest 删除文档信息 <br>
     */
    @Test
    void deleteDocmentTest() throws IOException {
        // 1. 创建一个删除的请求,绑定索引名和需要删除的文档ID
        DeleteRequest deleteRequest = new DeleteRequest("jprecommend", "1");


        // 2. 发起删除请求
        DeleteResponse response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);

        System.out.println(JSON.toJSONString(response));
    }

    /**
     * 功能描述:addDocmentByBatchTest 批量创建文档 <br>
     */
    @Test
    void addDocmentByBatchTest() throws IOException {
        // 1. 创建批量的请求
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2s");     //  设置超时时间
        List<Jprecommend> jprecommends = jprecommendMapper.selectList(null);
        // 2. 将多条数据批量的放入bulkRequest中

        for (int i = 0; i < jprecommends.size(); i++) {
            String data = JSON.toJSONString(jprecommends.get(i));
            IndexRequest indexRequest = new IndexRequest("jprecommend").source(data, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        // 3. 执行批量创建文档
        BulkResponse responses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(responses.hasFailures());    // 是否失败,如果false则表示全部成功
        System.out.println(JSON.toJSONString(responses));
    }

    /**
     * 功能描述:searchTest 批量搜索,可以设置高亮等信息 <br>
     */
    @Test
    void searchTest() throws IOException {

        // 1. 创建批量搜索请求,并绑定索引
        SearchRequest searchRequest = new SearchRequest("jprecommend");
        // 2. 构建搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "句");
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        // 4. 发起查询请求获取数据
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(JSON.toJSONString(response));
        System.out.println(JSON.toJSONString(response.getHits().getHits()));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值