Elasticsearch第三谈(SpringBoot集成Elasticsearch)

写博客即是为了记录自己的学习历程,也希望能够结交志同道合的朋友一起学习。文章在撰写过程中难免有疏漏和错误,欢迎指出文章的不足之处;更多内容请点进爱敲代码的小游子查看。
临渊羡鱼,不如退而结网。一起加油!

官方文档JavaApi:https://www.elastic.co/guide/en/elasticsearch/client/index.html

1、导入依赖

保证版本和本机版本一致

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

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

2、认识核心包

org.elasticsearch.client:elasticsearch-rest-client
org.elasticsearch:elasticsearch

3、初始化

RestHighLevelClient实例需要按以下方式构建REST高级客户端构建器:

RestHighLevelClient client = new RestHighLevelClient(
        RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http")));

关闭客户端

cline.close();

4、创建配置类

@Configuration
public class ElasticsearchConfig {

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

        return client;
    }

}

5、索引操作

1、创建索引

@Test
	void contextLoads() throws IOException {
		//1、索引创建
		CreateIndexRequest request = new CreateIndexRequest("yky_index2");
		//2、执行请求 ==> 请求后获取响应
		CreateIndexResponse createIndexResponse
				= restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);

		System.out.println(createIndexResponse);
	}

2、判断索引是否存在

 //获取索引 ==>只能判断是否存在
    @Test
    void getIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("yky");
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

3、删除索引

   //删除索引
    @Test
    void deleteIndex() throws IOException{
        DeleteIndexRequest request = new DeleteIndexRequest("yky_index");
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }

6、文档的增删改查

1、添加文档测试

把数据封装成对象 => 创建请求 => 设置规则 => 转成json数据格式 => 发送请求

    //添加文档测试
    @Test
    void testAddDocument() throws IOException {
        //创建对象
        User user = new User("爱敲代码的小游子",20);
        //创建请求
        IndexRequest request = new IndexRequest("yky_index");
        //规则 put /yky/_doc/id
        request.id("1001");
        //超时时间
        request.timeout(TimeValue.timeValueSeconds(1000));
        //request.timeout("1s");
        //将数据放入请求 ==> 需要传入json数据(fastjson)
        request.source(JSON.toJSONString(user), XContentType.JSON);
        //客户端发送请求
        IndexResponse index = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        System.out.println(index.toString());
        System.out.println(index.status());
    }

2、获取文档

//更新文档信息
    @Test
    void testUpdateDocument() throws IOException {
        //指定索引和id
        UpdateRequest request = new UpdateRequest("yky_index", "1001");
        request.timeout("1s");
        User user = new User("爱敲代码的小游子", 1);
        request.doc(JSON.toJSONString(user), XContentType.JSON);
        //执行请求
        UpdateResponse update = restHighLevelClient.update(request, RequestOptions.DEFAULT);
        System.out.println(update.toString());
        System.out.println(update.status());
    }

3、更新文档操作

  //更新文档信息
    @Test
    void testUpdateDocument() throws IOException {
        //指定索引和id
        UpdateRequest request = new UpdateRequest("索引名", "id");
        request.timeout("1s");
        User user = new User("爱敲代码的小游子", 1);
        request.doc(JSON.toJSONString(user), XContentType.JSON);
        //执行请求
        UpdateResponse update = restHighLevelClient.update(request, RequestOptions.DEFAULT);
        System.out.println(update.toString());
        System.out.println(update.status());
    }

4、删除文档

  //删除文档
    @Test
    void testDeleteDocument() throws IOException {
        DeleteRequest request = new DeleteRequest("yky_index", "1001");
        DeleteResponse delete = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.status());
    }

5、批量增加数据

    //批量增加数据
    @Test
    void testBulkDocument() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");

        ArrayList<User> list = new ArrayList<>();
        //增加数据

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

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulk.hasFailures());
    }

6、查询

@Test
    //xxx QueryBuilder对应刚才看到的所有命令
    void testSearchDocument() throws IOException {
        SearchRequest searchRequest = new SearchRequest("yky_index");
        //构造搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //查询条件 ===> QueryBuilders工具类快速匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "小游子");
        //MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();

        sourceBuilder.query(termQueryBuilder);
        //设置查询时间
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //发送请求
        searchRequest.source(sourceBuilder);
        //分页
        //sourceBuilder.from(1);
        //sourceBuilder.size(1);
        //执行
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //System.out.println(JSON.toJSONString(searchResponse.getHits()));
        System.out.println("===============");
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }

你可能感兴趣的:(海纳百川,Java,SpringBoot,elasticsearch,java,数据库,mysql)