SpringBoot整合ElasticSearch

文档

网上的es教程大都十分老旧,而且es的版本众多,个别版本的差异还较大,另外es本身提供多种api,导 致许多文章各种乱七八糟实例!所以后面直接放弃,从官网寻找方案,这里我使用elasticsearch最新的 7.6.1版本来讲解:

1、进入es的官网指导文档
https://www.elastic.co/guide/index.html

2、找到 Elasticsearch Clients(这个就是客户端api文档)

SpringBoot整合ElasticSearch

3、我们使用java rest风格api,大家可以更加自己的版本选择特定的other versions

SpringBoot整合ElasticSearch

4、rest又分为high level和low level,我们直接选择high level下面的 Getting started

SpringBoot整合ElasticSearch

5、向下阅读找到Maven依赖和基本配置!

SpringBoot整合ElasticSearch

Java REST Client 说明

Java REST Client 有两种风格:

Java Low Level REST Client :用于Elasticsearch的官方低级客户端。它允许通过http与Elasticsearch 集群通信。将请求编排和响应反编排留给用户自己处理。它兼容所有的Elasticsearch版本。(PS:学过 WebService的话,对编排与反编排这个概念应该不陌生。可以理解为对请求参数的封装,以及对响应结 果的解析)

Java High Level REST Client :用于Elasticsearch的官方高级客户端。它是基于低级客户端的,它提供 很多API,并负责请求的编排与响应的反编排。(PS:就好比是,一个是传自己拼接好的字符串,并且 自己解析返回的结果;而另一个是传对象,返回的结果也已经封装好了,直接是对象,更加规范了参数 的名称以及格式,更加面对对象一点)

(PS:所谓低级与高级,我觉得一个很形象的比喻是,面向过程编程与面向对象编程)

网上很多教程比较老旧,都是使用TransportClient操作的,在 Elasticsearch 7.0 中不建议使用 TransportClient,并且在8.0中会完全删除TransportClient。因此,官方更建议我们用Java High Level REST Client,它执行HTTP请求,而不是序列号的Java请求。既然如此,这里我们就直接用高级了。

配置基本项目依赖

1、新建一个springboot(2.2.5版)项目 kuang-elasticsearch ,导入web依赖即可!

2、配置es的依赖

<properties>
<java.version>1.8</java.version>
<!-- 这里SpringBoot默认配置的版本不匹配,我们需要自己配置版本! -->
<elasticsearch.version>7.6.1</elasticsearch.version>
</properties>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

3、继续阅读文档到Initialization ,我们看到需要构建RestHighLevelClient对象;

RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http"))); // 构建客户端对象
// 操作....
// 高级客户端内部会创建低级客户端用于基于提供的builder执行请求。低级客户端维护一个连接池,
并启动一些线程,因此当你用完以后应该关闭高级客户端,并且在内部它将会关闭低级客户端,以释放这
些资源。关闭客户端可以使用close()方法:
client.close(); // 关闭

4、我们编写一个配置类,提供这个bean来进行操作

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;
@Configuration
public class ElasticsearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1", 9200, "http")));
return client;
}
}

5、常用方法工具类封装

