springboot集成elasticsearch7的图文方法

1.创建项目











修改依赖版本

2.创建配置文件

package com.huanmingjie.elasticsearch.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 ElasticsearchClientConfig {

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

}

3.测试

3.1索引操作

1.创建索引


2.判断索引是否存在


3.删除索引

索引操作代码

package com.huanmingjie.elasticsearch;

import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
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.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
class ElasticsearchApplicationTests {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    //创建索引 PUT zoomy_index
    @Test
    void createIndex() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("zoomy_index");
        restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
    }

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

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

3.2文档操作

创建实体类

package com.huanmingjie.elasticsearch.pojo;

import org.springframework.stereotype.Component;

@Component
public class User {
    private String name;
    private int age;

    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

1.添加文档


2.获取文档,判断是否存在

3.获取文档信息

4.更新文档


5.删除文档


3.3实战操作

批量创建数据


查询



package com.huanmingjie.elasticsearch;

import com.alibaba.fastjson.JSON;
import com.huanmingjie.elasticsearch.pojo.User;
import com.huanmingjie.elasticsearch.utils.ESConstant;
import net.minidev.json.JSONObject;
import org.apache.lucene.util.QueryBuilder;
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.SearchRequestBuilder;
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.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
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.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

@SpringBootTest
class ElasticsearchApplicationTests {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    //创建索引 PUT zoomy_index
    @Test
    void createIndex() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("zoomy_index");
        restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
    }

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

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

    //添加文档 PUT zoomy_index/_doc/1
    @Test
    void addDocument() throws IOException {
        User user = new User("zoomy", 21);
        IndexRequest request = new IndexRequest("zoomy_index");
        request.id("1");
        request.timeout(TimeValue.timeValueSeconds(1));
        request.source(JSON.toJSONString(user), XContentType.JSON);
        //客户端发送请求,获取响应结果
        IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        System.out.println(indexResponse.toString());
        //命令返回的状态
        System.out.println(indexResponse.status());
    }

    //获取文档,判断是否存在
    @Test
    void exitDocument() throws IOException {
        GetRequest request = new GetRequest("zoomy_index", "1");
        //不获取返回的_source的上下文,效率更高
        request.fetchSourceContext(new FetchSourceContext(false));
        request.storedFields("_none_");
        boolean exists = restHighLevelClient.exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

    //获取文档信息
    @Test
    void getDocument() throws IOException {
        GetRequest request = new GetRequest("zoomy_index", "1");
        GetResponse getResponse = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        //打印文档内容
        System.out.println(getResponse.getSourceAsString());
        //返回全部内容
        System.out.println(getResponse);

    }

    //更新文档 POST zoomy_index/_doc/1/_update
    @Test
    void updateDocument() throws IOException {
        UpdateRequest request = new UpdateRequest("zoomy_index", "1");
        request.timeout(TimeValue.timeValueSeconds(1));
        User user = new User("zoomy", 22);
        request.doc(JSON.toJSONString(user), XContentType.JSON);
        UpdateResponse updateResponse = restHighLevelClient.update(request, RequestOptions.DEFAULT);
        System.out.println(updateResponse.status());
    }

    //删除文档
    @Test
    void deleteDocument() throws IOException {
        DeleteRequest request = new DeleteRequest("zoomy_index", "1");

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

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

        ArrayList<User> userList = new ArrayList<>();
        userList.add(new User("zoomy1", 21));
        userList.add(new User("zoomy2", 22));
        userList.add(new User("zoomy3", 23));

        for (int i = 0; i < userList.size(); i++) {
            bulkRequest.add(
                    new IndexRequest("zoomy_index")
                            .id("" + (i + 1))
                            .source(JSON.toJSONString(userList.get(i)), XContentType.JSON));
        }
        BulkResponse bulkItemResponses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulkItemResponses.hasFailures());
    }

    //批量处理数据
    @Test
    void searchRequest() throws IOException {
        SearchRequest searchRequest = new SearchRequest(ESConstant.ZOOMY_INDEX);
        //构建搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //查询条件QueryBuilders工具  termQuery 精确查询 matchAllQuery匹配所有
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "zoomy1");
//        MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
        searchSourceBuilder.query(termQueryBuilder);
        //from size有默认参数
//        searchSourceBuilder.from();
//        searchSourceBuilder.size();
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(JSON.toJSONString(searchResponse.getHits()));
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }
    }

}

以上就是springboot集成elasticsearch7的详细内容,更多关于springboot集成elasticsearch7的资料请关注我们其它相关文章!

(0)

