ElasticSearch_集成SpringBoot

ElasticSearch集成SpringBoot

1. 依赖

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

2. 新建项目

image-20201030135312316

导入依赖后我们查看SpringBoot中的ElasticSearch的版本,发现为 7.6.2 版本,与我们本地的 7.8.0不匹配

image-20201030135900769

一定要保证我们导入的依赖和我们ES版本一致,在我们的POM中修改版本即可

image-20201030140238373

3. 配置对象

package com.wang.wangesapi.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 ElasticSearchConfig {

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        RestHighLevelClient client = new RestHighLevelClient(
                //配置hostname和端口
                RestClient.builder(
                        new HttpHost("127.0.0.1",9200,"http")
                )
        );
        return client;
    }
}

4. API

1. 操作索引

1. 创建索引

package com.wang.wangesapi;

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 WangEsApiApplicationTests {

   //Autowired 根据名称首字母转大写匹配类型,这里和类型不一致,所以我们要用ID绑定
   @Autowired
   @Qualifier("restHighLevelClient")
   private RestHighLevelClient client;

   //测试索引的创建 所有的请求都使用Request创建
   @Test
   public void testCreateIndex() throws IOException {
      // 1. 创建索引请求
      CreateIndexRequest request = new CreateIndexRequest("wang_index");
      // 2. 执行创建请求 第二个参数我们一般使用默认的 RequestOptions.DEFAULT
      //indices ==> index的复数
      CreateIndexResponse createIndexResponse = client.indices().create(request,RequestOptions.DEFAULT);

      System.out.println(createIndexResponse);
   }

}

2. 获取索引

// 测试获取索引
@Test
public void testExitIndex() throws IOException {
   GetIndexRequest index = new GetIndexRequest("wang_index");
   boolean exists = client.indices().exists(index,RequestOptions.DEFAULT);
   System.out.println(exists);
}

image-20201030143534879

只能判断其是否存在

3. 删除索引

// 测试删除索引
@Test
public void testDeleteIndex() throws IOException {
   DeleteIndexRequest request = new DeleteIndexRequest("wang_index");
   AcknowledgedResponse delete = client.indices().delete(request,RequestOptions.DEFAULT);
   System.out.println(delete.isAcknowledged());
}

isAcknowledged() ==> 返回状态的布尔值

image-20201030144141190

2. 操作文档

1. 添加文档

//测试添加文档
@Test
public void testAddDocument() throws IOException {
   //创建对象
   User user = new User("张三",12);
   //创建请求
   IndexRequest request = new IndexRequest("wang_index");
   //创建规则 put/wang_index/_doc/1
   request.id("1");
   //设置过期规则,与 request.timeout("1s") 效果一致
   request.timeout(TimeValue.timeValueSeconds(1));
   //将我们数据放入请求 (JSON)
   IndexRequest source = request.source(JSON.toJSONString(user),XContentType.JSON);
   //客户端发送请求
   IndexResponse response = client.index(request,RequestOptions.DEFAULT);

   System.out.println(response.toString());
   System.out.println(response.status());
}

2. 获取文档

首先查看文档是否存在

//获取文档,首先判断是否存在 get/index/_doc/1
@Test
public void testIsExist() throws IOException {
   GetRequest request = new GetRequest("wang_index","1");
   //不获取我们返回的 _source 的上下文了,效率更高
   request.fetchSourceContext(
         new FetchSourceContext(false)
   );
   request.storedFields("_none_");

   boolean exists = client.exists(request,RequestOptions.DEFAULT);
   System.out.println(exists);
}

获取文档

//获取文档的信息
@Test
public void testGetDocument() throws IOException {
   GetRequest request = new GetRequest("wang_index","1");
   GetResponse response = client.get(request,RequestOptions.DEFAULT);
   //打印文档的内容
   System.out.println(response.getSourceAsString());
   //返回的全内容和命令式是一样的
   System.out.println(response);
}

结果如下

image-20201030152633930

3. 更新文档

//更新文档信息
@Test
public void testUpdateDocument() throws IOException {
   UpdateRequest request = new UpdateRequest("wang_index","1");
   request.timeout("1s");
   User user = new User("李四",24);
   request.doc(JSON.toJSONString(user),XContentType.JSON);
   UpdateResponse response = client.update(request,RequestOptions.DEFAULT);
   System.out.println(response.status());
}

4. 删除文档

