spring boot学习第八篇:操作elastic search的索引和索引中的数据

前提参考:elastic search入门-CSDN博客

前提说明:已经安装好了elastic search 7.x版本,我的es版本是7.11.1

1、 pom.xml文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.6.4</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.hmblogs</groupId><artifactId>hmblogs</artifactId><version>0.0.1-SNAPSHOT</version><name>hmblogs</name><description>hmblogs</description><properties><java.version>8</java.version><druid.version>1.2.8</druid.version><log4jdbc.version>1.16</log4jdbc.version><es.version>7.9.2</es.version></properties><dependencies><!-- druid数据源驱动 --><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>${druid.version}</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- mybatis --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3.1</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!--Mysql依赖包--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><!--lombok插件--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!--监控sql日志--><dependency><groupId>org.bgee.log4jdbc-log4j2</groupId><artifactId>log4jdbc-log4j2-jdbc4.1</artifactId><version>${log4jdbc.version}</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.9</version></dependency><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId></dependency><dependency><groupId>org.apache.kafka</groupId><artifactId>kafka-clients</artifactId></dependency><dependency><groupId>org.springframework.kafka</groupId><artifactId>spring-kafka</artifactId></dependency><!-- high client--><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>${es.version}</version><exclusions><exclusion><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId></exclusion><exclusion><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-client</artifactId></exclusion></exclusions></dependency><!-- rest-high-level-client 依赖如下2个jar --><dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>${es.version}</version></dependency><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-client</artifactId><version>${es.version}</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

2、application.yml文件内容如下:

server:port: 8081servlet.context-path: /#配置数据源
spring:datasource:druid:db-type: com.alibaba.druid.pool.DruidDataSourcedriverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpyurl: jdbc:log4jdbc:mysql://${DB_HOST:localhost}:${DB_PORT:3306}/${DB_NAME:eladmin}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=falseusername: ${DB_USER:root}password: ${DB_PWD:123456}redis:host: localhostport: 6379password: hemingdatabase: 10es:host: 43.138.0.199port: 9200scheme: http

3、BackendApplication.java文件内容如下:

package com.hmblogs.backend;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class BackendApplication {public static void main(String[] args) {SpringApplication.run(BackendApplication.class, args);}}

4、测试验证,ElasticsearchClientTest.java文件内容如下:


