springboot simple (13) springboot Elasticsearch(Elasticsearch8.5.1)

news2024/9/28 1:17:30

这里首先简单的介绍了Elasticsearch,然后实现了springboot集成Elasticsearch。

版本:
Elasticsearch:v8.5.1
Kibana:v8.5.1

springboot集成elasticsearch有两种方式。
1)rest客户端RestHingLevelClient;
2)接口ElasticSearchRepository。
这里采用第1种方式。

1 Elasticsearch简介

ElasticSearch是一个基于Apache Lucene的开源搜索引擎。
Kibana 是一个开源分析和可视化平台,旨在可视化操作 Elasticsearch。

也就是说
ElasticSearch 只是后台程序,没有界面;
Kibana是ElasticSearch对应的前端。

主要术语:

  • 索引(Index)
    索引是具有某种相似特征的文档的集合。例如,客户数据索引,产品目录索引,以及订单数据索引。
  • 文档(document)
    文档是可以被索引的基本单位。文档使用JSON表示。

2 springboot 集成Elasticsearch

Elasticsearch已支持Index(索引)、Document(文档)、Graph(图)、Machine learning(机器学习)等。
在这里插入图片描述
这里介绍了Index(索引)、Document(文档)的简单使用。

第1步:pom中引入依赖的包:

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

第2步:application.properties设置相关参数:

server.port =8081

spring.data.elasticsearch.repositories.enabled = true
spring.data.elasticsearch.cluster-nodes = localhost:9300

spring.elasticsearch.rest.username=elastic
spring.elasticsearch.rest.password=123456
spring.elasticsearch.rest.uris=localhost:9200

第3步:对应的配置类ElasticSearchConfig.java:

@Component
@Configuration
public class ElasticSearchConfig extends AbstractElasticsearchConfiguration {
    @Value("${spring.elasticsearch.rest.uris}")
    private String uris ;
    @Value("${spring.elasticsearch.rest.username}")
    private String username;
    @Value("${spring.elasticsearch.rest.password}")
    private String password ;

    @Override
    @Bean(destroyMethod = "close")
    public RestHighLevelClient elasticsearchClient() {
        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo(uris)
                .withBasicAuth(username, password)
                .build();
        return RestClients.create(clientConfiguration).rest();
    }
}

第4步:实现index的工具类IndexUtil.java:

@Component
public class IndexUtil {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 创建索引index
     * @param index
     * @return
     * @throws IOException
     */
    public boolean createIndex(String index){
        if (!isIndexExist(index)) {
            return false;
        }
        boolean isAcknowledged = false;
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(index);
        try {
            AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
            isAcknowledged = acknowledgedResponse.isAcknowledged();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return isAcknowledged;
        }
    }

    /**
     * 删除索引
     * @param index
     * @return
     * @throws IOException
     */
    public boolean deleteIndex(String index){
        if (!isIndexExist(index)) {
            return false;
        }
        boolean isAcknowledged = false;
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
        try {
            AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indices().delete(deleteIndexRequest,RequestOptions.DEFAULT);
            isAcknowledged = acknowledgedResponse.isAcknowledged();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return isAcknowledged;
        }
    }

    /**
     * 判断索引是否存在
     * @param index
     * @return
     * @throws IOException
     */
    public boolean isIndexExist(String index) {
        boolean isExist = false;
        try {
            GetIndexRequest getIndexRequest = new GetIndexRequest(index);
            isExist = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return isExist;
        }
    }
}

第5步:实现document的工具类DocumentUtil.java:

