我的es是7.18.x springboot版本为2.7.3
其他版本对应可以去查下,这里就不过多叙述
直接上步骤:
1.导入maven依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2.设置配置:
# spring配置
spring:
data:
elasticsearch:
username: your_username
password: your_password
cluster-name: cluster # 你的es集群名称
cluster-nodes: 127.0.0.1:9201,127.0.0.1:9202,127.0.0.1:9203
3.创建一个配置类 ElasticsearchConfig:
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;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import java.time.Duration;
/**
* description: 初始化ElasticsearchRestTemplate
* create by: zt
* create time: 2024/4/11 10:16
*/
@Configuration
public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {
@Value("${spring.data.elasticsearch.cluster-nodes}")
private String url;
@Value("${spring.data.elasticsearch.username}")
private String username;
@Value("${spring.data.elasticsearch.password}")
private String password;
@Override
@Bean
public RestHighLevelClient elasticsearchClient() {
url = url.replace("http://", "");
String[] urlArr = url.split(",");
HttpHost[] httpPostArr = new HttpHost[urlArr.length];
for (int i = 0; i < urlArr.length; i++) {
HttpHost httpHost = new HttpHost(urlArr[i].split(":")[0].trim(),
Integer.parseInt(urlArr[i].split(":")[1].trim()), "http");
httpPostArr[i] = httpHost;
}
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
RestClientBuilder builder = RestClient.builder(httpPostArr)
// 异步httpclient配置
.setHttpClientConfigCallback(httpClientBuilder -> {
// 账号密码登录
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
// httpclient连接数配置
httpClientBuilder.setMaxConnTotal(30);
// 每个路由值指定最大连接数
httpClientBuilder.setMaxConnPerRoute(10);
// httpclient 设置保活策略|长时间不连接es,报错超时连接 每隔五分钟发送一次请求
httpClientBuilder.setKeepAliveStrategy(((response, context) -> Duration.ofMinutes(5).toMillis()));
return httpClientBuilder;
});
return new RestHighLevelClient(builder);
}
@Bean
public ElasticsearchRestTemplate elasticsearchRestTemplate() {
return new ElasticsearchRestTemplate(elasticsearchClient());
}
4.创建一个文档映射实体:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* @Description: TODO
* @Author zt
* @Date 2024/4/11 9:55
* @Version 1.0
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "item_index")
public class TestEntity {
@Id
private Long id;
@Field(type = FieldType.Text)
private String title; //标题
@Field(type = FieldType.Keyword)
private String category;// 分类
@Field(type = FieldType.Keyword)
private String brand; // 品牌
@Field(type = FieldType.Double)
private Double price; // 价格
@Field(index = false, type = FieldType.Keyword)
private String images; // 图片地址
}
5.创建一个交互类:
import com.datian.framework.njwst.domain.TestEntity;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
/**
* @Description: TODO
* @Author zt
* @Date 2024/4/11 9:53
* @Version 1.0
*/
@Repository
public interface TestRepository extends ElasticsearchRepository<TestEntity, Long> {
}
6.开始测试使用:
import com.datian.framework.njwst.domain.TestEntity;
import com.datian.framework.njwst.repository.TestRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description: TODO
* @Author zt
* @Date 2024/4/10 17:48
* @Version 1.0
*/
@RestController
@RequestMapping("/es")
public class TestController {
@Autowired
private ElasticsearchRestTemplate mRestTemplate;
@Autowired
private TestRepository itemRepository;
@GetMapping("create")
public void createIndex() {
mRestTemplate.indexOps(TestEntity.class).create();
}
@GetMapping("insert")
public void insert() {
TestEntity item = new TestEntity(1L, "小米手机7", "手机", "小米", 2999.00, "https://img12.360buyimg.com/n1/s450x450_jfs/t1/14081/40/4987/124705/5c371b20E53786645/c1f49cd69e6c7e6a.jpg");
itemRepository.save(item);
}
}
此时itemRepository 和我们使用mybatisplus 时基本一致,已经包装了基础的操作类
对于一些简单的查询 也可以直接命名即可
例如:
@Repository
public interface TestRepository extends ElasticsearchRepository<TestEntity, Long> {
List<TestEntity> findByTitle(String title);
}
也可以执行自定义DSL语句:
例如:
@Repository
public interface TestRepository extends ElasticsearchRepository<TestEntity, Long> {
List<TestEntity> findByTitle(String title);
@Query("{\"match\": {\"brand\": \"?0\"}}")
List<TestEntity> findByBrand(String brand);
}
更多操作 可查阅官方api