?引言
本文參考黑馬 分布式Elastic search
Elasticsearch是一款非常強(qiáng)大的開源搜索引擎,具備非常多強(qiáng)大功能,可以幫助我們從海量數(shù)據(jù)中快速找到需要的內(nèi)容
一、初始化 Java RestClient
初始化RestHighLevelClient
為了與索引庫操作分離,我們再次參加一個測試類,做兩件事情:
- 初始化RestHighLevelClient
- 我們的酒店數(shù)據(jù)在數(shù)據(jù)庫,需要利用IHotelService去查詢,所以注入這個接口
文檔測試類
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import java.util.List;
/**
* @author whc
* @date 2023/2/28 15:01
*/
@SpringBootTest
public class HotelDocumentTest {
private RestHighLevelClient restHighLevelClient;
@Autowired
private IHotelService hotelService;
@BeforeEach
void setUp() {
this.restHighLevelClient = new RestHighLevelClient(RestClient.builder(
HttpHost.create("IP地址:9200")
));
}
@AfterEach
void tearDown() throws IOException {
this.restHighLevelClient.close();
}
}
測試類初始化 RestClient完畢。
二、RestClient 對文檔的CRUD操作
下面我們通過RestClient 對 文檔進(jìn)行 增刪改查操作,以便更加深層次的理解。
?新增文檔
需求: 將酒店數(shù)據(jù)從數(shù)據(jù)庫查詢出來,通過RestClient寫入到ElasticSearch中。
實(shí)體類與索引庫實(shí)體類的轉(zhuǎn)換
數(shù)據(jù)庫返回的結(jié)果是一個Hotel類型的對象,屬性如下:
@Data
@TableName("tb_hotel")
public class Hotel {
@TableId(type = IdType.INPUT)
private Long id;
private String name;
private String address;
private Integer price;
private Integer score;
private String brand;
private String city;
private String starName;
private String business;
private String longitude;
private String latitude;
private String pic;
}
那么問題來了,我們的ElasticSearch 索引庫的結(jié)構(gòu)與實(shí)體類不一致該怎么辦?
例如:經(jīng)緯度,索引庫中是 通過location來實(shí)現(xiàn)的,通過 , 分割開 。 實(shí)體類中則是兩個單獨(dú)的屬性。
因此,我們需要定義一個新的對象,將該屬性進(jìn)行合并從而達(dá)到我們想要的結(jié)果
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class HotelDoc {
private Long id;
private String name;
private String address;
private Integer price;
private Integer score;
private String brand;
private String city;
private String starName;
private String business;
private String location;
private String pic;
public HotelDoc(Hotel hotel) {
this.id = hotel.getId();
this.name = hotel.getName();
this.address = hotel.getAddress();
this.price = hotel.getPrice();
this.score = hotel.getScore();
this.brand = hotel.getBrand();
this.city = hotel.getCity();
this.starName = hotel.getStarName();
this.business = hotel.getBusiness();
this.location = hotel.getLatitude() + ", " + hotel.getLongitude();
this.pic = hotel.getPic();
}
}
語法說明
新增文檔的DSL語句如下:
POST /{索引庫名}/_doc/1
{
"name": "Jack",
"age": 20
}
Java代碼如下
可以看到與創(chuàng)建索引庫類似,同樣是三步走:
- 1.創(chuàng)建Request對象
- 2.準(zhǔn)備請求參數(shù),也就是DSL中的JSON文檔
- 3.發(fā)送請求
變化的地方在于,這里直接使用**client.xxx()的API,不再需要client.indices()**了。
完整代碼測試新增文檔
@Test
void testAddDocument() throws IOException {
//獲取酒店數(shù)據(jù)
Hotel hotel = hotelService.getById(36934L);
HotelDoc hotelDoc = new HotelDoc(hotel);
//1.創(chuàng)建request對象
IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
//2.準(zhǔn)備參數(shù)
request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
//3.發(fā)送請求
restHighLevelClient.index(request, RequestOptions.DEFAULT);
}
執(zhí)行即可。
?查詢文檔
查詢的DSL語句如下:
GET /索引庫名/_doc/{id}
大致分為2步
- 準(zhǔn)備Request對象
- 發(fā)送請求
不過查詢的目的是得到結(jié)果,解析為HotelDoc,因此難點(diǎn)是結(jié)果的解析。完整代碼如下:
可以看到,結(jié)果是一個 JSON,其中文檔放在一個_source
屬性中,因此解析就是拿到_source
,反序列化為Java對象即可。
與之前類似,也是分為三步
- 1.準(zhǔn)備Request對象。這次是查詢,所以是GetRequest
- 2.發(fā)送請求,得到結(jié)果。因?yàn)槭遣樵?,這里調(diào)用client.get()方法
- 3.解析結(jié)果,就是對JSON做反序列化
完整代碼
@Test
void testGetDocument() throws IOException {
//1.創(chuàng)建request對象
GetRequest request = new GetRequest("hotel", "36934");
//2.發(fā)送請求
GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
String sourceAsString = response.getSourceAsString();
System.out.println(sourceAsString);
}
結(jié)果如下:
?修改文檔
修改是分為兩種方式:
- 全量修改:本質(zhì)是先根據(jù)id刪除,再新增
- 增量修改:修改文檔中的指定字段值
在RestClient的API中,全量修改與新增的API完全一致,判斷依據(jù)是ID:
- 如果新增時(shí),ID已經(jīng)存在,則修改
- 如果新增時(shí),ID不存在,則新增
這里我們主要介紹 增量修改
代碼示例如下:
與之前類似,主要分為三步
- 1.準(zhǔn)備Request對象。這次是修改,所以是 UpdateRequest
- 2.準(zhǔn)備參數(shù)。也就是JSON文檔,里面包含要修改的字段
- 3.更新文檔。這里調(diào)用client.update()方法
完整代碼
@Test
void testUpdateDocument() throws IOException {
//1.創(chuàng)建request對象
UpdateRequest request = new UpdateRequest("hotel", "36934");
//2.準(zhǔn)備參數(shù)
request.doc(
"price", "456",
"starName", "三鉆"
);
//3.發(fā)送請求
restHighLevelClient.update(request, RequestOptions.DEFAULT);
}
修改結(jié)果
執(zhí)行完畢修改后,再次通過get請求查看修改結(jié)果
?刪除文檔
刪除的DSL為是這樣的:
DELETE /hotel/_doc/{id}
與查詢相比,僅僅是請求方式從DELETE變成GET,可以想象Java代碼應(yīng)該依然分為三步:
- 1.準(zhǔn)備Request對象,因?yàn)槭莿h除,這次是DeleteRequest對象。要指定索引庫名和id
- 2.準(zhǔn)備參數(shù),無參
- 3.發(fā)送請求。因?yàn)槭莿h除,所以是client.delete()方法
完整Java代碼
@Test
void testDeleteDocument() throws IOException {
//1.創(chuàng)建request對象
DeleteRequest request = new DeleteRequest("hotel", "36934");
//2.發(fā)送請求
restHighLevelClient.delete(request, RequestOptions.DEFAULT);
}
查看刪除結(jié)果
執(zhí)行完畢后,調(diào)用get請求查看結(jié)果
三、RestClient 批量文檔導(dǎo)入
需求:利用BulkRequest批量將數(shù)據(jù)庫數(shù)據(jù)導(dǎo)入到索引庫中。
步驟如下:
- 利用 mybatis-plus 查詢酒店數(shù)據(jù)
- 將查詢到的酒店數(shù)據(jù)(Hotel)轉(zhuǎn)換為文檔類型數(shù)據(jù)(HotelDoc)
- 利用JavaRestClient中的BulkRequest批處理,實(shí)現(xiàn)批量新增文檔
批量處理BulkRequest,其本質(zhì)就是將多個普通的CRUD請求組合在一起發(fā)送。
其中提供了一個add方法,用來添加其他請求
可以看到,能添加的請求包括:
- IndexRequest,也就是新增
- UpdateRequest,也就是修改
- DeleteRequest,也就是刪除
因此Bulk中添加了多個IndexRequest,就是批量新增功能了。示例:
依舊是分為三步:
- 1.創(chuàng)建Request對象。這里是BulkRequest
- 2.準(zhǔn)備參數(shù)。批處理的參數(shù),就是其它Request對象,這里就是多個IndexRequest
- 3.發(fā)起請求。這里是批處理,調(diào)用的方法為client.bulk()方法
導(dǎo)入酒店數(shù)據(jù)后,將代碼改為for循環(huán)即可
完整Java代碼
@Test
void testBulk() throws IOException {
//獲取酒店數(shù)據(jù)
List<Hotel> hotels = hotelService.list();
//1.創(chuàng)建bulk請求
BulkRequest request = new BulkRequest();
//2.添加批量處理的請求
for (Hotel hotel : hotels) {
HotelDoc hotelDoc = new HotelDoc(hotel);
request.add(new IndexRequest("hotel").
id(hotel.getId().toString()).source(JSON.toJSONString(hotelDoc), XContentType.JSON));
}
//3.發(fā)送請求
restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
}
查看執(zhí)行結(jié)果
執(zhí)行完畢后,執(zhí)行 以下DSL語句批量查詢
執(zhí)行完畢,導(dǎo)入成功。
?小結(jié)
以上就是【Bug 終結(jié)者】對 微服務(wù)分布式搜索引擎 Elastic Search RestClient 操作文檔 的簡單介紹,ES搜索引擎無疑是最優(yōu)秀的分布式搜索引擎,使用它,可大大提高項(xiàng)目的靈活、高效性! 技術(shù)改變世界!??!
文章來源:http://www.zghlxwxcb.cn/news/detail-819667.html
如果這篇【文章】有幫助到你,希望可以給【Bug 終結(jié)者】點(diǎn)個贊??,創(chuàng)作不易,如果有對【后端技術(shù)】、【前端領(lǐng)域】感興趣的小可愛,也歡迎關(guān)注?????? 【Bug 終結(jié)者】??????,我將會給你帶來巨大的【收獲與驚喜】??????!文章來源地址http://www.zghlxwxcb.cn/news/detail-819667.html
到了這里,關(guān)于微服務(wù)分布式搜索引擎 Elastic Search RestClient 操作文檔的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!