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

2024-01-25 16:12

本文主要是介绍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]]}

 

这篇关于spring boot学习第八篇:操作elastic search的索引和索引中的数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/643819

相关文章

Java实现字节字符转bcd编码

《Java实现字节字符转bcd编码》BCD是一种将十进制数字编码为二进制的表示方式,常用于数字显示和存储,本文将介绍如何在Java中实现字节字符转BCD码的过程,需要的小伙伴可以了解下... 目录前言BCD码是什么Java实现字节转bcd编码方法补充总结前言BCD码(Binary-Coded Decima

SpringBoot全局域名替换的实现

《SpringBoot全局域名替换的实现》本文主要介绍了SpringBoot全局域名替换的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录 项目结构⚙️ 配置文件application.yml️ 配置类AppProperties.Ja

Java使用Javassist动态生成HelloWorld类

《Java使用Javassist动态生成HelloWorld类》Javassist是一个非常强大的字节码操作和定义库,它允许开发者在运行时创建新的类或者修改现有的类,本文将简单介绍如何使用Javass... 目录1. Javassist简介2. 环境准备3. 动态生成HelloWorld类3.1 创建CtC

JavaScript中的高级调试方法全攻略指南

《JavaScript中的高级调试方法全攻略指南》什么是高级JavaScript调试技巧,它比console.log有何优势,如何使用断点调试定位问题,通过本文,我们将深入解答这些问题,带您从理论到实... 目录观点与案例结合观点1观点2观点3观点4观点5高级调试技巧详解实战案例断点调试:定位变量错误性能分

Java实现将HTML文件与字符串转换为图片

《Java实现将HTML文件与字符串转换为图片》在Java开发中,我们经常会遇到将HTML内容转换为图片的需求,本文小编就来和大家详细讲讲如何使用FreeSpire.DocforJava库来实现这一功... 目录前言核心实现:html 转图片完整代码场景 1:转换本地 HTML 文件为图片场景 2:转换 H

Java使用jar命令配置服务器端口的完整指南

《Java使用jar命令配置服务器端口的完整指南》本文将详细介绍如何使用java-jar命令启动应用,并重点讲解如何配置服务器端口,同时提供一个实用的Web工具来简化这一过程,希望对大家有所帮助... 目录1. Java Jar文件简介1.1 什么是Jar文件1.2 创建可执行Jar文件2. 使用java

SpringBoot实现不同接口指定上传文件大小的具体步骤

《SpringBoot实现不同接口指定上传文件大小的具体步骤》:本文主要介绍在SpringBoot中通过自定义注解、AOP拦截和配置文件实现不同接口上传文件大小限制的方法,强调需设置全局阈值远大于... 目录一  springboot实现不同接口指定文件大小1.1 思路说明1.2 工程启动说明二 具体实施2

Java实现在Word文档中添加文本水印和图片水印的操作指南

《Java实现在Word文档中添加文本水印和图片水印的操作指南》在当今数字时代,文档的自动化处理与安全防护变得尤为重要,无论是为了保护版权、推广品牌,还是为了在文档中加入特定的标识,为Word文档添加... 目录引言Spire.Doc for Java:高效Word文档处理的利器代码实战:使用Java为Wo

SpringBoot日志级别与日志分组详解

《SpringBoot日志级别与日志分组详解》文章介绍了日志级别(ALL至OFF)及其作用,说明SpringBoot默认日志级别为INFO,可通过application.properties调整全局或... 目录日志级别1、级别内容2、调整日志级别调整默认日志级别调整指定类的日志级别项目开发过程中,利用日志

Java中的抽象类与abstract 关键字使用详解

《Java中的抽象类与abstract关键字使用详解》:本文主要介绍Java中的抽象类与abstract关键字使用详解,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧... 目录一、抽象类的概念二、使用 abstract2.1 修饰类 => 抽象类2.2 修饰方法 => 抽象方法,没有