目录

  • springboot2.x集成es

springboot2.x集成es

首先导入我们的pom依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--引入ELasticSearch的依赖包-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency><!--转json的工具包,个人爱好,也可以用别的--><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.8.5</version></dependency>

然后我们把我们的es的信息配置到yml文件中

server:port: 80es:ip: 192.168.1.9port: 9300#连接池pool: 5#集群名字cluster:name: my-application

因为这里配置了集群节点名,所以需要在我们的config配置文件中修改我们的elasticSearch.yml配置文件

读取yml信息,根据配置文件启动es客户端的配置类

package com.xy.elasticsearch.config;import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.net.InetAddress;@Configuration
public class ElasticsearchConfig {private static final Logger LOGGER = LoggerFactory.getLogger(ElasticsearchConfig.class);/*** elk集群地址*/@Value("${es.ip}")private String ip;/*** 端口*/@Value("${es.port}")private String port;/*** 集群名称*/@Value("${es.cluster.name}")private String clusterName;/*** 连接池*/@Value("${es.pool}")private String pool;/*** Bean name default  函数名字** @return*/@Bean(name = "transportClient")public TransportClient transportClient() {TransportClient transportClient = null;try {// 配置信息Settings esSetting = Settings.builder().put("cluster.name", clusterName) //集群名字.put("client.transport.sniff", true)//增加嗅探机制,找到ES集群.put("thread_pool.search.size", Integer.parseInt(pool))//增加线程池个数,暂时设为5.build();//配置信息Settings自定义transportClient = new PreBuiltTransportClient(esSetting);TransportAddress transportAddress = new TransportAddress(InetAddress.getByName(ip), Integer.valueOf(port));transportClient.addTransportAddresses(transportAddress);} catch (Exception e) {LOGGER.error("elasticsearch TransportClient create error!!", e);}return transportClient;}
}

ElasticSearch客户端提供了多种方式的数据创建方式,包括json串,map,内置工具;我们正式开始一般用json格式,借助json工具框架,比如gson ,json-lib,fastjson等等;

然后我们简单测试一些数据,先增加一些json数据进去,然后用junit测试一下

package com.xy.elasticsearch;import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.json.JSONArray;
import org.junit.jupiter.api.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;@RunWith(SpringRunner.class)
@SpringBootTest
class ElasticsearchApplicationTests {@Autowiredprivate TransportClient client;/*** 创建索引 添加文档* @throws Exception*/@Testpublic void testIndex() {JsonArray jsonArray=new JsonArray();JsonObject jsonObject=new JsonObject();jsonObject.addProperty("title", "哪吒之魔童降世");jsonObject.addProperty("publishDate", "2019-07-26");jsonObject.addProperty("content", "天地灵气孕育出一颗能量巨大的混元珠,元始天尊将混元珠提炼成灵珠和魔丸,灵珠投胎为人,助周伐纣时可堪大用;而魔丸则会诞出魔王,为祸人间。元始天尊启动了天劫咒语,3年后天雷将会降临,摧毁魔丸。太乙受命将灵珠托生于陈塘关李靖家的儿子哪吒身上。然而阴差阳错,灵珠和魔丸竟然被掉包。本应是灵珠英雄的哪吒却成了混世大魔王。调皮捣蛋顽劣不堪的哪吒却徒有一颗做英雄的心。然而面对众人对魔丸的误解和即将来临的天雷的降临,哪吒是否命中注定会立地成魔?他将何去何从?");jsonObject.addProperty("director", "饺子");jsonObject.addProperty("price", "35");jsonArray.add(jsonObject);JsonObject jsonObject2=new JsonObject();jsonObject2.addProperty("title", "寄生虫");jsonObject2.addProperty("publishDate", "2019-10-11");jsonObject2.addProperty("content", "《寄生虫》讲述一家四口全是无业游民的爸爸基泽(宋康昊饰)成天游手好闲,直到积极向上的长子基宇(崔宇植饰)靠着伪造的文凭来到富豪朴社长(李善均饰)的家应征家教,两个天差地远的家庭因而被卷入一连串意外事件中");jsonObject2.addProperty("director", "奉俊昊");jsonObject2.addProperty("price", "45");jsonArray.add(jsonObject2);JsonObject jsonObject3=new JsonObject();jsonObject3.addProperty("title", "送我上青云");jsonObject3.addProperty("publishDate", "2019-08-16");jsonObject3.addProperty("content", "《女记者盛男(姚晨饰),心高气傲,个性刚硬,渴望真爱仍孑然一身,怀抱理想却屡屡在现实中碰壁。盛男意外地患上了卵巢癌,为了筹得手术费,她不得不接受一份自己不喜欢的工作,为一位企业家的父亲写自传,也因此踏上一段寻求爱欲亦是寻找自我的旅程。");jsonObject3.addProperty("director", "滕丛丛");jsonObject3.addProperty("price", "55");jsonArray.add(jsonObject3);JsonObject jsonObject4=new JsonObject();jsonObject4.addProperty("title", "复仇者联盟4");jsonObject4.addProperty("publishDate", "2019-04-14");jsonObject4.addProperty("content", "来自泰坦星的灭霸(乔什·布洛林饰)为了解决宇宙资源匮乏、人口暴增的问题,集齐6颗无限宝石,一个响指让全宇宙生命公平随机的减半。宇宙由于疯狂的泰坦灭霸的行动而变得满目疮痍,在泰坦星与灭霸决战失败的钢铁侠(小罗伯特·唐尼饰)孤身一人漂流宇宙,迷失在量子领域的蚁人(保罗·路德饰)意外回到现实世界,他的出现为幸存的复仇者们点燃了希望。无论前方将遭遇怎样的后果,幸存的超级英雄们都必须在剩余盟友的帮助下再一次集结,以逆转灭霸的所作所为,彻底恢复宇宙的秩序。");jsonObject4.addProperty("director", "乔·罗素安东尼·罗素");jsonObject4.addProperty("price", "35");jsonArray.add(jsonObject4);JsonObject jsonObject5=new JsonObject();jsonObject5.addProperty("title", "蜘蛛侠:英雄远征");jsonObject5.addProperty("publishDate", "2019-06-28");jsonObject5.addProperty("content", "在复仇者联盟众英雄的努力下,于灭霸无限手套事件中化作为灰烬的人们,重新回到了人世间,曾经消失的蜘蛛侠 彼得帕克 也回归到了普通的生活之中,数月后,蜘蛛侠彼得帕克所在的学校举行了欧洲旅游,帕克也在其中, 在欧州威尼斯旅行时,一个巨大无比的水怪袭击了威尼斯,不敌敌人的蜘蛛侠幸得一位自称神秘客的男子搭救才击退敌人,之后 神盾局局长找上正在旅游的彼得帕克并要求其加入神盾局,并安排神秘客协助帕克,神秘客自称来自其他宇宙,并告知一群名为元素众的邪恶势力已经入侵这个宇宙了,为了守护来之不易的和平,蜘蛛侠决定与神秘客联手,然而在神秘客那头罩之中,似乎隐藏着什么不为人知的真相……");jsonObject5.addProperty("director", "乔·沃茨");jsonObject5.addProperty("price", "38");jsonArray.add(jsonObject5);JsonObject jsonObject6=new JsonObject();jsonObject6.addProperty("title", "罗小黑战记");jsonObject6.addProperty("publishDate", "2019-09-07");jsonObject6.addProperty("content", "在熙攘的人类世界里,很多妖精隐匿其中,他们与人类相安无事地生活着。猫妖罗小黑因为家园被破坏,开始了它的流浪之旅。这场旅途中惺惺相惜的妖精同类与和谐包容的人类伙伴相继出现,让小黑陷入了两难抉择,究竟何处才是真正的归属 [3]  ?");jsonObject6.addProperty("director", "MTJJ");jsonObject6.addProperty("price", "38");jsonArray.add(jsonObject6);for(int i=0;i<jsonArray.size();i++){JsonObject jo=jsonArray.get(i).getAsJsonObject();IndexResponse response=client.prepareIndex("film", "new").setSource(jo.toString(), XContentType.JSON).get();System.out.println("索引名称:"+response.getIndex());System.out.println("类型:"+response.getType());System.out.println("文档ID:"+response.getId());System.out.println("当前实例状态:"+response.status());}}/*** 查询所有* @throws Exception*/@Testpublic void searchAll()throws Exception{SearchRequestBuilder srb=client.prepareSearch("film").setTypes("new");SearchResponse sr=srb.setQuery(QueryBuilders.matchAllQuery()).execute().actionGet(); // 查询所有SearchHits hits=sr.getHits();for(SearchHit hit:hits){System.out.println(hit.getSourceAsString());}}
}

然后我们可以在header插件中看到我们刚刚插入的数据

然后运行我们的查询方法,也能查询到我们的数据

后面我会专门整理一篇博客来记录es的其他常用操作

end…

Springboot2.x集成ElasticSearch相关推荐

