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

相关文章

在Ubuntu上部署SpringBoot应用的操作步骤

《在Ubuntu上部署SpringBoot应用的操作步骤》随着云计算和容器化技术的普及,Linux服务器已成为部署Web应用程序的主流平台之一,Java作为一种跨平台的编程语言,具有广泛的应用场景,本... 目录一、部署准备二、安装 Java 环境1. 安装 JDK2. 验证 Java 安装三、安装 mys

Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单

《Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单》:本文主要介绍Springboot的ThreadPoolTaskScheduler线... 目录ThreadPoolTaskScheduler线程池实现15分钟不操作自动取消订单概要1,创建订单后

详谈redis跟数据库的数据同步问题

《详谈redis跟数据库的数据同步问题》文章讨论了在Redis和数据库数据一致性问题上的解决方案,主要比较了先更新Redis缓存再更新数据库和先更新数据库再更新Redis缓存两种方案,文章指出,删除R... 目录一、Redis 数据库数据一致性的解决方案1.1、更新Redis缓存、删除Redis缓存的区别二

oracle数据库索引失效的问题及解决

《oracle数据库索引失效的问题及解决》本文总结了在Oracle数据库中索引失效的一些常见场景,包括使用isnull、isnotnull、!=、、、函数处理、like前置%查询以及范围索引和等值索引... 目录oracle数据库索引失效问题场景环境索引失效情况及验证结论一结论二结论三结论四结论五总结ora

JAVA中整型数组、字符串数组、整型数和字符串 的创建与转换的方法

《JAVA中整型数组、字符串数组、整型数和字符串的创建与转换的方法》本文介绍了Java中字符串、字符数组和整型数组的创建方法,以及它们之间的转换方法,还详细讲解了字符串中的一些常用方法,如index... 目录一、字符串、字符数组和整型数组的创建1、字符串的创建方法1.1 通过引用字符数组来创建字符串1.2

Redis事务与数据持久化方式

《Redis事务与数据持久化方式》该文档主要介绍了Redis事务和持久化机制,事务通过将多个命令打包执行,而持久化则通过快照(RDB)和追加式文件(AOF)两种方式将内存数据保存到磁盘,以防止数据丢失... 目录一、Redis 事务1.1 事务本质1.2 数据库事务与redis事务1.2.1 数据库事务1.

SpringCloud集成AlloyDB的示例代码

《SpringCloud集成AlloyDB的示例代码》AlloyDB是GoogleCloud提供的一种高度可扩展、强性能的关系型数据库服务,它兼容PostgreSQL,并提供了更快的查询性能... 目录1.AlloyDBjavascript是什么?AlloyDB 的工作原理2.搭建测试环境3.代码工程1.

Java调用Python代码的几种方法小结

《Java调用Python代码的几种方法小结》Python语言有丰富的系统管理、数据处理、统计类软件包,因此从java应用中调用Python代码的需求很常见、实用,本文介绍几种方法从java调用Pyt... 目录引言Java core使用ProcessBuilder使用Java脚本引擎总结引言python

SpringBoot操作spark处理hdfs文件的操作方法

《SpringBoot操作spark处理hdfs文件的操作方法》本文介绍了如何使用SpringBoot操作Spark处理HDFS文件,包括导入依赖、配置Spark信息、编写Controller和Ser... 目录SpringBoot操作spark处理hdfs文件1、导入依赖2、配置spark信息3、cont

springboot整合 xxl-job及使用步骤

《springboot整合xxl-job及使用步骤》XXL-JOB是一个分布式任务调度平台,用于解决分布式系统中的任务调度和管理问题,文章详细介绍了XXL-JOB的架构,包括调度中心、执行器和Web... 目录一、xxl-job是什么二、使用步骤1. 下载并运行管理端代码2. 访问管理页面,确认是否启动成功