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. RT-Thread线程构建

    RT-Thread 操作系统的启动过程如下 main()函数作为其中的一个线程在运行. 如果想新建一个线程,和main()线程并行运行,步骤如下:   第一步:线程初始化函数申明 static voi ...

  2. CKS 考试题整理 (12)-Trivy扫描镜像安全漏洞

    Task 使用Trivy开源容器扫描器检测namespace kamino中 Pod 使用的具有严重漏洞的镜像. 查找具有High或Critical严重性漏洞的镜像,并删除使用这些镜像的Pod. 注意 ...

  3. Mac pt-online-schema-change 图文并茂、不锁表在线修改 MySQL 表结构、添加表索引、添加表字段、修改表字段、删除表字段

    导读 percona-toolkit 源自 Maatkit 和 Aspersa 工具,这两个工具是管理 MySQL 的最有名的工具,但 Maatkit 已经不维护了,全部归并到 percona-too ...

  4. 调用内部或私有方法的N种方法

    非公开的类型或者方法被"隐藏"在程序集内部,本就不希望从外部访问,但是有时候调用一个内部或者私有方法可能是唯一的"救命稻草",这篇文章列出了几种具体的实现方式. ...

  5. 【Java】工具类 -- 持续更新

    Java原生工具类 Objects requireNotNull():为空抛异常,不为空返回本身 deepEquals():对象深度相等(数组层面)判断 调用Arrays.deepEquals0() ...

  6. ObjectInputStream_报错问题

    报错: Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: CE ...

  7. Prometheus-4:服务自动发现Service Discovery

    自动发现 Prometheus的服务发现的几种类型: 基于文件的服务发现: 基于DNS的服务发现: 基于API的服务发现:Kubernetes.Consul.Azure...... Prometheu ...

  8. Django+DRF+Vue 网页开发环境安装(windows/Linux)

    博客地址:https://www.cnblogs.com/zylyehuo/ 总览 一.安装 Django pip install django==3.2 二.安装 MySQL 驱动程序 pip in ...

  9. [Spring+SpringMVC+Mybatis]框架学习笔记(五):SpringAOP_顾问

    上一章:[Spring+SpringMVC+Mybatis]框架学习笔记(四):Spring实现AOP 下一章:[Spring+SpringMVC+Mybatis]框架学习笔记(六):Spring_A ...

  10. VueJS使用addEventListener的事件如何触发执行函数的this

    1.使用浏览器监听切屏为例 此处为考虑浏览器兼容性推荐使用:document.addEventListener 1.1.正常函数使用如下: let n = 0; let max = 3; // 切屏最 ...