java springboot + es7.8.1 单元测试 亲测可使用

  • Post author:
  • Post category:java


安装配置相关地址请看上篇


有个坑,需要修改pom的依赖方式,如果直接version版本号的话,会把es 6.8.8 的版本导入到本地

会报这个错 org.springframework.beans.factory.BeanCreationException:Error creating bean with name…

1、引入pom依赖

2、添加ElasticSearchClientConfig配置类

3、单元测试

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

<dependency>
	<groupId>org.elasticsearch.client</groupId>
	<artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>

<dependency>
	<groupId>org.elasticsearch</groupId>
	<artifactId>elasticsearch</artifactId>
	<version>7.8.1</version>
</dependency>
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchClientConfig {

    @Value("${elasticsearch.host}")
    private String es_host;

    @Value("${elasticsearch.port}")
    private int es_port;

    @Value("${elasticsearch.index}")
    private String es_index;

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        return new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));
    }
}
import com.alibaba.fastjson.JSON;
import com.ghc.demo05.entity.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.client.indices.GetIndexRequest;
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.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


@SpringBootTest
class Demo05ApplicationTests {


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

    @Test
    void highClient() throws IOException {
        // 1.创建索引请求
        CreateIndexRequest request = new CreateIndexRequest("test_index");
        // 2.客户端执行请求
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(response);
    }

    /**
     * 判断索引是否存在
     *
     * @author ghc
     * @since 2020/9/6 23:13
     */
    @Test
    void testExistsIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("test_index");
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

    /**
     * 删除索引
     *
     * @author ghc
     * @since 2020/9/6 23:13
     */
    @Test
    void testDeleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("test_index");
        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(response.isAcknowledged());
    }

    /**
     * 添加文档
     *
     * @author ghc
     * @since 2020/9/6 23:17
     */
    @Test
    void testAddDocument() throws IOException {
        // 1.创建对象
        User user = new User();
        user.setName("ghc");
        user.setAge(18);

        // 2.创建请求
        IndexRequest request = new IndexRequest("test_index");

        // 3.规则
        request.id("1");
        request.timeout(TimeValue.timeValueSeconds(1));

        // 4.将我们的数据放入请求中
        request.source(JSON.toJSONString(user), XContentType.JSON);

        // 5.客户端发送请求,获取响应结果
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        System.out.println(response.toString());
        System.out.println(response.status());
    }

    /**
     * 判断文档是否存在
     *
     * @author ghc
     * @since 2020/9/6 23:23
     */
    @Test
    void testIsExists() throws IOException {
        GetRequest request = new GetRequest("test_index","1");
        // 不获取返回的_source的上下文了
        request.fetchSourceContext(new FetchSourceContext(false));
        request.storedFields("_none_");
        boolean exists = client.exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

    /*
     * 获取文档信息
     *
     * @author ghc
     * @since 2020/9/6 23:24
     */
    @Test
    void testGetDocument() throws IOException {
        GetRequest request = new GetRequest("test_index","1");
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        System.out.println(response.getSource());
        System.out.println(response);
    }

    /**
     * 修改文档
     *
     * @author ghc
     * @since 2020/9/6 23:25
     */
    @Test
    void testUpdateDocument() throws IOException {
        //构建修改请求对象,指定索引库、类型、id
        UpdateRequest request = new UpdateRequest("test_index", "1");
        request.timeout("1s");

        User user = new User();
        user.setName("ghc_test");
        user.setAge(19);

        request.doc(JSON.toJSONString(user), XContentType.JSON);

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

    /**
     * 删除文档
     *
     * @author ghc
     * @since 2020/9/6 23:26
     */
    @Test
    void testDeleteDocument() throws IOException {
        DeleteRequest request = new DeleteRequest("test_index", "1");
        request.timeout("1s");

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

    /**
     * 批量插入文档信息
     *
     * @author ghc
     * @since 2020/9/6 23:28
     */
    @Test
    void testBatchInsertDocument() throws IOException {
        BulkRequest request = new BulkRequest();
        request.timeout("10s");

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

        list.add(new User(1,"ghc1", 20));
        list.add(new User(1,"ghc2", 21));
        list.add(new User(1,"ghc3", 22));
        list.add(new User(1,"ghc_4", 23));
        list.add(new User(1,"ghc_5", 24));
        list.add(new User(1,"ghc_6", 25));

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

        BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
        System.out.println(response.hasFailures());
    }

    /**
     * 精确查找
     *
     * @author ghc
     * @since 2020/9/6 23:29
     */
    @Test
    void testSearch() throws IOException {
        SearchRequest request = new SearchRequest("test_index");

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

        // 查询条件,我们可以使用
        TermQueryBuilder termQuery = QueryBuilders.termQuery("name", "ghc");
        sourceBuilder.query(termQuery);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        request.source(sourceBuilder);

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        System.out.println("======================================");

        for (SearchHit searchHit : response.getHits().getHits()) {
            System.out.println(searchHit.getSourceAsMap());
        }
    }


}



版权声明:本文为gaohechao原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。