第131天学习打卡(ElastiSearch 集成SpringBoot)
Posted doudoutj
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第131天学习打卡(ElastiSearch 集成SpringBoot)相关的知识,希望对你有一定的参考价值。
集成SpringBoot
查找官方文档
1.找到原生的依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.12.1</version>
</dependency>
2.找对象
3.分析这个类中的方法即可!
配置基本的项目
创建一个空项目
因为建立的是空项目,所以要配置环境
一定要保证我们的导入的依赖和我们的es版本一致
源码中提供对象!
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-K6xz4dIG-1621430912513)(C:\\Users\\HP\\AppData\\Roaming\\Typora\\typora-user-images\\image-20210519160050681.png)]
虽然这里导入了3个类,静态内部类,核心类只有一个
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package org.springframework.boot.autoconfigure.data.elasticsearch;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.WriteRequest.RefreshPolicy;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.reactive.ReactiveElasticsearchClient;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ReactiveElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
import org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;
import org.springframework.web.reactive.function.client.WebClient;
abstract class ElasticsearchDataConfiguration {
ElasticsearchDataConfiguration() {
}
@Configuration(
proxyBeanMethods = false
)
@ConditionalOnClass({WebClient.class, ReactiveElasticsearchOperations.class})
static class ReactiveRestClientConfiguration {
ReactiveRestClientConfiguration() {
}
@Bean
@ConditionalOnMissingBean(
value = {ReactiveElasticsearchOperations.class},
name = {"reactiveElasticsearchTemplate"}
)
@ConditionalOnBean({ReactiveElasticsearchClient.class})
ReactiveElasticsearchTemplate reactiveElasticsearchTemplate(ReactiveElasticsearchClient client, ElasticsearchConverter converter) {
ReactiveElasticsearchTemplate template = new ReactiveElasticsearchTemplate(client, converter);
template.setIndicesOptions(IndicesOptions.strictExpandOpenAndForbidClosed());
template.setRefreshPolicy(RefreshPolicy.IMMEDIATE);
return template;
}
}
@Configuration(
proxyBeanMethods = false
)
//RestHighLevelClient 高级客户端
@ConditionalOnClass({RestHighLevelClient.class})
static class RestClientConfiguration {
RestClientConfiguration() {
}
@Bean
@ConditionalOnMissingBean(
value = {ElasticsearchOperations.class},
name = {"elasticsearchTemplate"}
)
@ConditionalOnBean({RestHighLevelClient.class})
ElasticsearchRestTemplate elasticsearchTemplate(RestHighLevelClient client, ElasticsearchConverter converter) {
return new ElasticsearchRestTemplate(client, converter);
}
}
@Configuration(
proxyBeanMethods = false
)
static class BaseConfiguration {
BaseConfiguration() {
}
@Bean
@ConditionalOnMissingBean
ElasticsearchConverter elasticsearchConverter(SimpleElasticsearchMappingContext mappingContext) {
return new MappingElasticsearchConverter(mappingContext);
}
@Bean
@ConditionalOnMissingBean
SimpleElasticsearchMappingContext mappingContext() {
return new SimpleElasticsearchMappingContext();
}
}
}
具体的API测试
连接java后不需要kibana
config ElasticSearchClientConfig .java
package com.kuang.config;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//spring的两步骤
//1.找对象
//2.放到spring中待用
//3.如果是springboot 就先分析源码
@Configuration //相当于xml文件 r
public class ElasticSearchClientConfig {
// spring <beans id = restHighLevelClient class = RestHighLevelClient>
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1", 9200, "http")));
return client;
}
}
**pojo User.java **
package com.kuang.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component //注入到spring中
public class User {
private String name;
private int age;
}
1.创建索引
2.判断索引是否存在
3.删除索引
4.创建文档
5.crud文档
在pom.xml中引入依赖:
<!-- 引入fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
package com.kuang;
import com.alibaba.fastjson.JSON;
import com.kuang.pojo.User;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
@SpringBootTest
class KuangshenEsApiApplicationTests {
//面向对象来操作
@Autowired //按照类型匹配
@Qualifier("restHighLevelClient")
private RestHighLevelClient client;
//测试索引的创建 request
@Test
void testCreateIndex() throws IOException {
//1.创建索引请求
CreateIndexRequest request = new CreateIndexRequest("kuang_index");
//2客户端执行请求 IndicesClient,请求后获得响应
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
System.out.println(createIndexResponse);
}
//测试获取索引,只能判断其是否存在
@Test
void testExistIndex() throws IOException {
GetIndexRequest request = new GetIndexRequest("kuang_index");
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
//测试删除索引
@Test
void testDeleteIndex() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest("kuang_index");
//删除
AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
}
//测试添加文档
@Test
void testAddDocument() throws IOException {
//创建对象
User user = new User("狂神说", 3);
IndexRequest request = new IndexRequest("kuang_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()); //对应我们命令返回的状态 CREATED
}
//获取文档 判断是否存在 get /index/doc/1
@Test
void testIsExists() throws IOException {
GetRequest getRequest = new GetRequest("kuang_index", "1");
//不获取返回的_source的上下文
//es查询返回的json结果是"hits"下的_source _source是你查出来的json字符串的一个Key
getRequest.fetchSourceContext(new FetchSourceContext(false));
getRequest.storedFields("_none_");
boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
System.out.println(exists);
}
//获得文档的信息
@Test
void testGetDocument() throws IOException {
GetRequest getRequest = new GetRequest("kuang_index", "1");
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
System.out.println(getResponse.getSourceAsString());
System.out.println(getResponse);//返回的全部内容和命令是一样的
}
//更新文档信息
@Test
void testUpdateRequest() throws IOException {
UpdateRequest updateRequest = new UpdateRequest("kuang_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());
}
//删除文档记录
@Test
void testDeleteRequest() throws IOException {
DeleteRequest request = new DeleteRequest("kuang_index", "1");
request.timeout("1s");
DeleteResponse deleteResponse = client.delete(request, RequestOptions.DEFAULT);
System.out.println(deleteResponse.status());
}
//特殊的 真实的项目一般都会批量插入数据
@Test
void testBulkRequest() throws IOException {
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("10s");
ArrayList<User> userList = new ArrayList<>();
userList.add(new User("kuangshen1", 3));
userList.add(new User("kuangshen2", 3));
userList.add(new User("kuangshen3", 3));
userList.add(new User("qinjiang1", 3));
userList.add(new User("qinjiang2", 3));
userList.add(new User("qinjiang3", 3));
//批处理请求
for (int i = 0; i < userList.size(); i++) {
//批量更新和批量删除,就在这里修改对应的请求即可
bulkRequest.add(
new IndexRequest("kuang_index")
.id("" + (i + 1))//如果这里不用id 执行的时候就会生成随机id
.source(JSON.toJSONString(userList.get(i)), XContentType.JSON));
}
BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulkResponse.hasFailures());//是否失败 返回false就表示没有失败
}<以上是关于第131天学习打卡(ElastiSearch 集成SpringBoot)的主要内容,如果未能解决你的问题,请参考以下文章