前言
上一章節(jié)我們介紹了搭建Elasticsearch集群相關的知識。那么又該如何來操作Elasticsearch集群呢?在ES官網(wǎng)中提供了各種語言的客戶端,我們在項目開發(fā)過程中有多種Elasticsearch版本和連接客戶端可以選擇,那么他們有什么區(qū)別?這一章節(jié)袁老師帶領大家來學習Elasticsearch客戶端相關的內(nèi)容。
一. ES客戶端介紹
在Elasticsearch官網(wǎng)中提供了各種語言的客戶端:Elasticsearch Clients | Elastic。
|
優(yōu)點 |
缺點 |
說明 |
Java Low Level Rest Client |
與ES版本之間沒有關系,適用于作為所有版本ES的客戶端 |
低級別的REST客戶端,通過HTTP與集群交互,用戶需自己編組請求JSON串,及解析響應JSON串 |
不建議使用 |
Java High Level Rest Client |
官方推出的,版本與ES同步更新 |
使用的版本需要保持和ES服務端的版本一致,否則會有版本問題 |
強烈推薦使用。基于Low Level Rest Client,它提供了更多的接口。注意:7.15版本之后將被棄用 |
TransportClient |
啟動速度快,輕量級,可創(chuàng)建極多連接,與應用程序解耦;推薦使用原生的,ES本身就很簡單,靈活性很高 |
JAR包版本需與ES集群版本一致,ES集群升級,客戶端也跟著升級到相同版本 |
不建議使用。過時產(chǎn)品,7版本之后不再支持 |
Elasticsearch Java API Client |
最新的ES客戶端。Elasticsearch Java API Client通過API的方式來組裝請求數(shù)據(jù),避免直接編寫JSON字符串 |
文檔少 |
使用人較少 |
注意點擊進入后,選擇版本到6.2.4版本 ,因為我們之前按照的都是6.2.4版本講解的。進入后可以通過官方文檔了解和學習Java客戶端相關的知識。
二. 搭建工程環(huán)境
1.創(chuàng)建一個Spring Initalizr類型的項目,項目名稱設置為【es-client】。
2.創(chuàng)建項目時,勾選Lombok、Spring Boot DevTools和Spring Web依賴。
注意:這里我們直接導入了SpringBoot的啟動器,方便后續(xù)講解。
3.將resource目錄下自動生成的application.properties文件修改成application.yml。
4.在項目的pom.xml文件中手動引入Elasticsearch的High-level-Rest-Client等相關的依賴。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yx</groupId>
<artifactId>es-client</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>es-client</name>
<description>es-client</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
<!-- Apache開源組織提供的用于操作Java Bean的工具包 -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.1</version>
</dependency>
<!-- ES高級Rest Client -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.4.3</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.4.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
三. 索引庫及映射
創(chuàng)建索引庫的同時,我們也會創(chuàng)建type及其映射關系,但是這些操作不建議使用Java客戶端完成,原因如下:
- 索引庫和映射往往是初始化時完成,不需要頻繁操作,不如提前配置好。
- 官方提供的創(chuàng)建索引庫及映射API非常繁瑣,需要通過字符串拼接JSON結(jié)構(gòu)。
因此,這些操作建議還是使用我們之前學習的Rest風格API去實現(xiàn)。
在項目的com.yx.pojo包下創(chuàng)建Product商品類,以這樣一個商品數(shù)據(jù)為例來創(chuàng)建索引庫。
package com.yx.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Product {
private Long id; // 主鍵
private String title; // 標題
private String category; // 分類
private String brand; // 品牌
private Double price; // 價格
private String images; // 圖片地址
}
分析一下數(shù)據(jù)結(jié)構(gòu):
屬性 |
描述 |
id |
可以認為是主鍵,將來判斷數(shù)據(jù)是否重復的標識,不分詞,可以使用keyword類型 |
title |
搜索字段,需要分詞,可以用text類型 |
category |
商品分類,這個是整體,不分詞,可以使用keyword類型 |
brand |
品牌,與分類類似,不分詞,可以使用keyword類型 |
price |
價格,這個是double類型 |
images |
圖片,用來展示的字段,不搜索,index為false,不分詞,可以使用keyword類型 |
使用Kibana控制臺向集群中創(chuàng)建yx索引庫并編寫映射配置(如果之前創(chuàng)建過yx索引庫則先刪除)。
PUT /yx
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1
},
"mappings": {
"product": {
"properties": {
"id": {
"type": "keyword"
},
"title": {
"type": "text",
"analyzer": "ik_max_word"
},
"category": {
"type": "keyword"
},
"brand": {
"type": "keyword"
},
"price": {
"type": "double"
},
"images": {
"type": "keyword",
"index": false
}
}
}
}
}
四. 索引數(shù)據(jù)操作
有了索引庫之后,我們接下來看看如何對索引庫中的數(shù)據(jù)進行增刪改查操作。操作MySQL數(shù)據(jù)庫:
1.獲取數(shù)據(jù)庫連接。
2.完成數(shù)據(jù)的增刪改查操作。
3.釋放資源。
1.初始化客戶端
對索引庫做任何操作,都需要通過RestHighLevelClient客戶端來完成。
1.在項目的test測試文件夾下創(chuàng)建com.yx.es包,并在該包下創(chuàng)建一個ElasticsearchTests測試類。
2.然后在ElasticsearchTests類中編寫RestHighLevelClient客戶端的初始化方法init()和關閉方法close()。
package com.yx.es;
import com.google.gson.Gson;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.After;
import org.junit.Before;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
@SpringBootTest
public class ElasticsearchTests {
private RestHighLevelClient restHighLevelClient;
// JSON工具
private Gson gson = new Gson();
/** 初始化客戶端 */
@Before
public void init() {
RestClientBuilder restClientBuilder = RestClient.builder(
new HttpHost("127.0.0.1", 9201, "http"),
new HttpHost("127.0.0.1", 9202, "http"),
new HttpHost("127.0.0.1", 9203, "http")
);
restHighLevelClient = new RestHighLevelClient(restClientBuilder);
}
/** 關閉客戶端 */
@After
public void close() throws IOException {
// 關閉客戶端
restHighLevelClient.close();
}
}
2.新增文檔
新增文檔的實現(xiàn)是,先將數(shù)據(jù)封裝到POJO對象中,然后通過restHighLevelClient對象來向索引庫中新增數(shù)據(jù)。
2.1.新增文檔實現(xiàn)
1.在ElasticsearchTests類中編寫新增文檔的insert()方法。
/** 新增文檔 */
@Test
public void insert() throws IOException {
// 1.文檔數(shù)據(jù)
Product product = new Product();
product.setId(1L);
product.setTitle("華為P60震撼發(fā)布");
product.setCategory("手機");
product.setBrand("華為");
product.setPrice(6999.99);
product.setImages("http://image.huawei.com/1.jpg");
// 2.將文檔數(shù)據(jù)轉(zhuǎn)換為JSON格式
String source = gson.toJson(product);
// 3.創(chuàng)建索引請求對象,訪問哪個索引庫、哪個type、指定文檔ID
IndexRequest request = new IndexRequest("yx", "product", product.getId().toString());
request.source(source, XContentType.JSON);
// 4.發(fā)送請求
IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
System.err.println(response);
}
2.運行insert()方法,輸出結(jié)果見下:
IndexResponse[index=yx,type=product,id=1,version=2,result=updated,seqNo=1,primaryTerm=1,shards={"total":2,"successful":2,"failed":0}]
3.運行insert()方法可能會報錯,具體解決方案見下。
2.2.新增文檔異常
1.如果導入Elasticsearch依賴時不指定其版本,可能導致找不到XContentType類。解決的方案就是在pom.xml文件中手動添加Elasticsearch對應版本的依賴,比如手動指定Elasticsearch的版本為6.4.3。如果沒有這個問題,則忽略此步驟。
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.4.3</version>
</dependency>
2.如果運行insert()方法提示java.lang.NullPointerException空指針異常,則可能的原因是@Test注解的包導入錯誤,注意導入的包是org.junit.Test而非org.junit.jupiter.api.Test。
3.查看文檔
根據(jù)Rest風格,查看文檔是根據(jù)文檔id進行GET查詢操作,難點是對結(jié)果的解析。
1.在ElasticsearchTests類中編寫查看文檔的select()方法。
/** 查看文檔 */
@Test
public void select() throws IOException {
// 創(chuàng)建GET請求并指定id
GetRequest request = new GetRequest("yx", "product", "1");
// 查詢,得到響應
GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
// 獲得響應結(jié)果數(shù)據(jù)
String source = response.getSourceAsString();
// 轉(zhuǎn)化為JSON數(shù)據(jù)
Product product = gson.fromJson(source, Product.class);
System.err.println(product);
}
2.運行select()方法,輸出結(jié)果見下:
Product(id=1, title=華為P60震撼發(fā)布, category=手機, brand=華為, price=6999.99, images=http://image.huawei.com/1.jpg)
4.修改文檔
新增文檔時,如果傳遞的id是已經(jīng)存在的,則會完成修改文檔操作,如果id不存在,則是新增文檔操作。
1.在ElasticsearchTests類中編寫修改文檔的update()方法。
/** 修改文檔 */
@Test
public void update() throws IOException {
// 1.文檔數(shù)據(jù)
Product product = new Product();
product.setId(1L); // id存在則為修改操作
product.setTitle("華為P60直降1000");
product.setPrice(5999.99);
// 2.將文檔數(shù)據(jù)轉(zhuǎn)換為JSON格式
String source = gson.toJson(product);
// 3.創(chuàng)建索引請求對象,訪問哪個索引庫、哪個type、指定文檔ID
IndexRequest request = new IndexRequest("yx", "product", product.getId().toString());
request.source(source, XContentType.JSON);
// 4.發(fā)送請求
IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
System.err.println(response);
}
2.運行update()方法,輸出結(jié)果見下:
IndexResponse[index=yx,type=product,id=1,version=2,result=updated,seqNo=1,primaryTerm=1,shards={"total":2,"successful":2,"failed":0}]
5.刪除文檔
根據(jù)id刪除文檔。
1.在ElasticsearchTests類中編寫刪除文檔的delete()方法。
/** 刪除文檔 */
@Test
public void delete() throws IOException {
// 準備刪除的請求,參數(shù)為id
DeleteRequest request = new DeleteRequest("yx", "product", "1");
// 發(fā)起請求
DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
System.err.println(response);
}
2.運行delete()方法,輸出結(jié)果見下:
DeleteResponse[index=yx,type=product,id=1,version=3,result=deleted,shards=ShardInfo{total=2, successful=2, failures=[]}]
五. 結(jié)語
Elasticsearch客戶端基礎部分的內(nèi)容袁老師就給大家介紹完了?;仡櫹逻@一章節(jié)我們學習的主要內(nèi)容,介紹了ES客戶端項目工程搭建、索引庫及映射、索引數(shù)據(jù)操作,主要重點介紹了索引數(shù)據(jù)的增刪改查操縱。關于ES客戶端基礎部分的內(nèi)容就介紹到這里,下一章節(jié)袁老師帶領大家學習Elasticsearch客戶端高級操作部分的內(nèi)容。
今天的內(nèi)容就分享到這里吧。關注「袁庭新」,干貨天天都不斷!文章來源:http://www.zghlxwxcb.cn/news/detail-857214.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-857214.html
到了這里,關于袁庭新ES系列15節(jié)|Elasticsearch客戶端基礎操作的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!