@Component
public class DocumentUtil {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 添加document
     * @param object
     * @param index
     * @param id
     * @return
     */
    public void addDocument(Object object, String index,String id){
        //1 create IndexRequest
        IndexRequest indexRequest = new IndexRequest(index);
        indexRequest.id(id);
        indexRequest.timeout(TimeValue.timeValueSeconds(1));
        String content = JSON.toJSONString(object);
        indexRequest.source(content, XContentType.JSON);
        try {
            //2 send IndexRequest
            IndexResponse indexResponse =restHighLevelClient.index(indexRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加document,随机id
     * @param object
     * @param index
     * @return
     */
    public void addDocument(Object object, String index){
        String id= "";
        id = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
        addDocument(object, index, id);
    }

    /**
     * get Document
     * @param index
     * @param id
     * @return
     */
    public GetResponse getDocumnet(String index,String id){
        GetResponse getResponse = null;
        GetRequest getRequest = new GetRequest(index, id);
        try {
            getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        }catch (IOException e){
            e.printStackTrace();
        } finally {
            return  getResponse;
        }
    }

    /**
     * update document
     * @param object
     * @param index
     * @param id
     */
    public void updateDocument(Object object, String index,String id){
        //1 create UpdateRequest
        UpdateRequest updateRequest = new UpdateRequest(index,id);
        updateRequest.timeout(TimeValue.timeValueSeconds(1));
        String content = JSON.toJSONString(object);
        updateRequest.doc(content, XContentType.JSON);
        try {
            //2 send UpdateRequest
            UpdateResponse updateResponse =restHighLevelClient.update(updateRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除Document
     * @param index
     * @param id
     */
    public void deleteDocument(String index,String id){
        //1 create DeleteRequest
        DeleteRequest deleteRequest = new DeleteRequest(index, id);
        try {
            //2 send DeleteRequest
            DeleteResponse deleteResponse =  restHighLevelClient.delete(deleteRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public SearchResponse search(String index, TermQueryBuilder termQueryBuilder){
        //1 create SearchRequest
        SearchRequest searchRequest = new SearchRequest(index);

        //2 create SearchSourceBuilder
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(TimeValue.timeValueSeconds(60));

        //3 查询条件放入SearchRequest
        searchRequest.source(searchSourceBuilder);

        //4 send SearchRequest
        SearchResponse searchResponse = null;
        try {
            searchResponse = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return searchResponse;
        }
    }

    public SearchResponse searchHighLight(String index, TermQueryBuilder termQueryBuilder){
        //1 create SearchRequest
        SearchRequest searchRequest = new SearchRequest(index);

        //2 create SearchSourceBuilder
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.highlighter();
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(TimeValue.timeValueSeconds(60));

        //3 查询条件放入SearchRequest
        searchRequest.source(searchSourceBuilder);

        //4 send SearchRequest
        SearchResponse searchResponse = null;
        try {
            searchResponse = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return searchResponse;
        }
    }
}

3 测试验证

前提:安装运行ElasticSearch和Kibana。

第1步:创建index,postman发送请求:
在这里插入图片描述

然后,Kibana中输入:
GET /_cat/indices?v
查询到index创建成功。在这里插入图片描述
第2步:创建Document,postman发送请求:
在这里插入图片描述
然后,Kibana中输入:
GET heroic/_doc/1
查询到Document创建成功。在这里插入图片描述
第3步:查询Document,postman发送请求:
在这里插入图片描述

第4步:修改Document,将name“关羽”改为“刘备”;
postman发送请求:
在这里插入图片描述
然后,Kibana中输入:
GET heroic/_doc/1
查询到Document修改成功。
在这里插入图片描述
第5步:删除Document,postman发送请求:
在这里插入图片描述
然后,Kibana中输入:
GET heroic/_doc/1
查询到Document删除成功。
在这里插入图片描述
代码详见:
https://gitee.com/linghufeixia/springboot-simple
chapter9-1


教程列表
springboot simple(0) springboot简介
springboot simple(1) springboot Helloworld
springboot simple(2) springboot Starter
springboot simple(3 )springboot Web开发
springboot simple(4)springboot 数据持久化
springboot simple (5) springboot Nosql
springboot simple (6) springboot mqtt
springboot simple (7) springboot thrift
springboot simple (8) springboot kafka
springboot simple (9) springboot jpa(Hibernate)
springboot simple (10) springboot protobuf
springboot simple (11) springboot protostuff
springboot simple (12) springboot RabbitMQ
springboot simple (13) springboot Elasticsearch

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/354198.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

2.2 BeautifulSoup 装载HTML文档

HTML文档结点的查找工具很多&#xff0c;其中 BeautifulSoup 是功能强大且十分流行的查找工具之一。1. BeautifulSoup 的安装安装&#xff1a;pip install bs4导包&#xff1a;from bs4 import BeautifulSoup2. BeautifulSoup 装载HTML文档如果 doc 是一个 HTML 文档&#xff0…

fast planner总结

一、前端 kinodynamic A*算法动力学路径搜索 1.1 路径搜索的主要函数为kinodynamicAstar类的search函数 int KinodynamicAstar::search(Eigen::Vector3d start_pt, Eigen::Vector3d start_v, Eigen::Vector3d start_a,Eigen::Vector3d end_pt, Eigen::Vector3d end_v, bool ini…

DPDK — Userspace PMD 源码分析

目录 文章目录目录PMD driver 通过 IGB_UIO 与 UIO 进行交互注册一个 UIO 设备PMD 的应用层实现PMD 同样支持中断处理方式PMD driver 通过 IGB_UIO 与 UIO 进行交互 IGB_UIO 内核模块的另一个主要功能就是让用于态的 PMD 网卡驱动程序得以与 UIO 进行交互。对于 PMD 的实现来说…

松下PLC通过fpwin上传写入MRTC模块方法

目录 PLC程序上传方法 加密模块使用 PLC程序上传方法 手动将PLC模式设置为prog模式查看PLC是否设置为禁止上传查询指示灯是否变蓝&#xff0c;变蓝则需要将PLC禁止上传功能取消。 3.当上述动作操作完成后&#xff0c;将PLC程序导入到PLC中。为了配合加密程序使用&#xff0c;…

进程通信方式

无名管道( pipe )&#xff1a; 管道是一种半双工的通信方式&#xff0c;数据只能单向流动&#xff0c;而且只能在具有亲缘关系的进程间使用。进程的亲缘关系通常是指父子进程关系。高级管道&#xff08;popen&#xff09;&#xff1a; 将另一个程序当做一个新的进程在当前程序进…

主成分分析(PCA)原理详解

1. 相关背景 在许多领域的研究与应用中&#xff0c;通常需要对含有多个变量的数据进行观测&#xff0c;收集大量数据后进行分析寻找规律。多变量大数据集无疑会为研究和应用提供丰富的信息&#xff0c;但是也在一定程度上增加了数据采集的工作量。更重要的是在很多情形下&…

Windows server——部署web服务

作者简介&#xff1a;一名云计算网络运维人员、每天分享网络与运维的技术与干货。 座右铭&#xff1a;低头赶路&#xff0c;敬事如仪 个人主页&#xff1a;网络豆的主页​​​​​​ 目录 前言 本章重点 一.web讲解 1.WWW概述 &#xff08;1&#xff09;WWW服务概述 &…

Linux应用编程下连接本地数据库进行增删改查系列操作

文章目录前言一、常用SQL操作语句二、相关函数解析三、连接本地数据库四、编译运行五、程序源码前言 本篇为C语言应用编程下连接Linux本地数据库进行增删改查系列操作。 在此之前&#xff0c;首先当然是你需要具备一定的数据库基础&#xff0c;所以下面我先列出部分常用的SQL…

如何利用文件上传漏洞-以及如何修复它们

目录什么是文件上传漏洞&#xff1f;文件上传请求如何工作为什么文件上传漏洞是个问题&#xff1f;漏洞 #1&#xff1a;通过文件内容远程代码执行&#xff08;Web Shell 上传&#xff09;绕过黑名单保护案例 1&#xff1a;案例 2&#xff1a;案例 3&#xff1a;案例 4&#xff…

【Spark分布式内存计算框架——Spark SQL】10. External DataSource(上)数据源与格式

第六章 External DataSource 在SparkSQL模块&#xff0c;提供一套完成API接口&#xff0c;用于方便读写外部数据源的的数据&#xff08;从Spark 1.4版本提供&#xff09;&#xff0c;框架本身内置外部数据源&#xff1a; 在Spark 2.4版本中添加支持Image Source&#xff08;图…

音频信号处理笔记(一)

相关课程&#xff1a;【音频信号处理及深度学习教程】 文章目录01 信号的时域分析1.1 分帧1.1.1 幅值包络1.1.2 均方根能量0 信号的叠加&#xff1a;https://teropa.info/harmonics-explorer/ 一个复杂信号分解成若干简单信号分量之和。不同个频率信号的叠加: 由于和差化积&a…

【Mysql基础 —— SQL语句(一)】

文章目录概述使用启动/停止mysql服务连接mysql客户端数据模型SQLSQL语句分类DDL数据库操作表操作查询创建数据类型修改删除DML添加数据修改数据删除数据DQL基础查询条件查询聚合函数分组查询排序查询分页查询执行顺序DCL管理用户权限控制概述 数据库&#xff08;Database&#…

如何评价一个新技术——以 ChatGPT 为例

开源社KAIYUANSHE近期微信公众号订阅功能做调整啦&#xff01;没有被星标的账号在信息流里可能不显示大图了&#xff01;快星标⭐我们&#xff0c;就可以及时看到发布的文章啦&#xff01;STEP01 点击右上角标志STEP02 点击【设为星标】缘起2015 年的时候&#xff0c;我写过一篇…

DaVinci 偏好设置:用户 - UI 设置

偏好设置 - 用户/ UI 设置Preferences - User/ UI Settings工作区选项Workspace Options语言Language指定 DaVinci Resolve 软件界面所使用的语言。目前支持英语、简体中文、日语、西班牙语、葡萄牙语、法语、俄语、泰语和越南语等等。启动时重新加载上一个工作项目Reload last…

Python 连接数据源与邮件功能(九)

文章目录一、概述二、Python 连接数据源1&#xff09;Python MySQL 基础操作1、部署MySQL2、MySQL Connector 库【1】安装 mysql-connector-python 库【2】连接 MySQL【3】增加数据【4】查询数据【5】更新数据【6】删除数据2、PyMySQL 库【1】安装 PyMySQL 库【2】连接 MySQL【…

2023年数学建模美赛D题(Prioritizing the UN Sustainability Goals):SDGs 优先事项的选择

正在写&#xff0c;不断更新&#xff0c;别着急。。。 4. SDGs 优先事项的选择 4.1 基于SDG密度分布图选择优先事项 虽然每个可持续发展目标的接近度矩阵和中心性度量的结果是通用的&#xff0c;并创建了基本的可持续发展目标网络&#xff0c;但由于各国在网络的不同部分取得…

前端网格布局grid

网格布局 <style> .container {border:none;display: grid;height: 600px;grid-template-columns: 200px 1fr; /*两列&#xff0c;第一列200px&#xff0c;第二列自适应*/grid-template-rows: 50px 1fr 30px; /*三行&#xff1a;第一行&#xff1a;50px,第二行&#…

【C语言每日一题】——猜名次

【C语言每日一题】——猜名次&#x1f60e;前言&#x1f64c;猜名次&#x1f64c;解题思路分享&#xff1a;&#x1f60d;解题源码分享&#xff1a;&#x1f60d;总结撒花&#x1f49e;&#x1f60e;博客昵称&#xff1a;博客小梦 &#x1f60a;最喜欢的座右铭&#xff1a;全神…

大数据之-Nifi-应用场景2-2_设置putfile处理器自动创建目标文件夹_以及存在重复文件时自动覆盖---大数据之Nifi工作笔记0006

上一节我们留了两个问题,一个是,如果我们没有创建putfile要写入的目标文件夹,会报错吗? 可以看到我们putfile目标文件夹是上面这个目录 我们来试一试,如果目标文件夹不存在,putfile处理器会自动创建吗 首先我们删除这个target目标文件夹 然后我们进入cd source目录,源文件夹目…

echart在微信小程序的使用

echart在微信小程序的使用 echarts不显示在微信小程序 <!-- 微信小程序的echart的使用 --> <view class"container"><ec-canvas id"mychart-dom-bar" canvas-id"mychart-bar" ec"{{ ec }}"></ec-canvas> &l…