这里首先简单的介绍了Elasticsearch,然后实现了springboot集成Elasticsearch。
版本:
Elasticsearch:v8.5.1
Kibana:v8.5.1
springboot集成elasticsearch有两种方式。
1)rest客户端RestHingLevelClient;
2)接口ElasticSearchRepository。
这里采用第1种方式。
1 Elasticsearch简介
ElasticSearch是一个基于Apache Lucene的开源搜索引擎。
Kibana 是一个开源分析和可视化平台,旨在可视化操作 Elasticsearch。
也就是说:
ElasticSearch 只是后台程序,没有界面;
Kibana是ElasticSearch对应的前端。
主要术语:
- 索引(Index)
索引是具有某种相似特征的文档的集合。例如,客户数据索引,产品目录索引,以及订单数据索引。 - 文档(document)
文档是可以被索引的基本单位。文档使用JSON表示。
2 springboot 集成Elasticsearch
Elasticsearch已支持Index(索引)、Document(文档)、Graph(图)、Machine learning(机器学习)等。
这里介绍了Index(索引)、Document(文档)的简单使用。
第1步:pom中引入依赖的包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<version>3.0.2</version>
</dependency>
第2步:application.properties设置相关参数:
server.port =8081
spring.data.elasticsearch.repositories.enabled = true
spring.data.elasticsearch.cluster-nodes = localhost:9300
spring.elasticsearch.rest.username=elastic
spring.elasticsearch.rest.password=123456
spring.elasticsearch.rest.uris=localhost:9200
第3步:对应的配置类ElasticSearchConfig.java:
@Component
@Configuration
public class ElasticSearchConfig extends AbstractElasticsearchConfiguration {
@Value("${spring.elasticsearch.rest.uris}")
private String uris ;
@Value("${spring.elasticsearch.rest.username}")
private String username;
@Value("${spring.elasticsearch.rest.password}")
private String password ;
@Override
@Bean(destroyMethod = "close")
public RestHighLevelClient elasticsearchClient() {
final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo(uris)
.withBasicAuth(username, password)
.build();
return RestClients.create(clientConfiguration).rest();
}
}
第4步:实现index的工具类IndexUtil.java:
@Component
public class IndexUtil {
@Autowired
private RestHighLevelClient restHighLevelClient;
/**
* 创建索引index
* @param index
* @return
* @throws IOException
*/
public boolean createIndex(String index){
if (!isIndexExist(index)) {
return false;
}
boolean isAcknowledged = false;
CreateIndexRequest createIndexRequest = new CreateIndexRequest(index);
try {
AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
isAcknowledged = acknowledgedResponse.isAcknowledged();
} catch (IOException e) {
e.printStackTrace();
} finally {
return isAcknowledged;
}
}
/**
* 删除索引
* @param index
* @return
* @throws IOException
*/
public boolean deleteIndex(String index){
if (!isIndexExist(index)) {
return false;
}
boolean isAcknowledged = false;
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
try {
AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indices().delete(deleteIndexRequest,RequestOptions.DEFAULT);
isAcknowledged = acknowledgedResponse.isAcknowledged();
} catch (IOException e) {
e.printStackTrace();
} finally {
return isAcknowledged;
}
}
/**
* 判断索引是否存在
* @param index
* @return
* @throws IOException
*/
public boolean isIndexExist(String index) {
boolean isExist = false;
try {
GetIndexRequest getIndexRequest = new GetIndexRequest(index);
isExist = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
} finally {
return isExist;
}
}
}
第5步:实现document的工具类DocumentUtil.java:
@Component
public class DocumentUtil {
@Autowired
private RestHighLevelClient restHighLevelClient;
/**
* 添加document
* @param object
* @param index
* @param id
* @return
*/
public void addDocument(Object object, String index,String id){
//1 create IndexRequest
IndexRequest indexRequest = new IndexRequest(index);
indexRequest.id(id);
indexRequest.timeout(TimeValue.timeValueSeconds(1));
String content = JSON.toJSONString(object);
indexRequest.source(content, XContentType.JSON);
try {
//2 send IndexRequest
IndexResponse indexResponse =restHighLevelClient.index(indexRequest,RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 添加document,随机id
* @param object
* @param index
* @return
*/
public void addDocument(Object object, String index){
String id= "";
id = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
addDocument(object, index, id);
}
/**
* get Document
* @param index
* @param id
* @return
*/
public GetResponse getDocumnet(String index,String id){
GetResponse getResponse = null;
GetRequest getRequest = new GetRequest(index, id);
try {
getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
}catch (IOException e){
e.printStackTrace();
} finally {
return getResponse;
}
}
/**
* update document
* @param object
* @param index
* @param id
*/
public void updateDocument(Object object, String index,String id){
//1 create UpdateRequest
UpdateRequest updateRequest = new UpdateRequest(index,id);
updateRequest.timeout(TimeValue.timeValueSeconds(1));
String content = JSON.toJSONString(object);
updateRequest.doc(content, XContentType.JSON);
try {
//2 send UpdateRequest
UpdateResponse updateResponse =restHighLevelClient.update(updateRequest,RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 删除Document
* @param index
* @param id
*/
public void deleteDocument(String index,String id){
//1 create DeleteRequest
DeleteRequest deleteRequest = new DeleteRequest(index, id);
try {
//2 send DeleteRequest
DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest,RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
}
public SearchResponse search(String index, TermQueryBuilder termQueryBuilder){
//1 create SearchRequest
SearchRequest searchRequest = new SearchRequest(index);
//2 create SearchSourceBuilder
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(termQueryBuilder);
searchSourceBuilder.timeout(TimeValue.timeValueSeconds(60));
//3 查询条件放入SearchRequest
searchRequest.source(searchSourceBuilder);
//4 send SearchRequest
SearchResponse searchResponse = null;
try {
searchResponse = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
} finally {
return searchResponse;
}
}
public SearchResponse searchHighLight(String index, TermQueryBuilder termQueryBuilder){
//1 create SearchRequest
SearchRequest searchRequest = new SearchRequest(index);
//2 create SearchSourceBuilder
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.highlighter();
searchSourceBuilder.query(termQueryBuilder);
searchSourceBuilder.timeout(TimeValue.timeValueSeconds(60));
//3 查询条件放入SearchRequest
searchRequest.source(searchSourceBuilder);
//4 send SearchRequest
SearchResponse searchResponse = null;
try {
searchResponse = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
} finally {
return searchResponse;
}
}
}
3 测试验证
前提:安装运行ElasticSearch和Kibana。
第1步:创建index,postman发送请求:
然后,Kibana中输入:
GET /_cat/indices?v
查询到index创建成功。
第2步:创建Document,postman发送请求:
然后,Kibana中输入:
GET heroic/_doc/1
查询到Document创建成功。
第3步:查询Document,postman发送请求:
第4步:修改Document,将name“关羽”改为“刘备”;
postman发送请求:
然后,Kibana中输入:
GET heroic/_doc/1
查询到Document修改成功。
第5步:删除Document,postman发送请求:
然后,Kibana中输入:
GET heroic/_doc/1
查询到Document删除成功。
代码详见:
https://gitee.com/linghufeixia/springboot-simple
chapter9-1
教程列表:
springboot simple(0) springboot简介
springboot simple(1) springboot Helloworld
springboot simple(2) springboot Starter
springboot simple(3 )springboot Web开发
springboot simple(4)springboot 数据持久化
springboot simple (5) springboot Nosql
springboot simple (6) springboot mqtt
springboot simple (7) springboot thrift
springboot simple (8) springboot kafka
springboot simple (9) springboot jpa(Hibernate)
springboot simple (10) springboot protobuf
springboot simple (11) springboot protostuff
springboot simple (12) springboot RabbitMQ
springboot simple (13) springboot Elasticsearch