相关推荐

  • SpringBoot整合Spring Data Elasticsearch的过程详解

    Spring Data Elasticsearch提供了ElasticsearchTemplate工具类,实现了POJO与elasticsearch文档之间的映射 elasticsearch本质也是存储数据,它不支持事物,但是它的速度远比数据库快得多, 可以这样来对比elasticsearch和数据库 索引(indices)--------数据库(databases) 类型(type)------------数据表(table) 文档(Document)---------------- 行(ro

  • SpringBoot整合Elasticsearch7.2.0的实现方法

    Spring boot 2.1.X整合Elasticsearch最新版的一处问题 新版本的Spring boot 2的spring-boot-starter-data-elasticsearch中支持的Elasticsearch版本是2.X,但Elasticsearch实际上已经发展到7.2.X版本了,为了更好的使用Elasticsearch的新特性,所以弃用了spring-boot-starter-data-elasticsearch依赖,而改为直接使用Spring-data-elastics

  • SpringBoot整合Elasticsearch并实现CRUD操作

     配置准备 在build.gradle文件中添加如下依赖: compile "org.elasticsearch.client:transport:5.5.2" compile "org.elasticsearch:elasticsearch:5.5.2" //es 5.x的内部使用的 apache log4日志 compile "org.apache.logging.log4j:log4j-core:2.7" compile "org

  • es(elasticsearch)整合SpringCloud(SpringBoot)搭建教程详解

    注意:适用于springboot或者springcloud框架 1.首先下载相关文件 2.然后需要去启动相关的启动文件 3.导入相关jar包(如果有相关的依赖包不需要导入)以及配置配置文件,并且写一个dao接口继承一个类,在启动类上标注地址 <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> &l

  • springboot集成elasticsearch7的图文方法

    1.创建项目 修改依赖版本 2.创建配置文件 package com.huanmingjie.elasticsearch.config; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.context.annotation.Bean;

  • springboot集成nacos的配置方法

    本文介绍了springboot集成nacos的配置方法,分享给大家,具体如下: nacos仓库:https://github.com/alibaba/nacos nacos介绍文档:https://nacos.io/zh-cn/docs/architecture.html nacos使用例子:https://github.com/nacos-group/nacos-examples springboot配置-集成nacos,例子代码下载 springboot-nacos-consumer spr

  • SpringBoot集成H2内存数据库的方法

    目录 前言 准备 技术栈 目录结构 pom.xml 实体类 User AddressRepository application.yml 连接配置 数据初始化配置 h2 web consloe配置 代码下载 H2是Thomas Mueller提供的一个开源的.纯java实现的关系数据库. 前言 本篇文章引导你使用Spring Boot,Spring Data JPA集成H2内存数据库.更多关于H2数据参考:http://www.h2database.com/html/tutorial.html

  • SpringBoot集成Spring Security的方法

    至今Java能够如此的火爆Spring做出了很大的贡献,它的出现让Java程序的编写更为简单灵活,而Spring如今也形成了自己的生态圈,今天咱们探讨的是Spring旗下的一个款认证工具:SpringSecurity,如今认证框架主流"shiro"和"SpringSecurity",由于和Spring的无缝衔接,使用SpringSecurity的企业也越来越多. 1.Spring Security介绍 Spring security,是一个强大的和高度可定制的身份验

  • SpringBoot利用redis集成消息队列的方法

    一.pom文件依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> 二.创建消息接收者 变量.方法及构造函数进行标注,完成自动装配的工作. 通过 @Autowired的使用来消除 set ,get方法. @Autowired pub

  • Springboot中集成Swagger2框架的方法

    摘要:在项目开发中,往往期望做到前后端分离,也就是后端开发人员往往需要输出大量的服务接口,接口的提供方无论是是Java还是PHP等语言,往往会要花费一定的精力去写接口文档,比如A接口的地址.需要传递参数情况.返回值的JSON数据格式以及每一个字段说明.当然还要考虑HTTP请求头.请求内容等信息.随着项目的进度快速高速的迭代,后端输出的接口往往会面临修改.修复等问题,那也意味着接口文档也要进行相应的调整.接口文档的维护度以及可读性就大大下降. 既然接口文档需要花费精力去维护,还要适当的进行面对面交

  • SpringBoot集成Swagger2生成接口文档的方法示例

    我们提供Restful接口的时候,API文档是尤为的重要,它承载着对接口的定义,描述等.它还是和API消费方沟通的重要工具.在实际情况中由于接口和文档存放的位置不同,我们很难及时的去维护文档.个人在实际的工作中就遇到过很多接口更新了很久,但是文档却还是老版本的情况,其实在这个时候这份文档就已经失去了它存在的意义.而 Swagger 是目前我见过的最好的API文档生成工具,使用起来也很方便,还可以直接调试我们的API.我们今天就来看下 Swagger2 与 SpringBoot 的结合. 准备工作

  • SpringBoot集成Beetl后统一处理页面异常的方法

    背景 SpringBoot集成Beetl后如果页面出现异常会将出现异常之前的页面输出到客户端,但是由于页面不完整会导致用户看到的页面错乱或者空白,如下 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> 在控制台可以看到 >

  • SpringBoot集成WebSocket实现前后端消息互传的方法

    什么是WebSocket? WebSocket 协议是基于 TCP 的一种新的网络协议.它实现了浏览器与服务器全双工 (full-duplex) 通信-允许服务器主动发送信息给客户端. 为什么需要WebSocket? 大家都知道以前客户端想知道服务端的处理进度,要不停地使用 Ajax 进行轮询,让浏览器隔个几秒就向服务器发一次请求,这对服务器压力较大.另外一种轮询就是采用 long poll 的方式,这就跟打电话差不多,没收到消息就一直不挂电话,也就是说,客户端发起连接后,如果没消息,就一直不返

  • SpringBoot集成Redisson实现分布式锁的方法示例

    上篇 <SpringBoot 集成 redis 分布式锁优化>对死锁的问题进行了优化,今天介绍的是 redis 官方推荐使用的 Redisson ,Redisson 架设在 redis 基础上的 Java 驻内存数据网格(In-Memory Data Grid),基于NIO的 Netty 框架上,利用了 redis 键值数据库.功能非常强大,解决了很多分布式架构中的问题. Github的wiki地址: https://github.com/redisson/redisson/wiki 官方文档

随机推荐