Elasticsearch整合SpringBoot案例
1、elasticsearch官方文档的使用与介绍
1.1、Rest客户端初始化官方文档链接:
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-getting-started-initialization.html#java-rest-high-getting-started-initialization
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http")));
1.2、RequestOptions官方文档链接:
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-low-usage-requests.html#java-rest-low-usage-request-options
这 RequestOptions类包含应共享的部分请求在同一应用程序中的多个请求之间。通过RequestOptions对请求进行统一设置
private static final RequestOptions COMMON_OPTIONS;
static {
RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
builder.addHeader("Authorization", "Bearer " + TOKEN);
builder.setHttpAsyncResponseConsumerFactory(
new HttpAsyncResponseConsumerFactory
.HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));
COMMON_OPTIONS = builder.build();
}
1.3、对数据进行保存,创建Index索引官方文档:
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-document-index.html#java-rest-high-document-index
选择在哪个索引中存储数据,并且设置“键”-“存储的值”:
IndexRequest indexRequest = new IndexRequest("posts").id("1").source(要存储的JSON数据);
执行存储:
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
1.4、对数据进行查询官方文档:
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-search.html
所有的根操作都可以根据SearchSourceBuilder进行实现:
SearchRequest searchRequest = new SearchRequest();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.size();
searchSourceBuilder.from();
searchRequest.source(searchSourceBuilder);
使用同步方式进行查询执行
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
要获取筛选后的数据,我们首先需要获取响应中包含的 SearchHits:
SearchHits hits = searchResponse.getHits();
SearchHits 提供有关所有命中的全局信息,例如命中总数或最高分数:
TotalHits totalHits = hits.getTotalHits();
//总命中数,必须在totalHits.relation的上下文中解释
long numHits = totalHits.value;
//命中数是准确的 (EQUAL_TO) 还是总数的下限 (GREATER_THAN_OR_EQUAL_TO)
TotalHits.Relation relation = totalHits.relation;
float maxScore = hits.getMaxScore();
嵌套在 SearchHits 中的是可以迭代的划分开的具体搜索结果:
SearchHit[] searchHits = hits.getHits();
for (SearchHit hit : searchHits) {
// do something with the SearchHit
}
2、实际案例中整合例子:
2.1、创建elasticsearch存储结构:
PUT imooc_news
{
"mappings": {
"properties": {
"id":{
"type": "keyword"
},
"title":{
"type": "text"
},
"categoryId":{
"type": "integer"
},
" articleType":{
"type": "integer"
},
"articleCover":{
"type": "keyword"
},
"isAppoint":{
"type": "keyword"
},
"articleStatus":{
"type": "integer"
},
"publishUserId":{
"type": "keyword"
},
"publishTime":{
"type": "date"
},
"readCounts":{
"type": "integer"
},
"commentCounts":{
"type": "integer"
},
"mongoFileId":{
"type": "keyword"
},
"isDelete":{
"type": "integer"
},
"createTime":{
"type": "date"
},
"updateTime":{
"type": "date"
},
"content":{
"type": "text"
}
}
}
}
2.2、配置方法
@Configuration
public class ElasticSearchConfig {
public static final RequestOptions COMMON_OPTIONS;
static {
RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
/* builder.addHeader("Authorization", "Bearer " + TOKEN);
builder.setHttpAsyncResponseConsumerFactory(
new HttpAsyncResponseConsumerFactory
.HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));*/
COMMON_OPTIONS = builder.build();
} @Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
new HttpHost("192.168.111.131", 9200, "http")));
return client;
}
}
2.3、进行相关数据存储:
public void updateArticleStatus(String articleId, Integer status) throws IOException {
Article article = new Article();
article.setId(articleId);
article.setArticleStatus(status);
articleMapper.updateByPrimaryKeySelective(article);
Article articleOne = articleMapper.selectByPrimaryKey(articleId);
//ES官方推荐的一次bulk size介于5-15MB之间,请求个数是1000-5000个
//BulkRequest bulkRequest = new BulkRequest();
IndexRequest indexRequest = new IndexRequest(EsContant.PRODUCT_INDEX);
indexRequest.id(articleOne.getId());
String s = JSON.toJSONString(articleOne);
//传入Json类型数据时必须设置XContentType.JSON
indexRequest.source(s, XContentType.JSON);
//bulkRequest.add(indexRequest);
IndexResponse index = restHighLevelClient.index(indexRequest, ElasticSearchConfig.COMMON_OPTIONS);
}
2.4、对数据进行查询:
@Override
public PagedGridResult queryArticlePortalString(String keyword, Integer category, Integer page, Integer pageSize) throws IOException {
//SearchSourceBuilder用于构建查询语句,所有跟操作都可以直接使用 SearchSourceBuilder的方法进
//在本例中:{"query":{"bool":{"filter":[{"term":{"categoryId":{"value":11,"boost":1.0}}}],"adjust_pure_negative":true,"boost":1.0}}}
//所以跟操作时query
//总指elasticsearch查询核心在于对捋清楚条件的嵌套逻辑
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//进行模糊查询,由于要对title进行模糊查询,所以title的类型应该设置成text而不是keyword
if (!StringUtils.isEmpty(keyword)) {
boolQuery.must(QueryBuilders.matchQuery("title", keyword));
}
//根据category进行查找筛选
if (!StringUtils.isEmpty(category)) {
boolQuery.filter(QueryBuilders.termQuery("categoryId", category));
}
sourceBuilder.query(boolQuery); String s = sourceBuilder.toString();
System.out.println("构建DSL" + s);
/** SearchRequest searchRequest = new SearchRequest();
* searchRequest.indices("posts");
* searchRequest.source(sourceBuilder);
* 以下的方法相当于以上方法的结合体
**/
SearchRequest searchRequest = new SearchRequest(new String[]{EsContant.PRODUCT_INDEX}, sourceBuilder); /**
* {
* "took" : 3,
* "timed_out" : false,
* "_shards" : {
* "total" : 1,
* "successful" : 1,
* "skipped" : 0,
* "failed" : 0
* },
* "hits" : {
* "total" : {
* "value" : 1,
* "relation" : "eq"
* },
* "max_score" : 0.9105468,
* "hits" : [
* {
* "_index" : "imooc_news_dev",
* "_type" : "_doc",
* "_id" : "210510BTG8GFT8BC",
* "_score" : 0.9105468,
* "_source" : {
* "articleCover" : "",
* "articleStatus" : 4,
* "articleType" : 2,
* "categoryId" : 11,
* "commentCounts" : 0,
* "content" : ".......文章内容.......",
* "createTime" : 1620635728000,
* "id" : "210510BTG8GFT8BC",
* "isAppoint" : 0,
* "isDelete" : 0,
* "publishTime" : 1620635728000,
* "publishUserId" : "210509HK5HYTHZR4",
* "readCounts" : 0,
* "title" : "字节、腾讯、金山wps、跟谁学、百度 go工程师面试题集锦",
* "updateTime" : 1620635728000
* }
* }
* ]
* }
* }
*/
// 2、执行检索
SearchResponse response = client.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS); SearchHits hits = response.getHits();
SearchHit[] newsHits = hits.getHits();
List<Article> articles = new ArrayList<>();
if (newsHits != null && newsHits.length > 0) {
for (SearchHit newsHit : newsHits) {
String sourceAsString = newsHit.getSourceAsString();
Article article = JSON.parseObject(sourceAsString, Article.class);
articles.add(article);
}
}
// PageHelper.startPage(page,pageSize);
return setterPagedGrid(articles, page);
}
Elasticsearch整合SpringBoot案例的更多相关文章
- elasticSearch 7.6.1 入门及elasticSearch整合springboot
一.ElasticSearch概述 官网:https://www.elastic.co/cn/downloads/elasticsearch Elaticsearch,简称为es,es是一个开源的高扩 ...
- 【SpringBoot】搜索框架ElasticSearch介绍和整合SpringBoot
========================12章 搜索框架ElasticSearch介绍和整合SpringBoot ============================= 加入小D课堂技术交 ...
- SpringBoot整合Mybatis案例
SpringBoot整合Mybatis案例 2019/7/15以实习生身份入职公司前端做Angular ,但是感觉前途迷茫,于是乎学习一下Java的框架——SpringBooot. 参照大神博客:ht ...
- SpringBoot整合Swagger2案例,以及报错:java.lang.NumberFormatException: For input string: ""原因和解决办法
原文链接:https://blog.csdn.net/weixin_43724369/article/details/89341949 SpringBoot整合Swagger2案例 先说SpringB ...
- 史上最全SpringBoot整合Mybatis案例
摘要:如果小编说,SpringBoot是目前为止最好的框架,应该没有人会反驳吧?它的出现使得我们很容易就能搭建一个新应用.那么,SpringBoot与其他第三方框架的整合必定是我们需要关注的重点. 开 ...
- 初识elasticsearch_2(查询和整合springboot)
初始化 首先将官网所下载的json文件,放入到es中,采用如下命令: curl -H "Content-Type: application/json" -XPOST 'localh ...
- ElasticSearch业务逻辑案例
ElasticSearch业务逻辑案例 一.业务难题 我们有一个索引: myindex/mytype(为了方便,我们下文以a/b表示) 索引类型中的一个字段group之前是a.b.c(历史遗留问题), ...
- 基于Centos 7.4 搭建ELK整合SpringBoot日志收集
基于Centos 7.4搭建es7.12.0+logstash-7.12.0+kibana-7.12.0(ELK)整合SpringBoot日志收集 注:Skywalking和logstash可共用一个 ...
- 整合springboot(app后台框架搭建四)
springboot可以说是为了适用SOA服务出现,一方面,极大的简便了配置,加速了开发速度:第二方面,也是一个嵌入式的web服务,通过jar包运行就是一个web服务: 还有提供了很多metric,i ...
- 整合 springboot 和 swagger出问题
整合 springboot 和 swagger ,出现报错, org.springframework.beans.factory.UnsatisfiedDependencyException: Err ...
随机推荐
- RabbitMQ系列-Exchange介绍
RabbitMQ系列 RabbitMQ系列-概念及安装 1. Exchange RabbitMQ系列-概念及安装提到AMQP 0-9-1协议默认支持四种exchange,分别是Direct Excha ...
- centos安装Vue
一直以来,有关LINUX的系统安装包,都是比较随意,直接使用yum进行或者apt-get 安装 标准安装流程是什么的呢.我们通过centos安装Vue进行展示 1 首先下载安装nodejs , htt ...
- odoo开发教程十:Actions
actions定义了系统对于用户的操作的响应:登录.按钮.选择项目等. 一:窗口action(ir.actions.act_window ) 最常用的action类型,用于将model的数据展示出来. ...
- 终于把 7 年前的 Docker Hub 账号恢复了
折腾 docker,向 Docker Hub 提交镜像的时候发现原来自己在 2014 年就已经注册过 Docker Hub 的账号了,而且在 https://hub.docker.com/u/shen ...
- Firefox Quantum 向左,Google Chrome 向右
今天,又重新安装了一下 Firefox Quantum-68.0 (64 位),不同的是这一次安装的是国际中文版,而不是北京谋智火狐的版本. 北京谋智火狐 国际中文版 总的来说,有几点体验: 在 ht ...
- tomghost
思路: 先使用端口扫描,会发现22,8009,8080 8009的考察点:tomcat ajp协程属性设置导致的文件读取和文件执行. https://github.com/00theway/Ghost ...
- WPF中控件转命令
WPF不是所有控件都有Command属性,如果窗体需要在ViewModel 使用System.Windows.Interactivity事件 在nuget浏览搜索 下载System.Windows.I ...
- 一站式数据可观测性平台 Datavines 正式开源啦
Datavines是一站式开源数据可观测性平台,提供元数据管理.数据概览报告.数据质量管理,数据分布查询.数据趋势洞察等核心能力,致力于帮助用户全面地了解和掌管数据,让您做到心中有数,目前作为 Dat ...
- javaSE 温故而知新
重温 javaSE 前言:有地基才能有高楼大厦 目录 重温 javaSE 认识java Java基础 1.数据类型 1.1 基本数据类型: 1.2 引用数据类型 1.3 基本数据类型的包装类 1.4 ...
- 如何在 Windows Server 2022 阿里云服务器上搭建自己的 MQTT 服务器。
一.简介 最近,在做一个项目的时候,需要在线管理网络继电器,以前也做过硬件的项目,但是这样的项目不多.现在我想实现一个在线可以接受网络继电器发送的信号,也可以向网络继电器发送命令,控制其的运行.这个功 ...