import com.alibaba.fastjson.JSON;
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.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Component
public class EsUtils<T> {
@Autowired
@Qualifier("restHighLevelClient")
private RestHighLevelClient client;
/**
* 判断索引是否存在
* @param index
* @return
* @throws IOException
*/
public boolean existsIndex(String index) throws IOException {
GetIndexRequest request = new GetIndexRequest(index);
boolean exists = client.indices().exists(request,
RequestOptions.DEFAULT);
return exists;
}
/**
* 创建索引
* @param index
* @throws IOException
*/
public boolean createIndex(String index) throws IOException {
CreateIndexRequest request = new CreateIndexRequest(index);
CreateIndexResponse createIndexResponse
=client.indices().create(request,RequestOptions.DEFAULT);
return createIndexResponse.isAcknowledged();
}
/**
* 删除索引
* @param index
* @return
* @throws IOException
*/
public boolean deleteIndex(String index) throws IOException {
DeleteIndexRequest deleteIndexRequest = new
DeleteIndexRequest(index);
AcknowledgedResponse response =
client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
return response.isAcknowledged();
}
/**
* 判断某索引下文档id是否存在
* @param index
* @param id
* @return
* @throws IOException
*/
public boolean docExists(String index, String id) throws IOException {
GetRequest getRequest = new GetRequest(index,id);
//只判断索引是否存在不需要获取_source
getRequest.fetchSourceContext(new FetchSourceContext(false));
getRequest.storedFields("_none_");
boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
return exists;
}
/**
* 添加文档记录
* @param index
* @param id
* @param t 要添加的数据实体类
* @return
* @throws IOException
*/
public boolean addDoc(String index,String id,T t) throws IOException {
IndexRequest request = new IndexRequest(index);
request.id(id);
//timeout
request.timeout(TimeValue.timeValueSeconds(1));
request.timeout("1s");
  request.source(JSON.toJSONString(t), XContentType.JSON);
IndexResponse indexResponse = client.index(request,
RequestOptions.DEFAULT);
RestStatus Status = indexResponse.status();
return Status==RestStatus.OK||Status== RestStatus.CREATED;
}
/**
* 根据id来获取记录
* @param index
* @param id
* @return
* @throws IOException
*/
public GetResponse getDoc(String index, String id) throws IOException {
GetRequest request = new GetRequest(index,id);
GetResponse getResponse = client.get(request,
RequestOptions.DEFAULT);
return getResponse;
}
/**
* 批量添加文档记录
* 没有设置id ES会自动生成一个,如果要设置 IndexRequest的对象.id()即可
* @param index
* @param list
* @return
* @throws IOException
*/
public boolean bulkAdd(String index, List<T> list) throws IOException {
BulkRequest bulkRequest = new BulkRequest();
//timeout
bulkRequest.timeout(TimeValue.timeValueMinutes(2));
bulkRequest.timeout("2m");
for (int i =0;i<list.size();i++){
bulkRequest.add(new IndexRequest(index)
.source(JSON.toJSONString(list.get(i))));
}
BulkResponse bulkResponse = client.bulk(bulkRequest,
RequestOptions.DEFAULT);
return !bulkResponse.hasFailures();
}
/**
* 批量删除和更新就不写了可根据上面几个方法来写
*/
/**
* 更新文档记录
* @param index
* @param id
* @param t
* @return
* @throws IOException
*/

public boolean updateDoc(String index,String id,T t) throws IOException
{
UpdateRequest request = new UpdateRequest(index,id);
request.doc(JSON.toJSONString(t));
request.timeout(TimeValue.timeValueSeconds(1));
request.timeout("1s");
UpdateResponse updateResponse = client.update(
request, RequestOptions.DEFAULT);
return updateResponse.status()==RestStatus.OK;
}
/**
* 删除文档记录
* @param index
* @param id
* @return
* @throws IOException
*/
public boolean deleteDoc(String index,String id) throws IOException {
DeleteRequest request = new DeleteRequest(index,id);
//timeout
request.timeout(TimeValue.timeValueSeconds(1));
request.timeout("1s");
DeleteResponse deleteResponse = client.delete(
request, RequestOptions.DEFAULT);
return deleteResponse.status()== RestStatus.OK;
}
/**
* 根据某字段来搜索
* @param index
* @param field
* @param key 要收搜的关键字
* @throws IOException
*/
public void search(String index,String field ,String key,Integer
from,Integer size) throws IOException {
SearchRequest searchRequest = new SearchRequest(index);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.termQuery(field, key));
//控制搜素
sourceBuilder.from(from);
sourceBuilder.size(size);
//最大搜索时间。
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest,
RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(searchResponse.getHits()));
}
}

APIs 测试

测试创建索引:

@Test
void testCreateIndex() throws IOException {
CreateIndexRequest request = new CreateIndexRequest("kuang_index");
CreateIndexResponse createIndexResponse
=restHighLevelClient.indices().create(request,RequestOptions.DEFAULT);
System.out.println(createIndexResponse);
}

测试获取索引:

@Test
void testExistsIndex() throws IOException {
GetIndexRequest request = new GetIndexRequest("kuang_index");
boolean exists = restHighLevelClient.indices().exists(request,
RequestOptions.DEFAULT);
System.out.println(exists);
}

测试删除索引:

@Test
void testDeleteIndexRequest() throws IOException {
DeleteIndexRequest deleteIndexRequest = new
DeleteIndexRequest("kuang_index");
AcknowledgedResponse response
= restHighLevelClient.indices().delete(deleteIndexRequest,
RequestOptions.DEFAULT);
System.out.println(response.isAcknowledged());
}

测试添加文档记录: 创建一个实体类User

@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class User {
private String name;
private int age;
}

测试添加文档记录

