【业务功能篇83】微服务SpringCloud-ElasticSearch-Kibanan-docke安装-应用层实战

news/2025/3/14 18:12:16/

五、ElasticSearch应用

1.ES 的Java API两种方式

  Elasticsearch 的API 分为 REST Client API(http请求形式)以及 transportClient
API两种。相比来说transportClient API效率更高,transportClient
是通过Elasticsearch内部RPC的形式进行请求的,连接可以是一个长连接,相当于是把客户端的请求当成

  Elasticsearch 集群的一个节点,当然 REST Client API 也支持http
keepAlive形式的长连接,只是非内部RPC形式。但是从Elasticsearch 7 后就会移除transportClient
。主要原因是transportClient 难以向下兼容版本。

1.1 9300[TCP]

  利用9300端口的是spring-data-elasticsearch:transport-api.jar,但是这种方式因为对应的SpringBoot版本不一致,造成对应的transport-api.jar也不同,不能适配es的版本,而且ElasticSearch7.x中已经不推荐使用了,ElasticSearch 8之后更是废弃了,所以我们不做过多的介绍

1.2 9200[HTTP]

  基于9200端口的方式也有多种

  • JsetClient:非官方,更新缓慢
  • RestTemplate:模拟发送Http请求,ES很多的操作需要我们自己来封装,效率低
  • HttpClient:和上面的情况一样
  • ElasticSearch-Rest-Client:官方的RestClient,封装了ES的操作,API层次分明,易于上手。
  • JavaAPIClient 7.15版本后推荐

2.ElasticSearch-Rest-Client整合

2.1 创建检索的服务

  我们在商城服务中创建一个检索的SpringBoot服务

image.png

添加对应的依赖:官方地址:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-getting-started-maven.html#java-rest-high-getting-started-maven-maven

image.png

公共依赖不要忘了,同时我们在公共依赖中依赖了MyBatisPlus所以我们需要在search服务中排除数据源,不然启动报错

image.png

image.png

然后我们需要把这个服务注册到Nacos注册中心中,这块操作了很多遍,不重复

添加对应的ElasticSearch的配置类

/*** ElasticSearch的配置类*/
@Configuration
public class MallElasticSearchConfiguration {@Beanpublic RestHighLevelClient restHighLevelClient(){RestClientBuilder builder = RestClient.builder(new HttpHost("192.168.56.100", 9200, "http"));RestHighLevelClient client = new RestHighLevelClient(builder);return client;}
}

image.png

测试:

image.png

2.2 测试保存文档

设置RequestOptions

image.png

我们就在ElasticSearch的配置文件中设置

image.png

保存数据

然后就可以结合官方文档来实现文档数据的存储

package com.msb.mall.mallsearch;import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.msb.mall.mallsearch.config.MallElasticSearchConfiguration;
import lombok.Data;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
class MallSearchApplicationTests {@Autowiredprivate RestHighLevelClient client;@Testvoid contextLoads() {System.out.println("--->"+client);}/*** 测试保存文档*/@Testvoid saveIndex() throws Exception {IndexRequest indexRequest = new IndexRequest("system");indexRequest.id("1");// indexRequest.source("name","bobokaoya","age",18,"gender","男");User user = new User();user.setName("bobo");user.setAge(22);user.setGender("男");// 用Jackson中的对象转json数据ObjectMapper objectMapper = new ObjectMapper();String json = objectMapper.writeValueAsString(user);indexRequest.source(json, XContentType.JSON);// 执行操作IndexResponse index = client.index(indexRequest, MallElasticSearchConfiguration.COMMON_OPTIONS);// 提取有用的返回信息System.out.println(index);}@Dataclass User{private String name;private Integer age;private String gender;}}

之后成功

image.png

image.png

2.3 检索操作

参考官方文档可以获取到处理各种检索情况的API

案例1:检索出所有的bank索引的所有文档

