初始化客戶端
引入相關(guān)依賴
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>8.10.2</version>
</dependency>
初始化客戶端
為了方便演示,我關(guān)閉了elasticsearch的安全驗(yàn)證,帶安全驗(yàn)證的初始化方式將在最后專門介紹
String serverUrl="http://127.0.0.1:9200";
RestClient restClient=RestClient
.builder(HttpHost
.create(serverUrl))
.build();
ElasticsearchTransport transport=new RestClientTransport(restClient,new JacksonJsonpMapper());
ElasticsearchClient esClient=new ElasticsearchClient(transport);
索引
創(chuàng)建索引
void createIndex(){
String mappings = "{\n" +
" \"properties\" : {\n" +
" \"id\" : {\n" +
" \"type\" : \"keyword\" \n" +
" },\n"+
" \"name\" : {\n" +
" \"type\" : \"text\",\n" +
" \"fields\" : {\n" +
" \"keyword\" : {\n" +
" \"type\" : \"keyword\",\n" +
" \"ignore_above\" : 256 \n" +
" }\n" +
" } \n" +
" }, \n" +
" \"price\" : { \n" +
" \"type\" : \"long\" \n" +
" } \n" +
" }\n" +
"}\n";
JsonpMapper mapper=esClient._transport().jsonpMapper();
JsonParser parser= Json.createParser(new StringReader(mappings));
CreateIndexRequest createIndexRequest=new CreateIndexRequest.Builder().index("test")
.mappings(TypeMapping._DESERIALIZER.deserialize(parser,mapper)).build();
try {
esClient.indices().create(createIndexRequest);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
刪除索引
void deleteMapping(){
try {
DeleteIndexResponse response;
response= esClient.indices().delete(deleteIndexRequest->deleteIndexRequest.index("test"));
System.out.println(response.toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
判斷索引是否存在
void existsIndex(){
try {
BooleanResponse hotel = esClient.indices().exists(existsIndexRequest -> existsIndexRequest.index("hotel"));
System.out.println(hotel.value());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
文檔
新增文檔
void insertDoc(){
Hotel hotel=hotelService.getById(61083L);
HotelDoc hotelDoc=new HotelDoc(hotel);
IndexRequest<HotelDoc> request=new IndexRequest.Builder<HotelDoc>()
.id("11")
.index("hotel")
.document(hotelDoc)
.build();
try {
IndexResponse index = esClient.index(request);
System.out.println(index.id());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
其中,HotelDoc是一個(gè)實(shí)體類
刪除文檔
void deleteDoc(){
try {
esClient.delete(deleteRequest->deleteRequest.index("hotel").id("11"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
查詢文檔
void searchDoc(){
TermQuery termQuery= QueryBuilders.term()
.field("_id")
.value("11")
.build();
SearchRequest request=new SearchRequest.Builder()
.index("hotel")
.query(termQuery._toQuery()).build();
try {
SearchResponse<HotelDoc> response=esClient.search(request,HotelDoc.class);
//輸出結(jié)果
for(Hit<HotelDoc> hit:response.hits().hits()){
System.out.println(hit.source());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
更新文檔
void updateDoc(){
HotelDoc hotelDoc=new HotelDoc();
//需要更新哪個(gè)字段就賦值哪個(gè)字段
hotelDoc.setCity("xx");
try {
esClient.update(updateRequest->updateRequest
.index("hotel")
.id("11")
.doc(hotelDoc)
,HotelDoc.class);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
批量導(dǎo)入文檔
void insertMany(){
List<Hotel> hotels=hotelService.list();
List<HotelDoc> hotelDocs=hotels.stream().map(HotelDoc::new).collect(Collectors.toList());
BulkRequest.Builder bl=new BulkRequest.Builder();
for(HotelDoc hotelDoc:hotelDocs){
bl.operations(op->op.index(
idx->idx.index("hotel")
.id(hotelDoc.getId().toString())
.document(hotelDoc)
));
}
try {
esClient.bulk(bl.refresh(Refresh.WaitFor).build());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
連接Https集群
帶安全驗(yàn)證的連接有點(diǎn)復(fù)雜,將下列代碼中CA證書的位置改為實(shí)際所在的位置就行了。
通過(guò)用戶名密碼連接
password為elastic的密碼,可以在我的另一篇文章中查看密碼的重置方式
Docker安裝部署[8.x]版本Elasticsearch+Kibana+IK分詞器文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-848112.html
void makeConnection_https() throws CertificateException, IOException,
NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
// 創(chuàng)建憑據(jù)提供器
final CredentialsProvider credentialsProvider =
new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("elastic", password));
// 設(shè)置CA證書路徑
Path caCertificatePath = Paths.get("E:\\tools\\elasticsearch-8.10.2\\config\\certs\\http_ca.crt");
// 創(chuàng)建證書工廠
CertificateFactory factory =
CertificateFactory.getInstance("X.509");
Certificate trustedCa;
try (InputStream is = Files.newInputStream(caCertificatePath)) {
// 從輸入流中生成證書
trustedCa = factory.generateCertificate(is);
}
// 創(chuàng)建密鑰庫(kù)
KeyStore trustStore = KeyStore.getInstance("pkcs12");
trustStore.load(null, null);
trustStore.setCertificateEntry("ca", trustedCa);
// 創(chuàng)建SSL上下文構(gòu)建器
SSLContextBuilder sslContextBuilder = SSLContexts.custom()
.loadTrustMaterial(trustStore, null);
final SSLContext sslContext = sslContextBuilder.build();
// 構(gòu)建Rest客戶端構(gòu)建器
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200, "https"))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(
HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder.setSSLContext(sslContext)
.setDefaultCredentialsProvider(credentialsProvider);
}
});
// 構(gòu)建Rest客戶端
RestClient restClient = builder.build();
// 創(chuàng)建Rest客戶端傳輸
ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());
esClient = new ElasticsearchClient(transport);
// asyncClient = new ElasticsearchAsyncClient(transport);
}
通過(guò)ApiKey連接
ApiKey在Kibana的Security下生成文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-848112.html
void makeConnection_token() throws CertificateException, IOException,
NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
// 定義CA證書路徑
Path caCertificatePath = Paths.get("E:\\tools\\elasticsearch-8.10.2\\config\\certs\\http_ca.crt");
// 創(chuàng)建X.509證書工廠
CertificateFactory factory =
CertificateFactory.getInstance("X.509");
Certificate trustedCa;
try (InputStream is = Files.newInputStream(caCertificatePath)) {
// 從輸入流中生成X.509證書
trustedCa = factory.generateCertificate(is);
}
// 創(chuàng)建PKCS12密鑰庫(kù)
KeyStore trustStore = KeyStore.getInstance("pkcs12");
trustStore.load(null, null);
// 將CA證書添加到密鑰庫(kù)
trustStore.setCertificateEntry("ca", trustedCa);
// 創(chuàng)建SSL上下文構(gòu)建器,并設(shè)置信任材料
SSLContextBuilder sslContextBuilder = SSLContexts.custom()
.loadTrustMaterial(trustStore, null);
final SSLContext sslContext = sslContextBuilder.build();
// 創(chuàng)建Rest客戶端構(gòu)建器
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200, "https"))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(
HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder.setSSLContext(sslContext);
}
});
// 設(shè)置默認(rèn)請(qǐng)求頭
Header[] defaultHeaders =
new Header[]{new BasicHeader("Authorization",
"ApiKey yourApiKey")};
builder.setDefaultHeaders(defaultHeaders);
// 構(gòu)建Rest客戶端
RestClient restClient = builder.build();
// 創(chuàng)建基于RestClient的傳輸方式
ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper());
// 創(chuàng)建Elasticsearch客戶端
esClient = new ElasticsearchClient(transport);
}
到了這里,關(guān)于[elastic 8.x]java客戶端連接elasticsearch與操作索引與文檔的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!