  1. Springboot2.0 集成 Elasticsearch 6.x 未添加 transport-netty4-client 依赖 启动时报错

    报错内容关键部分: Failed to instantiate [org.elasticsearch.client.transport.TransportClient]: Factory method ...

  2. 【SpringBoot高级篇】SpringBoot集成Elasticsearch搜索引擎

    [SpringBoot高级篇]SpringBoot集成Elasticsearch搜索引擎 1. 什么是Elasticsearch? 2. 安装并运行Elasticsearch 2.1 拉取镜像 2.2 ...

  3. SpringBoot笔记:SpringBoot2.3集成SpringSession+nginx+redis实现session共享

    文章目录 Spring Session介绍 Redis集成 yml配置 依赖添加 redis存值查看 登录服务器查看redis的值 查询所有"spring:session:"开头的 ...

  4. SpringBoot学习历程(十一):SpringBoot2.X集成mail发送邮件

    SpringBoot学习历程(十一):SpringBoot2.X集成mail发送邮件 前言 1. 引入依赖 2. 设置邮件配置信息 3. 发送邮件 3.1 发送普通文本邮件 3.2 发送HTML格式内 ...

  5. 第 4-8 课:Spring Boot 集成 ElasticSearch

    ElasticSearch 是⼀个开源的搜索引擎,建⽴在⼀个全⽂搜索引擎库 Apache Lucene™ 基础之上. Lucene 可以说是当下最先进.⾼性能.全功能的搜索引擎库--⽆论是开源还是私有 ...