    @Testvoid searchIndexAll() throws IOException {// 1.创建一个 SearchRequest 对象SearchRequest searchRequest = new SearchRequest();searchRequest.indices("bank"); // 设置我们要检索的数据对应的索引库SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();/*sourceBuilder.query();sourceBuilder.from();sourceBuilder.size();sourceBuilder.aggregation();*/searchRequest.source(sourceBuilder);// 2.如何执行检索操作SearchResponse response = client.search(searchRequest, MallElasticSearchConfiguration.COMMON_OPTIONS);// 3.获取检索后的响应对象,我们需要解析出我们关心的数据System.out.println("ElasticSearch检索的信息:"+response);}

image.png

案例2:根据address全文检索

    @Testvoid searchIndexByAddress() throws IOException {// 1.创建一个 SearchRequest 对象SearchRequest searchRequest = new SearchRequest();searchRequest.indices("bank"); // 设置我们要检索的数据对应的索引库SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();// 查询出bank下 address 中包含 mill的记录sourceBuilder.query(QueryBuilders.matchQuery("address","mill"));searchRequest.source(sourceBuilder);// System.out.println(searchRequest);// 2.如何执行检索操作SearchResponse response = client.search(searchRequest, MallElasticSearchConfiguration.COMMON_OPTIONS);// 3.获取检索后的响应对象,我们需要解析出我们关心的数据System.out.println("ElasticSearch检索的信息:"+response);}

案例3:嵌套的聚合操作:检索出bank下的年龄分布和每个年龄段的平均薪资

/*** 聚合:嵌套聚合* @throws IOException*/@Testvoid searchIndexAggregation() throws IOException {// 1.创建一个 SearchRequest 对象SearchRequest searchRequest = new SearchRequest();searchRequest.indices("bank"); // 设置我们要检索的数据对应的索引库SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();// 查询出bank下 所有的文档sourceBuilder.query(QueryBuilders.matchAllQuery());// 聚合 aggregation// 聚合bank下年龄的分布和每个年龄段的平均薪资AggregationBuilder aggregationBuiler = AggregationBuilders.terms("ageAgg").field("age").size(10);// 嵌套聚合aggregationBuiler.subAggregation(AggregationBuilders.avg("balanceAvg").field("balance"));sourceBuilder.aggregation(aggregationBuiler);sourceBuilder.size(0); // 聚合的时候就不用显示满足条件的文档内容了searchRequest.source(sourceBuilder);System.out.println(sourceBuilder);// 2.如何执行检索操作SearchResponse response = client.search(searchRequest, MallElasticSearchConfiguration.COMMON_OPTIONS);// 3.获取检索后的响应对象,我们需要解析出我们关心的数据System.out.println(response);}

案例4:并行的聚合操作:查询出bank下年龄段的分布和总的平均薪资

/*** 聚合* @throws IOException*/@Testvoid searchIndexAggregation1() throws IOException {// 1.创建一个 SearchRequest 对象SearchRequest searchRequest = new SearchRequest();searchRequest.indices("bank"); // 设置我们要检索的数据对应的索引库SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();// 查询出bank下 所有的文档sourceBuilder.query(QueryBuilders.matchAllQuery());// 聚合 aggregation// 聚合bank下年龄的分布和平均薪资AggregationBuilder aggregationBuiler = AggregationBuilders.terms("ageAgg").field("age").size(10);sourceBuilder.aggregation(aggregationBuiler);// 聚合平均年龄AvgAggregationBuilder balanceAggBuilder = AggregationBuilders.avg("balanceAgg").field("age");sourceBuilder.aggregation(balanceAggBuilder);sourceBuilder.size(0); // 聚合的时候就不用显示满足条件的文档内容了searchRequest.source(sourceBuilder);System.out.println(sourceBuilder);// 2.如何执行检索操作SearchResponse response = client.search(searchRequest, MallElasticSearchConfiguration.COMMON_OPTIONS);// 3.获取检索后的响应对象,我们需要解析出我们关心的数据System.out.println(response);}

案例5:处理检索后的结果

 @Testvoid searchIndexResponse() throws IOException {// 1.创建一个 SearchRequest 对象SearchRequest searchRequest = new SearchRequest();searchRequest.indices("bank"); // 设置我们要检索的数据对应的索引库SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();// 查询出bank下 address 中包含 mill的记录sourceBuilder.query(QueryBuilders.matchQuery("address","mill"));searchRequest.source(sourceBuilder);// System.out.println(searchRequest);// 2.如何执行检索操作SearchResponse response = client.search(searchRequest, MallElasticSearchConfiguration.COMMON_OPTIONS);// 3.获取检索后的响应对象,我们需要解析出我们关心的数据// System.out.println("ElasticSearch检索的信息:"+response);RestStatus status = response.status();TimeValue took = response.getTook();SearchHits hits = response.getHits();TotalHits totalHits = hits.getTotalHits();TotalHits.Relation relation = totalHits.relation;long value = totalHits.value;float maxScore = hits.getMaxScore(); // 相关性的最高分SearchHit[] hits1 = hits.getHits();for (SearchHit documentFields : hits1) {/*"_index" : "bank","_type" : "account","_id" : "970","_score" : 5.4032025*///documentFields.getIndex(),documentFields.getType(),documentFields.getId(),documentFields.getScore();String json = documentFields.getSourceAsString();//System.out.println(json);// JSON字符串转换为 Object对象ObjectMapper mapper = new ObjectMapper();Account account = mapper.readValue(json, Account.class);System.out.println("account = " + account);}//System.out.println(relation.toString()+"--->" + value + "--->" + status);}@ToString@Datastatic class Account {private int account_number;private int balance;private String firstname;private String lastname;private int age;private String gender;private String address;private String employer;private String email;private String city;private String state;}

数据的结果:

image.png


http://www.ppmy.cn/news/1061587.html

相关文章

MyBatis与Spring整合以及AOP和PageHelper分页插件整合

目录 前言 一、MyBatis与Spring整合的好处以及两者之间的关系 1.好处 2.关系 二、MyBatis和Spring集成 1.导入pom.xml 2.编写配置文件 3.利用mybatis逆向工程生成模型层代码 三、常用注解 四、AOP整合pageHelper分页插件 创建一个切面 测试 前言 MyBatis是一个开源的…

论文阅读_模型结构_LoRA

name_en: LoRA: Low-Rank Adaptation of Large Language Models name_ch: LORA:大语言模型的低阶自适应 paper_addr: http://arxiv.org/abs/2106.09685 date_read: 2023-08-17 date_publish: 2021-10-16 tags: [‘深度学习’,‘大模型’] author: Edward J. Hu cita…

人工智能技术的主要类别

人工智能技术主要类别: 机器学习: 监督学习:使用带有标签的训练数据来训练模型,使其能够预测未知数据的标签。常见任务包括分类和回归。无监督学习:使用无标签的训练数据,模型通过发现数据中的模式、聚类或…

【洛谷】P2440 木材加工

原题链接:https://www.luogu.com.cn/problem/P2440 1. 题目描述 2. 思路分析 整体思路:二分答案 设置一个变量longest来记录最长木头的长度,sum记录切成的小段数量之和。 令左边界l0,右边界llongest。 写一个bool类型的check…

solidity0.8.0的应用案例12:通用可升级合约UUPS

代理合约中选择器冲突(Selector Clash)的另一个解决办法:通用可升级代理(UUPS,universal upgradeable proxy standard)。代码由OpenZeppelin的UUPSUpgradeable简化而成,不应用于生产。 UUPS 作为透明代理的替代方案,UUPS也能解决"选择器冲突"(Selector Cl…

Python 数据分析——matplotlib 快速绘图

matplotlib采用面向对象的技术来实现,因此组成图表的各个元素都是对象,在编写较大的应用程序时通过面向对象的方式使用matplotlib将更加有效。但是使用这种面向对象的调用接口进行绘图比较烦琐,因此matplotlib还提供了快速绘图的pyplot模块。…

Java——简单的文件读取和写入

这段代码是一个简单的文件读取和写入的例子。它创建了一个BufferFile类,构造方法接受一个文件名作为参数。BufferFile类中的write方法用于从标准输入读取内容,并将其写入到指定的文件中,直到输入"end"为止。read方法用于读取指定文…

《Python基础教程》专栏总结篇

大家好,我是爱编程的喵喵。双985硕士毕业,现担任全栈工程师一职,热衷于将数据思维应用到工作与生活中。从事机器学习以及相关的前后端开发工作。曾在阿里云、科大讯飞、CCF等比赛获得多次Top名次。现为CSDN博客专家、人工智能领域优质创作者。…