在《Elasticsearch8.4.2在windows系统下的安装介绍》中介绍了如何安装ES,那么安装成功后改如何将数据写入到ES呢?写入ES数据的方式有很多,本次将介绍一种写入方式elasticsearch-java来写入数据到ES,elasticsearch-java是官方提供的java sdk写入方式,用户只需要配置相关参数就可以方便写入数据,源码地址:https://github.com/elastic/elasticsearch-java
前期需要引入相关的jar包到项目中,如下所示:
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>8.4.2</version>
<exclusions>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore-nio</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.15</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore-nio</artifactId>
<version>4.4.15</version>
<exclusions>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</exclusion>
</exclusions>
</dependency>
编写如下代码
// Create the low-level client
String host = "localhost";
int port = 9200;
//tag::create-secure-client-fingerprint
String fingerprint = "指纹信息";
SSLContext sslContext = TransportUtils.sslContextFromCaFingerprint(fingerprint);
BasicCredentialsProvider credsProv = new BasicCredentialsProvider(); // <2>
credsProv.setCredentials(
AuthScope.ANY, new UsernamePasswordCredentials(ES用户名, ES密码)
);
RestClient restClient = RestClient
.builder(new HttpHost(host, port, "https")) // <3>
.setHttpClientConfigCallback(hc -> hc
.setSSLContext(sslContext) // <4>
.setDefaultCredentialsProvider(credsProv)
)
.build();
// Create the transport and the API client
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
try {
String tradeMsg = "{\"a\":\"b\"}";
IndexRequest<JsonData> request = IndexRequest.of(i -> i
.index("索引名称")
.document(JsonData.fromJson(tradeMsg))
);
client.index(request);
} catch (IOException e) {
e.printStackTrace();
}
其中有几个地方必须先准备好,用户名&密码、指纹信息和索引名称。
用户名&密码
在安装ES时默认会生成ES的用户名和密码,将它copy出来填写到代码的对应的位置上,安装过程可以参考之前的介绍
指纹信息
在安装ES时默认会生成指纹信息,将它copy出来填写到代码的对应的位置上,安装过程可以参考之前的介绍,本次是默认安装ES,没有做过任何的其它变更,那么需要通过以HTTPS的方式去连接ES服务端,其它方式可能连接不上。代码中演示的方式是通过指纹信息获取SSL上下文信息,然后以HTTPS的方式访问ES服务端。
索引名称
相当于定义数据库表名,代码中需要定义一个索引的名称,告诉系统需要将数据写入到哪里,也可以通过Kibana的开发者工具预先创建好索引并定义好各个字段的类型。文章来源:https://www.toymoban.com/news/detail-670676.html
具体elasticsearch-java的使用方式,官方也有文档介绍:Basic authentication | Elasticsearch Java API Client [8.4] | Elastic文章来源地址https://www.toymoban.com/news/detail-670676.html
到了这里,关于Elasticsearch写入数据之elasticsearch-java的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!