  6. Java集成ElasticSearch及配置类工具类整理

    Java集成ElasticSearch及配置类工具类整理 前言:做一个有梦想的程序猿! ES不同的版本API差异比较大,此处ES版本为:6.5.3 代码如下: 添加Maven依赖 <!-- ES ...

  7. SpringBoot2.x 集成 七牛云对象存储Kodo

    本文主要对SpringBoot2.x集成七牛云对象存储Kodo进行简单总结,其中SpringBoot使用的2.4.5版本. 一.七牛云对象存储Kodo简介 七牛云对象存储Kodo是七牛云提供的高可靠. ...

  8. SpringBoot2.x 集成 FreeMarker

    本文主要对SpringBoot2.x集成FreeMarker及其常用语法进行简单总结,其中SpringBoot使用的2.4.5版本. 一.FreeMarker简介 Apache FreeMarker™ ...

  9. spring boot集成Elasticsearch客户端

    spring boot整合Elasticsearch客户端 在spring boot程序应用中集成Elasticsearch客户端,并通过配置对连接进行管理. Elasticsearch的客户端Jav ...

最新文章

  1. 他们创造了编程语言,他们是这个时代伟大的父亲
  2. 了解的四大关键性概念
  3. static_cast与c风格的强制类型转换比较
  4. Oracle根据已有表的数据建立新表
  5. Celery--分布式任务队列
  6. Algorithm:C++语言实现之链表相关算法(链表相加、链表的部分翻转、链表划分、链表去重、重复元素全部删除)
  7. 【黑科技】在alv中设置字体样式
  8. python中的作用域以及内置函数globals()-全局变量、locals()-局部变量
  9. 智能胖墩机器人_探班新雅CDIE | 智能硬件“奇幻乐园”
  10. 代码也浪漫:用Python放一场烟花秀!
  11. css 滤镜之AlphaImageLoader
  12. 数据结构之图:加权有向图与dijkstra算法找到最短路径,Python——28
  13. git代码托管 · 操作举例: “git bash here ”(全程操作讲解) - git命令篇
  14. UC神马数据采集api
  15. 暑假集训-8.05总结
  16. Scratch(四十三):赛龙舟
  17. iOS 在CollectionView上做展开收起动画
  18. wedo2.0编程模块介绍_wedo2.0课程包
  19. 第3章 Kafka API
  20. win7系统中安装破解版Charles教程 基本使用方法汇总

热门文章

  1. 数字信号处理翻转课堂笔记1
  2. 集成学习多样性度量总结
  3. Java ArrayList的遍历
  4. 爬取可搜索百度图片并下载到本地——以远洋椿萱茂词条为例
  5. layui open传参_layer.open传值
  6. Apache 软件基金会欢庆20周年:由社区驱动发展的“Apache 之道”
  7. python怎么修改默认路径_修改默认python
  8. ue4使用houdini制作体积云 houdini游戏工具(一)
  9. 百度网盘 yundetectservice.exe可以禁用关闭吗
  10. python爬虫未来发展趋势_什么是Python爬虫?有什么应用空间?-未来数据科技关于礼的诗句...