@Test
void testAddDocument() throws IOException {
// 创建对象
User user = new User("狂神说", 3);
// 创建请求
IndexRequest request = new IndexRequest("kuang_index");
// 规则
request.id("1");
  request.timeout(TimeValue.timeValueSeconds(1));
request.timeout("1s");
request.source(JSON.toJSONString(user), XContentType.JSON);
// 发送请求
IndexResponse indexResponse = restHighLevelClient.index(request,
RequestOptions.DEFAULT);
System.out.println(indexResponse.toString());
RestStatus Status = indexResponse.status();
System.out.println(Status == RestStatus.OK || Status ==
RestStatus.CREATED);
}

测试:判断某索引下文档id是否存在

// 判断此id是否存在这个索引库中
@Test
void testIsExists() throws IOException {
GetRequest getRequest = new GetRequest("kuang_index","1");
// 不获取_source上下文 storedFields
getRequest.fetchSourceContext(new FetchSourceContext(false));
getRequest.storedFields("_none_");
// 判断此id是否存在!
boolean exists = restHighLevelClient.exists(getRequest,
RequestOptions.DEFAULT);
System.out.println(exists);
}

测试:根据id获取记录

// 获得文档记录
@Test
void testGetDocument() throws IOException {
GetRequest getRequest = new GetRequest("kuang_index","3");
GetResponse getResponse = restHighLevelClient.get(getRequest,
RequestOptions.DEFAULT);
System.out.println(getResponse.getSourceAsString()); // 打印文档内容
System.out.println(getResponse);
}

测试:更新文档记录

// 更新文档记录
@Test
void testUpdateDocument() throws IOException {
UpdateRequest request = new UpdateRequest("kuang_index","1");
request.timeout(TimeValue.timeValueSeconds(1));
request.timeout("1s");
User user = new User("狂神说", 18);
request.doc(JSON.toJSONString(user), XContentType.JSON);
UpdateResponse updateResponse = restHighLevelClient.update(
request, RequestOptions.DEFAULT);
System.out.println(updateResponse.status() == RestStatus.OK);
}

测试:删除文档记录

// 删除文档测试
@Test
void testDelete() throws IOException {
DeleteRequest request = new DeleteRequest("kuang_index","3");
//timeout
request.timeout(TimeValue.timeValueSeconds(1));
request.timeout("1s");
DeleteResponse deleteResponse = restHighLevelClient.delete(
request, RequestOptions.DEFAULT);
System.out.println(deleteResponse.status() == RestStatus.OK);
}

测试:批量添加文档

// 批量添加数据
@Test
void testBulkRequest() throws IOException {
BulkRequest bulkRequest = new BulkRequest();
//timeout
bulkRequest.timeout(TimeValue.timeValueMinutes(2));
bulkRequest.timeout("2m");
ArrayList<User> userList = new ArrayList<>();
userList.add(new User("xiaohan1",3));
userList.add(new User("xiaohan12",3));
userList.add(new User("xiaohan13",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))
.source(JSON.toJSONString(userList.get(i)),XContentType.JSON));
}
// bulk
BulkResponse bulkResponse =
restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);
System.out.println(!bulkResponse.hasFailures());
}

查询测试:

// 查询测试
/**
* 使用QueryBuilder
* termQuery("key", obj) 完全匹配
* termsQuery("key", obj1, obj2..) 一次匹配多个值
* matchQuery("key", Obj) 单个匹配, field不支持通配符, 前缀具高级特性
* multiMatchQuery("text", "field1", "field2"..); 匹配多个字段, field有通
配符忒行
* matchAllQuery(); 匹配所有文件
*/
@Test
void testSearch() throws IOException {
SearchRequest searchRequest = new SearchRequest("kuang_index");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name",
"qinjiang1");
MatchAllQueryBuilder matchAllQueryBuilder =
QueryBuilders.matchAllQuery();
sourceBuilder.query(matchAllQueryBuilder);
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
searchRequest.source(sourceBuilder);
SearchResponse response = restHighLevelClient.search(searchRequest,
RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(response.getHits()));
System.out.println("================SearchHit==================");
for (SearchHit documentFields : response.getHits().getHits()) {
System.out.println(documentFields.getSourceAsMap());
}
}

内容出处:,

声明:本网站所收集的部分公开资料来源于互联网,转载的目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。如果您发现网站上有侵犯您的知识产权的作品,请与我们取得联系,我们会及时修改或删除。文章链接:http://www.yixao.com/tech/27868.html

发表评论

登录后才能评论