目录
一、通过elasticsearch client操作elasticsearch
首先引入elasticsearch依赖
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.6.2</version>
</dependency>
操作 elasticsearch有两种方式
一、通过elasticsearch client操作elasticsearch
<!-- rest高级客户端依赖 -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.6.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>transport-netty4-client</artifactId>
<version>7.6.2</version>
</dependency>
这种方式使用起来比较复杂,需要对API比较了解。适合需要定制化的需求。如果是简单的增删除改查,还是用第二种方式用spring框架二次封装,以ORM的方式对数据进行操作可能更习惯使用。
//定义client链接
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http")));
// 然后用client进行增删改查
二、通过spring框架操作elasticsearch
引入依赖
<!--
与elasticsearch版本有对应关系
且会自动引入依赖elasticsearch-rest-high-level-client、transport-netty4-client
-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>4.0.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<!--<version>默认同spring-boot-starterr的版本</version>-->
</dependency>
application.yml配置
#elasticsearch服务器连接配置
spring:
data:
elasticsearch:
cluster-name: elasticsearch
cluster-nodes: localhost:9300
配置好之后通过继承org.springframework.data.elasticsearch.repository.ElasticsearchRepository或使用ElasticsearchRestTemplate操作elasticsearch。
@Component
public interface IndexRepository extends ElasticsearchRepository<Index, Long> {
}
或
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;