SpringBoot整合elasticsearch-java
一、依赖
系统使用的是ElasticSearch8.2.0
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>8.1.0</version>
</dependency>
二、配置
1、yml文件配置
elasticsearch:
url: 192.168.58.131
port: 9200
2、config配置文件
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
@Configuration
public class RestClientConfig {
@Value("${elasticsearch.url}")
private String url;
@Value("${elasticsearch.port}")
private String port;
@Bean
public ElasticsearchClient elasticsearchClient() throws IOException {
// 创建低级客户端
RestClient restClient = RestClient.builder(
new HttpHost(url, Integer.parseInt(port))
).build();
// 使用 Jackson 映射器创建传输层
ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper()
);
// 创建 API 客户端
ElasticsearchClient client = new ElasticsearchClient(transport);
// 关闭 ES 客户端
transport.close();
restClient.close();
return client;
}
}
3、测试是否连接成功
@SpringBootTest
class ElasticSearchApplicationTests {
@Autowired
private ElasticsearchClient elasticsearchClient;
@Test
void test(){
System.out.println(elasticsearchClient);
}
}
运行成功
三、索引基本语法
参考文档:Elasticsearch8.x版本中RestHighLevelClient被弃用,新版本中全新的Java客户端Elasticsearch Java API Client中常用API练习
原文地址:https://blog.csdn.net/weixin_55127182/article/details/140591020
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!