elasticsearch + spring boot 配置

目录

首先引入elasticsearch依赖

操作 elasticsearch有两种方式

一、通过elasticsearch client操作elasticsearch

二、通过spring框架操作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;

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值