在《Elasticsearch8.4.2在windows系統(tǒng)下的安裝介紹》中介紹了如何安裝ES,那么安裝成功后改如何將數(shù)據(jù)寫入到ES呢?寫入ES數(shù)據(jù)的方式有很多,本次將介紹一種寫入方式elasticsearch-java來寫入數(shù)據(jù)到ES,elasticsearch-java是官方提供的java sdk寫入方式,用戶只需要配置相關(guān)參數(shù)就可以方便寫入數(shù)據(jù),源碼地址:https://github.com/elastic/elasticsearch-java
前期需要引入相關(guān)的jar包到項(xiàng)目中,如下所示:
<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();
}
其中有幾個(gè)地方必須先準(zhǔn)備好,用戶名&密碼、指紋信息和索引名稱。
用戶名&密碼
在安裝ES時(shí)默認(rèn)會(huì)生成ES的用戶名和密碼,將它c(diǎn)opy出來填寫到代碼的對(duì)應(yīng)的位置上,安裝過程可以參考之前的介紹
指紋信息
在安裝ES時(shí)默認(rèn)會(huì)生成指紋信息,將它c(diǎn)opy出來填寫到代碼的對(duì)應(yīng)的位置上,安裝過程可以參考之前的介紹,本次是默認(rèn)安裝ES,沒有做過任何的其它變更,那么需要通過以HTTPS的方式去連接ES服務(wù)端,其它方式可能連接不上。代碼中演示的方式是通過指紋信息獲取SSL上下文信息,然后以HTTPS的方式訪問ES服務(wù)端。
索引名稱
相當(dāng)于定義數(shù)據(jù)庫(kù)表名,代碼中需要定義一個(gè)索引的名稱,告訴系統(tǒng)需要將數(shù)據(jù)寫入到哪里,也可以通過Kibana的開發(fā)者工具預(yù)先創(chuàng)建好索引并定義好各個(gè)字段的類型。文章來源:http://www.zghlxwxcb.cn/news/detail-670676.html
具體elasticsearch-java的使用方式,官方也有文檔介紹:Basic authentication | Elasticsearch Java API Client [8.4] | Elastic文章來源地址http://www.zghlxwxcb.cn/news/detail-670676.html
到了這里,關(guān)于Elasticsearch寫入數(shù)據(jù)之elasticsearch-java的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!