import com.alibaba.fastjson.JSONObject;
import com.hmblogs.backend.entity.Users;
import lombok.extern.slf4j.Slf4j;
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.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.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner;import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;@Slf4j
//@Component
@RunWith(SpringRunner.class)
@SpringBootTest
public class ElasticsearchClientTest {@Autowiredprivate RestHighLevelClient client;String index = "users";/*** 创建索引** @throws IOException*/@Testpublic void createIndex() throws IOException {CreateIndexRequest indexRequest = new CreateIndexRequest(index);CreateIndexResponse response = client.indices().create(indexRequest, RequestOptions.DEFAULT);log.info("创建索引:"+response.isAcknowledged());}/*** 判断索引是否存在** @throws IOException*/@Testpublic void indexExists() throws IOException {GetIndexRequest request = new GetIndexRequest(index);boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);log.info("索引是否存在:"+exists);}/*** 添加文档** @throws IOException*/@Testpublic void addDoc() throws IOException {IndexRequest request = new IndexRequest(index);String source = JSONObject.toJSONString(new Users(10000, "逍遥", 30));// 手动设置id
//        request.id("10000");request.source(source, XContentType.JSON);IndexResponse response = client.index(request, RequestOptions.DEFAULT);log.info("添加文档:"+response.getResult());}/*** 批量添加文档*/@Testpublic void batchAddDoc() throws IOException {BulkRequest bulkRequest = new BulkRequest();List<IndexRequest> requests = generateRequests();for (IndexRequest indexRequest : requests) {bulkRequest.add(indexRequest);}BulkResponse responses = client.bulk(bulkRequest, RequestOptions.DEFAULT);log.info("批量添加结果:"+!responses.hasFailures());}public List<IndexRequest> generateRequests() {List<IndexRequest> requests = new ArrayList<>();requests.add(generateNewsRequest(1, "小明", 22));requests.add(generateNewsRequest(2, "隔壁老王", 30));requests.add(generateNewsRequest(3, "lily", 25));return requests;}public IndexRequest generateNewsRequest(Integer id, String name, Integer age) {IndexRequest indexRequest = new IndexRequest(index);String source = JSONObject.toJSONString(new Users(id, name, age));indexRequest.source(source, XContentType.JSON);return indexRequest;}/*** 更新文档** @throws IOException*/@Testpublic void updateDoc() throws IOException {UpdateRequest updateRequest = new UpdateRequest(index, "AmxCP40BM8-M0To1vOET");Map<String, Object> params = new HashMap<>();params.put("id", "1");params.put("name", "逍遥");params.put("age", 33);params.put("hobby", "唱歌,跳舞,网上冲浪,看电影,旅行");updateRequest.doc(params);UpdateResponse response = client.update(updateRequest, RequestOptions.DEFAULT);log.info("修改文档结果:"+response.getResult());}/*** 搜索** @throws IOException*/@Testpublic void search() throws IOException {SearchRequest request = new SearchRequest(index);SearchSourceBuilder builder = new SearchSourceBuilder();BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();boolQueryBuilder.must(new RangeQueryBuilder("age").from(20).to(30)).must(new TermQueryBuilder("id", 3));builder.query(boolQueryBuilder);request.source(builder);log.info("搜索语句为: " + request.source().toString());SearchResponse search = client.search(request, RequestOptions.DEFAULT);log.info("搜索结果为:"+search);SearchHits hits = search.getHits();SearchHit[] hitsArr = hits.getHits();for (SearchHit documentFields : hitsArr) {log.info(documentFields.getSourceAsString());}}@Testpublic void search2() {SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.from(0);sourceBuilder.size(10);sourceBuilder.fetchSource(new String[]{"name", "age"}, new String[]{});MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("hobby", "唱歌,跳舞,网上冲浪,看电影,旅行");TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "逍遥");RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age");rangeQueryBuilder.gte(20);rangeQueryBuilder.lte(40);BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();boolBuilder.must(matchQueryBuilder);boolBuilder.must(termQueryBuilder);boolBuilder.must(rangeQueryBuilder);sourceBuilder.query(boolBuilder);SearchRequest searchRequest = new SearchRequest(index);searchRequest.source(sourceBuilder);try {log.info("搜索语句为: " + searchRequest.source().toString());SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);log.info("搜索结果为:"+search);SearchHits hits = search.getHits();SearchHit[] hitsArr = hits.getHits();for (SearchHit documentFields : hitsArr) {log.info(documentFields.getSourceAsString());}} catch (IOException e) {log.error("搜索报错:{}",e);}}/*** 删除文档* @throws IOException*/@Testpublic void deleteDoc() throws IOException {DeleteRequest deleteRequest = new DeleteRequest(index, "3g8vP40Bi8WQ8ue06wWd");DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT);log.info("删除结果为:"+response.getResult());}/*** 删除索引* @throws IOException*/@Testpublic void deleteIndex() throws IOException {DeleteIndexRequest request = new DeleteIndexRequest(index);AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);log.info("删除索引结果为:"+response.isAcknowledged());}}

每个方法的作用见注释说明,

