一、依赖
系统使用的是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.131port: 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;@Beanpublic 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 {@Autowiredprivate ElasticsearchClient elasticsearchClient;@Testvoid test(){System.out.println(elasticsearchClient);}
}
运行成功
三、索引基本语法
参考文档:Elasticsearch8.x版本中RestHighLevelClient被弃用,新版本中全新的Java客户端Elasticsearch Java API Client中常用API练习