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案例的更多相关文章

  1. elasticSearch 7.6.1 入门及elasticSearch整合springboot

    一.ElasticSearch概述 官网:https://www.elastic.co/cn/downloads/elasticsearch Elaticsearch,简称为es,es是一个开源的高扩 ...

  2. 【SpringBoot】搜索框架ElasticSearch介绍和整合SpringBoot

    ========================12章 搜索框架ElasticSearch介绍和整合SpringBoot ============================= 加入小D课堂技术交 ...

  3. SpringBoot整合Mybatis案例

    SpringBoot整合Mybatis案例 2019/7/15以实习生身份入职公司前端做Angular ,但是感觉前途迷茫,于是乎学习一下Java的框架——SpringBooot. 参照大神博客:ht ...

  4. SpringBoot整合Swagger2案例,以及报错:java.lang.NumberFormatException: For input string: ""原因和解决办法

    原文链接:https://blog.csdn.net/weixin_43724369/article/details/89341949 SpringBoot整合Swagger2案例 先说SpringB ...

  5. 史上最全SpringBoot整合Mybatis案例

    摘要:如果小编说,SpringBoot是目前为止最好的框架,应该没有人会反驳吧?它的出现使得我们很容易就能搭建一个新应用.那么,SpringBoot与其他第三方框架的整合必定是我们需要关注的重点. 开 ...

  6. 初识elasticsearch_2(查询和整合springboot)

    初始化 首先将官网所下载的json文件,放入到es中,采用如下命令: curl -H "Content-Type: application/json" -XPOST 'localh ...

  7. ElasticSearch业务逻辑案例

    ElasticSearch业务逻辑案例 一.业务难题 我们有一个索引: myindex/mytype(为了方便,我们下文以a/b表示) 索引类型中的一个字段group之前是a.b.c(历史遗留问题), ...

  8. 基于Centos 7.4 搭建ELK整合SpringBoot日志收集

    基于Centos 7.4搭建es7.12.0+logstash-7.12.0+kibana-7.12.0(ELK)整合SpringBoot日志收集 注:Skywalking和logstash可共用一个 ...

  9. 整合springboot(app后台框架搭建四)

    springboot可以说是为了适用SOA服务出现,一方面,极大的简便了配置,加速了开发速度:第二方面,也是一个嵌入式的web服务,通过jar包运行就是一个web服务: 还有提供了很多metric,i ...

  10. 整合 springboot 和 swagger出问题

    整合 springboot 和 swagger ,出现报错, org.springframework.beans.factory.UnsatisfiedDependencyException: Err ...

随机推荐

  1. python 环境下使用PIP 报错的解决方法

    最近做一个小程序项目,使用djangorestframework,安装restframework 出现错误,安装环境Python2.7:出现错误如下:  "UnicodeEncodeErro ...

  2. Spring Boot 通用对象列表比较和去重

    1.前言   在Excel批量导入数据时,常常需要与数据库中已存在数据的比较,并且需要考虑导入数据重复的可能性.   导入的行数据,一般有一个实体类(对象)与之对应,往往这个实体类在数据库中的字段要比 ...

  3. GO通道:无缓冲通道与缓冲通道

    转载请注明出处: 1.通道定义 在多个协程之间进行通信和管理,可以使用 Go 语言提供的通道(Channel)类型.通道是一种特殊的数据结构,可以在协程之间进行传递数据,从而实现协程之间的通信和同步. ...

  4. Kubernetes(k8s)访问控制:身份认证

    目录 一.系统环境 二.前言 三.Kubernetes访问控制 四.身份认证简介 五.身份认证 5.1 配置客户端机器 5.2 使用base auth的方式进行认证 5.3 使用token的方式进行认 ...

  5. 使用python发送sip协议的OPTIONS

    环境:Windows10_x64  Python版本 :3.9.2   sip协议提供了OPTIONS请求方法可用于探测对端状态,今天记录下Windows10环境下使用python3.9简单实现sip ...

  6. React后台管理系统(TypeScript、Redux状态管理)环境搭建01

      搭建环境的时候,我们必须要先确保环境有node环境和npm环境,如下使用cmd命令 确保自己有了这两个环境之后我们就可以开始搭建项目,首先找一个文件夹,这个文件夹用来初始化当前环境,例如,我这里选 ...

  7. uniapp学习(二)

    easycom自动导入自定义组件 目录下 components / MyItem /MyItem.vue <template> <view> <view class=&q ...

  8. adb如何做Android ui自动化(这一篇就够了)

    一.简介 我们都知道在做Android ui自动化的时候用的是appium,环境搭建贼难受.如果我们在工作中遇到需要实现简单的自动化功能,可以直接使用adb来完成,无需去搭建繁琐的appium.ADB ...

  9. 2023年ccpc河南省程序设计竞赛-clk

    很荣幸能够参加这次比赛,比赛机会挺难得得,还是第一次线下参加这样的大型比赛,比赛体验自然无话可说比较刺激..这次比赛我和队友crf和nhr共同解决了三道题,参与感极差,可以说问题很大,最简单的签到题我 ...

  10. Redis设计

    目录 过期键删除策略 持久化 RDB AOF AOF重写 主从复制 完整重同步和部分重同步 哨兵Sentinel 哨兵对redis服务器集群的监听 执行者选举 故障转移 选择新的主服务器流程 过期键删 ...