方式一:SpringBoot 2.7.1 集成 ElasticSearch 7.4.0 的方式一 Spring-data-elasticsearch_全栈编程网的博客-CSDN博客SpringBoot 2.7.1 集成 ElasticSearch 7.4.0 的方式一 Spring-data-elasticsearchhttps://blog.csdn.net/ruanhao1203/article/details/125768175
目录
1. 安装 ElasticSearch
2. 概述
3. 项目代码
3.1 引入依赖
3.2 application.yml 配置
3.3 索引hello_es 对应实体类
3.4 RestHighLevelClient 客户端
3.5 创建CRUD的类
3.6 测试Controller
4. 启动SpringBoot,测试CRUD
4.1 创建ES索引hello_es和mapping
4.2 CRUD调用相关接口测试即可
Windows Docker 安装 ElasticSearch_全栈编程网的博客-CSDN博客
上一篇写了 spring-data-elasticsearch方式开发,这种方式CRUD方法都写好了,开发起来比较方便。
据说官方更推荐用 RestHighLevelClient 方式,不知真假,这种方式个人觉得确实灵活点,不过开发起来不是很方便。
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-data-elasticsearch
org.projectlombok
lombok
1.16.10
com.alibaba
fastjson
1.2.70
spring:
application:
name: demo
# elasticsearch:
# uris: localhost:9200
server:
port: 8081
# 另一个方式连接es
elasticsearch:
host: localhost
port: 9200
username:
password:
schema: http
connectTimeOut: 10000
socketTimeOut: 30000
connectionRequestTimeOut: 5000
maxConnectNum: 2000
maxConnectPerRoute: 2000
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class HelloEsEntity {
private Long id;
private String name;
private String content;
private Integer age;
private Date createDate;
}
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 自定义连接ES,区别于spring-data-elasticsearch方式,
* 1.spring-data-elasticsearch方式:框架封装好了对ES操作的CRUD方法,很方便,但是部分功能可能实现起来比较麻烦。
* 2.自定义这种:是自己实现CRUD功能,更麻烦,但是更灵活。
*/
@Configuration
public class ElasticSearchConfiguration {
/**
* ES地址,多个用逗号隔开
*/
@Value("${elasticsearch.host}")
private List host;
/**
* ES端口
*/
@Value("${elasticsearch.port}")
private List port;
/**
* 使用协议 http/https
*/
@Value("${elasticsearch.schema}")
private String schema;
/**
* ES用户名
*/
@Value("${elasticsearch.username}")
private String username;
/**
* ES密码
*/
@Value("${elasticsearch.password}")
private String password;
/**
* 连接超时时间
*/
@Value("${elasticsearch.connectTimeOut}")
private int connectTimeOut;
/**
* 连接超时时间
*/
@Value("${elasticsearch.socketTimeOut}")
private int socketTimeOut;
/**
* 获取连接的超时时间
*/
@Value("${elasticsearch.connectionRequestTimeOut}")
private int connectionRequestTimeOut;
/**
* 最大连接数
*/
@Value("${elasticsearch.maxConnectNum}")
private int maxConnectNum;
/**
* 最大路由连接数
*/
@Value("${elasticsearch.maxConnectPerRoute}")
private int maxConnectPerRoute;
@Bean
public RestHighLevelClient restHighLevelClient(){
ArrayList hostList = new ArrayList<>(host.size());
for (int i = 0; i < host.size(); i++) {
hostList.add(new HttpHost(host.get(i), Integer.valueOf(port.get(i)), schema));
}
RestClientBuilder client = RestClient.builder(hostList.toArray(new HttpHost[0]));
// 异步httpclient连接延时配置
client.setRequestConfigCallback(requestConfigBuilder -> {
requestConfigBuilder.setConnectTimeout(connectTimeOut);
requestConfigBuilder.setSocketTimeout(socketTimeOut);
requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);
return requestConfigBuilder;
});
// 异步httpclient连接数配置
client.setHttpClientConfigCallback(httpClientBuilder -> {
httpClientBuilder.setMaxConnTotal(maxConnectNum);
httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);
//是否添加鉴权
if (null != username && !"".equals(username) ) {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
return httpClientBuilder;
});
return new RestHighLevelClient(client);
}
}
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkItemResponse;
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.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.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.es.entity.HelloEsEntity;
/**
* RestHighLevelClient 方式连接 ElasticSearch,CRUD工具类
*/
@Component
public class ElasticSearchUtil {
private final String index = "hello_es";
@Autowired
private RestHighLevelClient client;
/**
* 判断索引是否存在
*
* @param index 索引名称
* @return boolean
*/
public boolean existsIndex(String index) throws IOException {
GetIndexRequest request = new GetIndexRequest(index);
return client.indices().exists(request, RequestOptions.DEFAULT);
}
/**
* 删除
*
* @param index 索引名称
* @return boolean
*/
public boolean deleteIndex(String index) throws IOException {
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
return delete.isAcknowledged();
}
/**
* 创建 hello_es 索引
*
* @return boolean
*/
public boolean createIndex() throws IOException {
CreateIndexRequest createIndexRequest = new CreateIndexRequest(index);
// setting中会设置主分区,拷贝分区,刷新时间
createIndexRequest.settings(Settings.builder().put("index.number_of_shards", "1")
.put("index.number_of_replicas", "1"));
//设置映射
Map mapping = new HashMap<>();
Map properties = new HashMap<>();
Map id = new HashMap<>();
id.put("type", "long");
properties.put("id", id);
Map name = new HashMap<>();
name.put("type", "keyword");
properties.put("name", name);
Map content = new HashMap<>();
content.put("type", "text");
content.put("analyzer", "ik_max_word");
properties.put("content", content);
Map age = new HashMap<>();
age.put("type", "integer");
properties.put("age", age);
Map createDate = new HashMap<>();
createDate.put("type", "date");
createDate.put("format", "yyyy‐MM‐dd HH:mm:ss||yyyy‐MM‐dd");
properties.put("createDate", createDate);
mapping.put("properties", properties);
createIndexRequest.mapping(JSON.toJSONString(mapping), XContentType.JSON);
CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
return createIndexResponse.isAcknowledged();
}
/**
* 新增记录
* @param esEntity
* @return
* @throws IOException
*/
public boolean save(HelloEsEntity esEntity) throws IOException {
if (esEntity.getId() == null) {
esEntity.setId(new Random().nextLong());
}
JSONObject jsonMap = JSON.parseObject(JSON.toJSONString(esEntity));
// 日期类型转换
SimpleDateFormat dateFormat =new SimpleDateFormat("yyyy‐MM‐dd HH:mm:ss");
jsonMap.put("createDate", dateFormat.format(new Date()));
//索引请求对象
IndexRequest indexRequest = new IndexRequest(index);
indexRequest.id(esEntity.getId().toString());
//指定索引文档内容
indexRequest.source(jsonMap.toJSONString(), XContentType.JSON);
//索引响应对象
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
DocWriteResponse.Result result = indexResponse.getResult();
if(result.compareTo(DocWriteResponse.Result.CREATED) == 0) {
return true;
}
return false;
}
/**
* 批量新增
* @param list
* @return
* @throws IOException
*/
public boolean bukltSave(List list) throws IOException {
BulkRequest bulkRequest = new BulkRequest(index);
for (HelloEsEntity esEntity : list) {
if (esEntity.getId() == null) {
esEntity.setId(new Random().nextLong());
}
JSONObject jsonMap = JSON.parseObject(JSON.toJSONString(esEntity));
// 日期类型转换
SimpleDateFormat dateFormat =new SimpleDateFormat("yyyy‐MM‐dd HH:mm:ss");
jsonMap.put("createDate", dateFormat.format(new Date()));
//索引请求对象
IndexRequest indexRequest = new IndexRequest();
indexRequest.id(String.valueOf(esEntity.getId()));
//指定索引文档内容
indexRequest.source(JSON.toJSONString(jsonMap), XContentType.JSON);
bulkRequest.add(indexRequest);
}
BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
BulkItemResponse[] items = bulk.getItems();
for (BulkItemResponse item : items) {
DocWriteResponse.Result result = item.getResponse().getResult();
if (result.compareTo(DocWriteResponse.Result.CREATED) == 0) {
return true;
}
}
return false;
}
/**
* 删除
* @param id
* @return
* @throws IOException
*/
public boolean delete(String id) throws IOException {
DeleteRequest deleteRequest = new DeleteRequest(index);
deleteRequest.id(id);
DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
DocWriteResponse.Result result = deleteResponse.getResult();
if (result.compareTo(DocWriteResponse.Result.DELETED) == 0) {
return true;
}
return false;
}
/**
* 根据id查询
* @param id
* @return
* @throws IOException
* @throws ParseException
*/
public HelloEsEntity queryById(String id) throws IOException, ParseException {
GetRequest getRequest = new GetRequest(index);
getRequest.id(id);
GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);
boolean exists = documentFields.isExists();
if (!exists) {
return null;
}
Map source = documentFields.getSource();
// 日期类型转换
if (source.containsKey("createDate")) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy‐MM‐dd HH:mm:ss");
source.put("createDate", dateFormat.parse(source.get("createDate").toString()));
}
HelloEsEntity helloEsEntity = JSON.toJavaObject(JSON.parseObject(JSON.toJSONString(source)), HelloEsEntity.class);
return helloEsEntity;
}
/**
* 更新
* @param helloEsEntity
* @return
* @throws IOException
* @throws ParseException
*/
public boolean update(HelloEsEntity helloEsEntity) throws IOException, ParseException {
Long id = helloEsEntity.getId();
HelloEsEntity map = queryById(id.toString());
if (map == null) {
return false;
}
JSONObject jsonMap = JSON.parseObject(JSON.toJSONString(helloEsEntity));
// 日期类型转换
SimpleDateFormat dateFormat =new SimpleDateFormat("yyyy‐MM‐dd HH:mm:ss");
jsonMap.put("createDate", dateFormat.format(new Date()));
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index(index);
updateRequest.id(id.toString());
updateRequest.doc(jsonMap.toJSONString(), XContentType.JSON);
UpdateResponse response = client.update(updateRequest, RequestOptions.DEFAULT);
DocWriteResponse.Result result = response.getResult();
if (result.compareTo(DocWriteResponse.Result.UPDATED) == 0) {
return true;
}
return false;
}
}
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSON;
import com.example.es.entity.HelloEsEntity;
import com.example.es.util.ElasticSearchUtil;
@RestController
@RequestMapping("es/util")
public class ElasticSearchUtilController {
@Autowired
private ElasticSearchUtil elasticSearchUtil;
/**
* 创建索引
* @return
*/
@GetMapping("/existsIndex")
public String existsIndex(@RequestParam(name = "index") String index) throws IOException {
boolean b = elasticSearchUtil.existsIndex(index);
return String.valueOf(b);
}
/**
* 删除索引
* @return
*/
@GetMapping("/deleteIndex")
public String deleteIndex(@RequestParam(name = "index") String index) throws IOException {
boolean b = elasticSearchUtil.deleteIndex(index);
return String.valueOf(b);
}
/**
* 创建索引 hello
* @return
*/
@GetMapping("/createIndex")
public String createIndex() throws IOException {
boolean b = elasticSearchUtil.createIndex();
return String.valueOf(b);
}
/**
* 创建索引 hello
* @return
*/
@GetMapping("/save")
public String save(@RequestBody HelloEsEntity entity) throws IOException {
boolean b = elasticSearchUtil.save(entity);
return String.valueOf(b);
}
/**
* 批量插入 hello
* @return
*/
@GetMapping("/bukltSave")
public String bukltSave(@RequestBody List list) throws IOException {
boolean b = elasticSearchUtil.bukltSave(list);
return String.valueOf(b);
}
/**
* 删除
* @return
*/
@GetMapping("/delete")
public String delete(@RequestParam(name = "id") String id) throws IOException {
boolean b = elasticSearchUtil.delete(id);
return String.valueOf(b);
}
/**
* 查询
* @return
*/
@GetMapping("/queryById")
public String queryById(@RequestParam(name = "id") String id) throws IOException, ParseException {
HelloEsEntity b = elasticSearchUtil.queryById(id);
return JSON.toJSONString(b);
}
/**
* 查询
* @return
*/
@GetMapping("/update")
public String update(@RequestBody HelloEsEntity helloEsEntity) throws IOException, ParseException {
boolean b = elasticSearchUtil.update(helloEsEntity);
return String.valueOf(b);
}
}
调用相关接口测试功能。
调用接口:localhost:8081/es/util/createIndex
创建成功:访问localhost:9200/hello_es ,查看创建的索引信息
{
"hello_es":{
"aliases":{
},
"mappings":{
"properties":{
"age":{
"type":"integer"
},
"content":{
"type":"text",
"analyzer":"ik_max_word"
},
"createDate":{
"type":"date",
"format":"yyyy‐MM‐dd HH:mm:ss||yyyy‐MM‐dd"
},
"id":{
"type":"long"
},
"name":{
"type":"keyword"
}
}
},
"settings":{
"index":{
"creation_date":"1657874038695",
"number_of_shards":"1",
"number_of_replicas":"1",
"uuid":"w-dbNu_eRSe3WTgUxsYczg",
"version":{
"created":"7040099"
},
"provided_name":"hello_es"
}
}
}
}
总结:以上只是简单操作,复杂的查询没有列出,后期文章补充。