关键词:
Java 之 ElasticSearch7.x.x + SpringBoot + 爬虫 + 项目实战【一篇文章精通系列】【SpringBoot集成ElasticSearch+项目实战】
一、ElasticSearch的Java官方文档
1、查看官方文档
https://www.elastic.co/guide/index.html
进入客户端的文档
https://www.elastic.co/guide/en/elasticsearch/client/index.html
因为我们本地安装的ES版本为
选择对应的版本即可
找到对应的版本
2、找到了原生的依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.16.3</version>
</dependency>
3、初始化
二、创建SpringBoot项目
1、创建项目
创建成功后在项目当中创建对应的模块
新建项目成功
我们可以看到已经自动引入对应的依赖
aven的目录当中我们可以看到,SpringBoot2.7.5 默认的ElasticSearch-client的版本为7.17.6
2、完善依赖
虽然这个版本可以使用但是,在切换SpringBoot的版本的时候会发生变化,所以我们需要自定义版本依赖
<!--自定义ES版本依赖,保证和本地版本一直-->
<elasticsearch.version>7.16.0</elasticsearch.version>
3、创建ElasticSearchClientConfig配置类
/*
* Spring两步骤,
* 1、找对象
* 2、放到Spring中待用
* */
@Configuration //xml - bean
public class ElasticSearchClientConfig
//spring <beans id='restHighLevelClient' class='RestHighLevelClient'>
/*
* 将创建ES链接的代码,注入到Spring的容器当中
* */
@Bean
public RestHighLevelClient restHighLevelClient()
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1", 9200, "http")
)
);
return client;
- 拓展
@Configuration注解的作用:声明一个类为配置类,用于取代bean.xml配置文件注册bean对象。
@Configuration注解最常见的搭配使用有两个:@Bean和@Scope
@Bean:等价于Spring中的bean标签用于注册bean对象的,给容器中添加组件,一般以方法名作为组件的id,配置类里面使用@Bean标注在方法上给容器注册组件,默认是单实例的。
@Scope:用于声明该bean的作用域,作用域有singleton、prototype、request、session。
singleton 单实例的(单例)(默认) ----全局有且仅有一个实例
prototype 多实例的(多例) ----每次获取Bean的时候会有一个新的实例
reqeust 同一次请求 ----request:每一次HTTP请求都会产生一个新的bean,同时该bean仅在当前HTTP request内有效
session 同一个会话级别 ---- session:每一次HTTP请求都会产生一个新的bean,同时该bean仅在当前HTTP session内有效
@Configuration注解的属性
@Configuration注解中有@Component注解的加持,因此它自己本身也是一个bean对象,可以通过Context的进行获取。
@Configuration中的属性proxyBeanMethods是及其重要的,设置true/false会得到不同的效果。
proxyBeanMethods = true的情况下,保持单实例对象
proxyBeanMethods = false的情况下,不进行检查IOC容器中是否存在,而是简单的调用方法进行创建对象,无法保持单实例,简单来说,就相当于true只调用一次(创建一次,后续重复调用),而false会调用多次(调用多少次创建多少个对象)。
- 分析源码
二、索引库API操作
1、在测试类当中注入对应的内容
在测试类当中进行测试
首先在测试类当中注入,刚刚的Spring容器当中的restHighLevelClient
这里注入有三种方式
@SpringBootTest
class ItbluxboxEsApiApplicationTests
/*
1、第一种注入方式
@Autowired
private RestHighLevelClient restHighLevelClient;//restHighLevelClient 必须和Config当中对应的属性名称相同
2、第二种注入方式
@Resource(lookup = "restHighLevelClient") //别名
private RestHighLevelClient client;
*/
/*
@Autowired(required=true):当使用@Autowired注解的时候,其实默认就是@Autowired(required=true),表示注入的时候,该bean必须存在,否则就会注入失败。
@Autowired(required=false):表示忽略当前要注入的bean,如果有直接注入,没有跳过,不会报错。
*/
/*
3、第三种注入方式
*/
@Autowired(required = false)
@Qualifier("restHighLevelClient") //指定容器当中注入的名称restHighLevelClient
private RestHighLevelClient client;//使用其他名称的时候
@Test
void contextLoads()
2、创建索引
@Test
void testCreateIndex() throws IOException
//1、创建索引请求
CreateIndexRequest request = new CreateIndexRequest("blue_index");
//2、客户端,执行请求IndicesClient CreateIndexResponse获得对应的响应
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
System.out.println(createIndexResponse);
运行测试类
运行成功
在ElasticSearch head当中我们可以看到,对应的索引库创建成功
3、获取索引(判断索引是否存在)
/*
* 测试获取索引
* */
@Test
void testExistIndex() throws IOException
GetIndexRequest request = new GetIndexRequest("blue_index");
/*exists判断当前索引是否存在*/
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);//是否存在
运行测试
4、删除索引
/*
* 测试删除索引
* */
@Test
void testDeleteIndex() throws IOException
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("blue_index");
/*删除*/
AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
运行测试
在ElasticSearch head当中没有了对应的索引库
三、文档API操作
1、创建文档
a、创建索引库,因为上面刚刚删除了对应的索引库
b、先创建实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class User
private String name;
private int age;
c、创建文档
/*测试添加文档*/
@Test
void testAddDocument() throws IOException
//创建对象
User user = new User("蓝盒子", 3);
//创建请求
IndexRequest request = new IndexRequest("blue_index");
/*
规则
put /kuang index/_doc/1
*/
request.id("1");
request.timeout(TimeValue.timeValueSeconds(1));
request.timeout("1s");
//将我们的数据放入请求 JSON
request.source(JSON.toJSONString(user), XContentType.JSON);
//客户端发送请求 , 发送请求获取响应结果
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
System.out.println(indexResponse.toString());//
System.out.println(indexResponse.status());//对应我们命令返回的状态
运行测试
创建成功
我们在head当中可以看到对应的内容
2、获取文档
/*获取文档,判断是否存在*/
@Test
void testIsExists() throws IOException
GetRequest getrequest = new GetRequest("blue_index","1");
//不获取返回的_source 的上下文
getrequest.fetchSourceContext(new FetchSourceContext(false));
getrequest.storedFields("_none_");
boolean exists = client.exists(getrequest, RequestOptions.DEFAULT);
System.out.println(exists);
运行测试
3、获取文档信息
//获取文档信息
@Test
void testGetDoucment() throws IOException
GetRequest getRequest = new GetRequest("blue_index","1");
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
System.out.println(getResponse.getSourceAsString());//打印文档的内容
System.out.println(getResponse);//返回全部的内容和命令是一样的
运行测试
4、更新文档记录
//更新文档信息
@Test
void testUpdateDoucment() throws IOException
UpdateRequest updateRequest = new UpdateRequest("blue_index","1");
updateRequest.timeout("1s");
User user = new User("蓝盒子Java", 18);
updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(updateResponse.status());
System.out.println(updateResponse);
运行测试更新成功
5、删除文档记录
//删除文档信息
@Test
void testDeleteDocument() throws IOException
DeleteRequest request = new DeleteRequest("blue_index","1");
request.timeout("1s");
DeleteResponse deleteResponse = client.delete(request, RequestOptions.DEFAULT);
System.out.println(deleteResponse.status());
System.out.println(deleteResponse);
删除成功
删除成功
6、批量插入数据
/*
批量插入代码
* */
@Test
void testBulkDocument() throws IOException
//批处理请求
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("10s");
ArrayList<User> userList = new ArrayList<>();
userList.add(new User("蓝盒子1",3));
userList.add(new User("蓝盒子2",13));
userList.add(new User("蓝盒子3",23));
userList.add(new User("蓝盒子4",5));
userList.add(new User("蓝盒子7",15));
userList.add(new User("蓝盒子8",25));
userList.add(new User("蓝盒子9",35));
//批处理请求
for (int i = 0; i < userList.size(); i++)
/*
批量删除:DeleteRequest
批量更新:UpdateRequest
*/
bulkRequest.add(new IndexRequest("blue_index")
.id(""+(i+1))
.source(JSON.toJSONString(userList.get(i)),XContentType.JSON)
);
BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulkResponse.hasFailures()); //是否失败
运行测试
如果不设置id会生成随机id
运行测试
运行成功
7、查询
package cn.itbluebox.itbluxboxesapi.utils;
public class ESconst
public static final String EX_INDEX = "blue_index";
在查询当中调用
查询的时候这里有各种构造器
搜索年龄为3岁的
@Test
void testSearch() throws IOException
SearchRequest searchRequest = new SearchRequest(ESconst.EX_INDEX);
//构建搜索条件
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//查询name为蓝盒子1的用户
//查询条件我们可以使用 QueryBuilders 工具类 来快速匹配
//QueryBuilders.termQuery 精确匹配
//QueryBuilders.matchAllQuery 匹配全部查询
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("age", "3");
sourceBuilder.query(termQueryBuilder);
/*
sourceBuilder.from();//分页开始
sourceBuilder.size();//一页的条数
*/
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(searchResponse.status());
System.out.println(JSON.toJSONString(searchResponse));
System.out.println("===========================================");
for (SearchHit documentFields : searchResponse.getHits().getHits())
System.out.println(documentFields.getSourceAsMap());
运行测试
SearchRequest 搜索请求
SearchSourceBuilder 条件构造
HighlightBuilder 构建高亮
TermQueryBuilder 构建精确查询
MatchAllQueryBuilder 构建全部查询
xxx QueryBuilder 对应我们刚才看到的所有命令
四、项目实战(创建项目搭建工程)
1、创建新项目
和之前一样选择好对应的依赖
完善好对应的依赖
<!--自定义ES版本依赖,保证和本地版本一直-->
<elasticsearch.version>7.16.0</elasticsearch.version>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
完善yml
2、引入一些静态资源
静态资源下载地址:https://download.csdn.net/download/qq_44757034/86935691
3、创建controller
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController
@GetMapping("/","/index") //访问路径为/或者/index
精通系列springboot集成elasticsearch+项目实战(代码片段)
Java之ElasticSearch7.x.x+SpringBoot+爬虫+项目实战【一篇文章精通系列】【SpringBoot集成ElasticSearch+项目实战】一、ElasticSearch的Java官方文档1、查看官方文档2、找到了原生的依赖3、初始化二、创建SpringBoot项目1、创建项目2、... 查看详情
springboot入门到精通-springboot入门(代码片段)
SpringBoot入门到精通系列SpringBoot入门到精通-Spring的注解编程(一)SpringBoot入门到精通-SpringBoot入门(二)SpringBoot入门到精通-Spring的基本使用(三)SpringBoot入门到精通-SpringBoot集成SSM(四)前言经过上面的学习,我们已经掌握的Spring的注... 查看详情
springboot入门到精通-spring的注解编程(代码片段)
SpringBoot入门到精通系列SpringBoot入门到精通-Spring的注解编程(一)SpringBoot入门到精通-SpringBoot入门(二)SpringBoot入门到精通-Spring的基本使用(三)SpringBoot入门到精通-SpringBoot集成SSM(四)前言SpringBoot并不是一个新技术了,但是我发现... 查看详情
springboot入门到精通-spring的基本使用(代码片段)
SpringBoot入门到精通系列SpringBoot入门到精通-Spring的注解编程(一)SpringBoot入门到精通-SpringBoot入门(二)SpringBoot入门到精通-Spring的基本使用(三)SpringBoot入门到精通-SpringBoot集成SSM(四)前言上一篇文章我们讲的是SpringBoot的入门程序,... 查看详情
java之springboot入门到精通idea版springboot原理分析,springboot监控(一篇文章精通系列)下(代码片段)
目录Java之SpringBoot入门到精通【IDEA版】(一篇文章精通系列)【上】Java之SpringBoot入门到精通【IDEA版】SpringBoot整合其他框架【Junit,Redis,MyBatis】(一篇文章精通系列)【中】Java之SpringBoot入门到精通【IDEA版】SpringBo... 查看详情
精通系列)(代码片段)
Java之SpringBoot+Vue+ElementUI前后端分离项目(上-项目搭建)Java之SpringBoot+Vue+ElementUI前后端分离项目(中-功能完善-实现查询)Java之SpringBoot+Vue+ElementUI前后端分离项目(下-功能完善-发布文章 查看详情
精通系列)创建springboot项目+基于ssm多模块项目案例+微服务实战(代码片段)
Gradle文章目录Java之Gradle【IDEA版】入门到精通(上)(一篇文章精通系列)【安装+基本使用+项目创建+项目部署+文件操作+依赖管理+插件使用】Java之Gradle【IDEA版】入门到精通(下)(... 查看详情
精通系列)创建springboot项目+基于ssm多模块项目案例+微服务实战(代码片段)
Gradle文章目录Java之Gradle【IDEA版】入门到精通(上)(一篇文章精通系列)【安装+基本使用+项目创建+项目部署+文件操作+依赖管理+插件使用】Java之Gradle【IDEA版】入门到精通(下)(... 查看详情
精通系列)创建springboot项目+基于ssm多模块项目案例+微服务实战(代码片段)
Gradle文章目录Java之Gradle【IDEA版】入门到精通(上)(一篇文章精通系列)【安装+基本使用+项目创建+项目部署+文件操作+依赖管理+插件使用】Java之Gradle【IDEA版】入门到精通(下)(... 查看详情
java之springboot入门到精通,springboot项目部署jar包方式,war包方式(一篇文章精通系列)(代码片段)
SpringBoot项目开发完毕后,支持两种方式部署到服务器:SpringBoot项目部署【jar包方式,war包方式】一、创建SpringBoot工程1、创建工程2、创建UserController二、jar包(官方推荐)1、打包2、运行jar包三、war包1、修改pom.xml的打包方式... 查看详情
springboot入门到精通-springboot自定义starter(代码片段)
定义自己的starterSpringBoot入门到精通-Spring的注解编程(一)SpringBoot入门到精通-SpringBoot入门(二)SpringBoot入门到精通-Spring的基本使用(三)SpringBoot入门到精通-SpringBoot集成SSM(四)SpringBoot入门到精通-SpringBoot自动配置原理(五)SpringBoot入门... 查看详情
java之springboot入门到精通idea版(一篇文章精通系列)上(代码片段)
一、SpringBoot概述SpringBoot提供了一种快速使用Spring的方式,基于约定优于配置的思想,可以让开发人员不必在配置与逻辑业务之间进行思维的切换,全身心的投入到逻辑业务的代码编写中,从而大大提高了开发的... 查看详情
java之springboot入门到精通idea版springboot整合其他框架junit,redis,mybatis(一篇文章精通系列)中(代码片段)
SpringBoot整合其他框架【Junit,Redis,MyBatis】一、SpringBoot整合Junit①搭建SpringBoot工程②引入starter-test起步依赖③编写测试类(1)在启动类傍边其他类④添加测试相关注解⑤编写测试方法二、SpringBoot整合Redis1、搭建SpringBoot工... 查看详情
springboot配置全系列
基础配置maven的profile方式springboot的profile使用方式开发模式配置配置tomcat配置web相关配置日志配置JSP配置数据源集成配置集成druid集成mybatis集成Freemarker集成redis集成dubbo集成zookeeper集成rocketmq 查看详情
springboot系列教程七:springboot集成mybatis
一.创建项目 项目名称为“springboot_mybatis_demo”,创建过程中勾选“Web”,“MyBatis”,“MySQL”,第一次创建Maven需要下载依赖包(耐心等待) 二.实现2.1创建User类1packagecom.woniu.bean;234publicclassUser{5pr... 查看详情
springboot系列之集成druid配置数据源监控
SpringBoot系列之集成Druid配置数据源监控继上一篇博客SpringBoot系列之JDBC数据访问之后,本博客再介绍数据库连接池框架Druid的使用实验环境准备:MavenIntelliJIDEA先新建一个SpringbootInitializer项目,详情参考SpringBoot系列之快速创建Initi... 查看详情
idea从零到精通(25)之springboot集成mybatis
文章目录作者简介引言导航步骤小结导航热门专栏推荐作者简介作者名:编程界明世隐简介:CSDN博客专家,从事软件开发多年,精通Java、JavaScript,博主也是从零开始一步步把学习成长、深知学习和积累的重... 查看详情
springboot从入门到精通(三十四)如何集成jwt实现token验证
...逐渐被基于Token的身份验证模式取代。接下来介绍如何在SpringBoot项目中集成JWT实现Token验证。一、JWT入门1.什么是JWTJWT(Jsonwebtoken)是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC7519)。它定义了一种紧凑的... 查看详情