 这里点击Run search2()

然后查看console的log,验证OK

这样写代码,还是不够灵活,能不能执行自定义的SQL或者DSL语句,这样就可以不用去想办法看下Builder那些类对象怎么设置了。

其实,要想实现这样的效果,就是调用http接口而已

RestTemplateUtil.java文件内容如下:


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;import java.util.HashMap;
import java.util.Map;@Component
public class RestTemplateUtil {@Autowiredprivate RestTemplate restTemplate;public String post(String url,Map map){// 设置请求头属性HttpHeaders httpHeaders = new HttpHeaders();httpHeaders.setContentType(MediaType.APPLICATION_JSON);HttpEntity httpEntity = new HttpEntity(map, httpHeaders);String results = restTemplate.postForObject(url, httpEntity, String.class);return results;}
}

ElasticsearchClientSqlDslTest.java类文件内容如下:


import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.util.HashMap;
import java.util.Map;@Slf4j
//@Component
@RunWith(SpringRunner.class)
@SpringBootTest
public class ElasticsearchClientSqlDslTest {@Autowiredprivate RestTemplateUtil restTemplateUtil;@Testpublic void complexQueryEsData() {// 请求参数Map map = new HashMap<>();map.put("query", "SELECT id,name,age FROM users order by name desc limit 6");String url = "http://43.138.0.199:9200/_sql?format=json";String studentData = restTemplateUtil.post(url, map);log.info("studentData:"+studentData);}
}

执行后,查出了数据,console如下截图:

返回数据如下:

{"columns":[{"name":"id","type":"long"},{"name":"name","type":"text"},{"name":"age","type":"long"}],"rows":[[2,"隔壁老王",30],[1,"逍遥",33],[1,"小明",22],[3,"lily",25]]}

 

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

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

相关文章

空间计算时代催生新一波巨大算力市场需求

什么是空间计算&#xff1f; 空间计算是一种整合虚拟现实&#xff08;VR&#xff09;、增强现实&#xff08;AR&#xff09;、混合现实&#xff08;MR&#xff09;等技术的计算模式&#xff0c;旨在将数字信息与真实世界融合在一起。这种融合创造了一个全新的计算环境&#xff…

【极数系列】docker环境搭建Flink1.18版本(04)

文章目录 引言01 Linux安装Docker1.安装yum-utils软件包2.安装docker3.启动docker4.设置docker自启动5.配置Docker使用systemd作为默认Cgroup驱动6.重启docker 02 docker部署Flink1.18版本1.拉取最新镜像2.检查镜像3.编写dockerFile文件4.执行dockerFile5.检查flink是否启动成功…

一个SSE(流式)接口引发的问题

前言 最近我们公司也是在做认知助手&#xff0c;大模型相关的功能&#xff0c;正在做提示词&#xff0c;机器人对话相关功能。想要提高用户体验&#xff0c;使用SSE请求模式&#xff0c;在不等数据完全拿到的情况下边拿边返回。 之前做过一版&#xff0c;但不是流式返回&…

机房环境动力监控系统:S275远程控制网关助力高效管理

现场问题 1、机房安全隐患 机房存在意外断电、温湿度过高过低、漏水断路等隐患&#xff0c;传统监测手段难以提前发现和预警。 2、机房远程运维困难 因环境改变、非授权活动、设备状态变化等引起的事故&#xff0c;难以满足机房远程运维的可靠管控要求。 3、机房改造成本高…

Django 实现SS

1、简单的sse只要用django内置的StreamingHttpResponse就可以实现 2、django-sse这个第三方库已经有10年没有更新&#xff0c;不要用这个库了。 3、告知前端关闭SSE连接需要发送yield "event: close\ndata: \n\n" 而不能只发送yield "event: close\n" …

菱形打印和十进制ip转二进制

1.菱形打印 用for循环 #!/bin/bashread -p "请输入菱形的大小&#xff1a;" num #打印向上的等腰三角形 for ((i1;i<num;i)) dofor ((jnum-1;j>i;j--))doecho -n " " #打印的是前面的空格donefor ((k1;k<2*i-1;k))doecho -n "*" #打印…

OneNote中的键盘快捷记录(超全)

本文列出了桌面 WindowsOneNote 的键盘快捷方式。 常用快捷方式 执行的操作 按 打开新的 OneNote 窗口。 CtrlM 创建 快速笔记。 CtrlShiftM 或 AltWindows 徽标键N 停靠 OneNote 窗口。 CtrlAltD 撤消前一个操作。 CtrlZ 如果可能&#xff0c;请重做上一个操作。 …

HCIE之BGP正则表达式(四)

BGP 一、AS-Path正则表达式数字| 等同于或的关系[]和.$ 一个字符串的结束_代表任意^一个字符串的开始()括号包围的是一个组合\ 转义字符* 零个或多个&#xff1f;零个或一个一个或多个 二、BGP对等体组三、BGP安全性 一、AS-Path正则表达式 正则表达式是按照一定模版匹配字符串…

《思考的快与慢》部分整理

认知心理学机位大洞见&#xff1a;人类大脑的默认模式是系统1&#xff0c;而不是系统2&#xff0c;人类大脑遵循“能不用脑&#xff0c;就不用脑”的原则。 系统1&#xff08;快系统&#xff09;对应着我们常说的直觉思维 系统2&#xff08;慢系统&#xff09;对应着理性思维…

Linux实验记录:使用RAID(独立冗余磁盘阵列)

前言&#xff1a; 本文是一篇关于Linux系统初学者的实验记录。 参考书籍&#xff1a;《Linux就该这么学》 实验环境&#xff1a; VmwareWorkStation 17——虚拟机软件 RedHatEnterpriseLinux[RHEL]8——红帽操作系统 目录 前言&#xff1a; 备注&#xff1a; 部署磁盘阵…

Vue路由

1. 路由的基本概念 1.1. 什么是路由&#xff1f; 路由的概念 路由的本质就是一种对应关系&#xff0c;比如说我们在url地址中输入我们要访问的url地址之后&#xff0c;浏览器要去请求这个url地址对应的资源。 那么url地址和真实的资源之间就有一种对应的关系&#xff0c;就是…

成功解决IndexError: index 0 is out of bounds for axis 1 with size 0.

成功解决IndexError: index 0 is out of bounds for axis 1 with size 0. &#x1f335;文章目录&#x1f335; &#x1f333;引言&#x1f333;&#x1f333;报错分析及解决方案&#x1f333;&#x1f333;参考文章&#x1f333;&#x1f333;结尾&#x1f333; &#x1f333;…

Cesium.js实现显示点位对应的自定义信息弹窗(数据面板)

零、相关技术选型&#xff1a; Vue2 Vuecli5 Cesium.js 天地图 一、需求说明 在使用2D地图&#xff08;天地图、高德地图等&#xff09;基于官方文档可以实现下面需求&#xff1a; 实现添加点位&#xff0c;并在点位附近显示对应的信息弹窗。 一般信息弹窗的显示方式有两种&am…

【数据结构1-2】二叉树

树形结构不仅能表示数据间的指向关系&#xff0c;还能表示出数据的层次关系&#xff0c;而有很明显的递归性质。因此&#xff0c;我们可以利用树的性质解决更多种类的问题。 但是在平常的使用中&#xff0c;我们并不需要使用这么复杂的结构&#xff0c;只需要建立一个包含int r…

分享一个POI封装的Excel解析工具

前言: 本来我已经很久没做java的项目了&#xff0c;最近手头的项目没啥事又被拉过去搞java了&#xff0c;但是看到这帮人写的代码&#xff0c;心凉了一截&#xff0c;写一个Excel的导入写的 都有很多问题&#xff0c; 写个示范吧&#xff1a; ExcelUtil util new ExcelUtil()&…

【极数系列】Flink配置参数如何获取?(06)

文章目录 gitee码云地址简介概述01 配置值来自.properties文件1.通过路径读取2.通过文件流读取3.通过IO流读取 02 配置值来自命令行03 配置来自系统属性04 注册以及使用全局变量05 Flink获取参数值Demo1.项目结构2.pom.xml文件如下3.配置文件4.项目主类5.运行查看相关日志 gite…

sqli-labs第一关

1.判断是否存在注入&#xff0c;注入是字符型还是数字型? ?id1 and 11 ?id1 and 12 因为输入and 11与and 12 回显正常&#xff0c;所以该地方不是数字型。 ?id1 ?id1-- 输入单引号后报错&#xff0c;在单引号后添加--恢复正常&#xff0c;说明存在字符注入 2.猜解SQL查…

【物联网】物联网技术的起源、发展、重点技术、应用场景与未来演进

物联网技术的起源、发展、重点技术、应用场景与未来演进 物联网&#xff08;IoT, Internet of Things&#xff09;是近年来科技领域中的热门话题&#xff0c;它将物理世界的各种“事物”与互联网连接起来&#xff0c;从而实现了数据的交换和通信。物联网技术的起源可追溯到20世…

【新书推荐】3.7 数据类型转换

本节必须掌握的知识点&#xff1a; 整型提升 浮点型和整型转换 浮点型转换 普通算术类型转换 示例十二 在实际项目应用过程中&#xff0c;我们通常会根据实际需要&#xff0c;对数据进行扩展和截取&#xff0c;我们称之为数据类型转换。对数据类型的转换需要遵循以下规则。 3.7…

毕业论文格式

官方格式 编号格式&#xff1a; 【论文标题设置】论文一二三级标题设置_哔哩哔哩_bilibili 编号和文字的间距太大怎么办&#xff1f;两招轻松解决&#xff01;