//删除文档记录
@Test
public void testDeleteDocument () throws IOException {
   DeleteRequest request = new DeleteRequest("wang_index","1");
   request.timeout("1s");

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

5. 批量操作

使用BulkRequest对象,其他的和单独操作差不多

//批量导入数据
@Test
void testBulkRequest() throws IOException {
    BulkRequest bulkRequest = new BulkRequest();
    bulkRequest.timeout(TimeValue.timeValueSeconds(10));

    ArrayList<User> userList = new ArrayList<>();
    userList.add(new User("张三1号",3));
    userList.add(new User("张三2号",3));
    userList.add(new User("张三3号",3));
    userList.add(new User("李四1号",3));
    userList.add(new User("李四2号",3));
    userList.add(new User("李四3号",3));

    //批处理请求
    for (int i = 0; i < userList.size(); i++) {
        bulkRequest.add(
                new IndexRequest("wang_index")
                        .id("" + i)
                        .source(JSON.toJSONString(userList.get(i)),XContentType.JSON));

    }

    BulkResponse responses = client.bulk(bulkRequest,RequestOptions.DEFAULT);
    //是否存在失败的数据 ==> 返回false则说明全部插入成功!
    System.out.println(responses.hasFailures());
}

6. 查询操作

//查询
//SearchRequest 搜索请求
//SearchSourceBuilder 条件构造
//HighlightBuilder 构建高亮
//TermQueryBuilder 精确查询
//XXXXQueryBuilder 对应我们看到的所有功能
@Test
public void testSearch() throws IOException {
    SearchRequest searchRequest = new SearchRequest("wang_index");
    //构建搜索的条件
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    //查询条件,可以使用 QueryBuilders 工具来实现
    //QueryBuilders.termQuery 精确匹配
    //QueryBuilder.matchAllQuery 匹配所有
    MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name","张三1号");
    sourceBuilder.query(matchQueryBuilder)
            .timeout(TimeValue.timeValueSeconds(1))
            //分页
            .from(0).size(3);
    searchRequest.source(sourceBuilder);

    SearchResponse searchResponse = client.search(searchRequest,RequestOptions.DEFAULT);
    System.out.println(JSON.toJSONString(searchResponse.getHits()));
    System.out.println("=========================================");
    //遍历搜索结果,取出其中的documentFields.getSourceAsMap,就可以得到JSON MAP的结果
    for (SearchHit documentFields : searchResponse.getHits()) {
        System.out.println(documentFields.getSourceAsMap());
    }

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


今天小编给大家分享的是Springboot下使用Redis管道(pipeline)进行批量操作的介绍,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起...
本篇文章和大家了解一下springBoot项目常用目录有哪些。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。springBoot项目常用目录springBoot项...
本篇文章和大家了解一下Springboot自带线程池怎么实现。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。一: ThreadPoolTaskExecuto1 ThreadP...
这篇文章主要介绍了SpringBoot读取yml文件有哪几种方式,具有一定借鉴价值,需要的朋友可以参考下。下面就和我一起来看看吧。Spring Boot读取yml文件的主要方式...
今天小编给大家分享的是SpringBoot配置Controller实现Web请求处理的方法,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起往下看吧...
本篇文章和大家了解一下SpringBoot实现PDF添加水印的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。简介PDF(Portable Document Form...
本篇文章和大家了解一下解决Springboot全局异常处理与AOP日志处理中@AfterThrowing失效问题的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有...
本篇文章和大家了解一下IDEA创建SpringBoot父子Module项目的实现方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。目录前言1. 软硬件环...
今天小编给大家分享的是springboot获取项目目录路径的方法,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起往下看吧。一定会有所收...
本篇内容主要讲解“SpringBoot+Spring Security无法实现跨域如何解决”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面...
这篇文章主要介绍“vue怎么发送请求到springboot程序”,在日常操作中,相信很多人在vue怎么发送请求到springboot程序问题上存在疑惑,小编查阅了各式资料,整理...
本篇内容主要讲解“Springboot内置的工具类CollectionUtils如何使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家...
本文小编为大家详细介绍“SpringBoot上传文件大小受限如何解决”,内容详细,步骤清晰,细节处理妥当,希望这篇“SpringBoot上传文件大小受限如何解决”文章能帮...
本文小编为大家详细介绍“springboot拦截器如何创建”,内容详细,步骤清晰,细节处理妥当,希望这篇“springboot拦截器如何创建”文章能帮助大家解决疑惑,下面...
本文小编为大家详细介绍“Hikari连接池使用SpringBoot配置JMX监控的方法是什么”,内容详细,步骤清晰,细节处理妥当,希望这篇“Hikari连接池使用SpringBoot配...
今天小编给大家分享一下SpringBoot如何使用Sa-Token实现权限认证的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大...
这篇文章主要介绍“SpringBoot如何集成SFTP客户端实现文件上传下载”,在日常操作中,相信很多人在SpringBoot如何集成SFTP客户端实现文件上传下...
本篇内容主要讲解“Springboot插件怎么开发”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Springboot插件怎
这篇文章主要介绍“Springboot怎么解决跨域请求问题”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇...
今天小编给大家分享一下如何在SpringBoot2中整合Filter的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文...