前言:上文介紹了使用DSL語言操作索引庫和文檔,本篇文章將介紹使用Java中的RestClient來對索引庫和文檔進行操作。
希望能夠加深自己的印象以及幫助到其他的小伙伴兒們????。
如果文章有什么需要改進的地方還請大佬不吝賜教????。
小威在此先感謝各位大佬啦~~????
??個人主頁:小威要向諸佬學習呀
??個人簡介:大家好,我是小威,一個想要與大家共同進步的男人????
目前狀況??:24屆畢業(yè)生,曾經(jīng)在某央企公司實習,目前在某稅務(wù)公司實習??????歡迎大家:這里是CSDN,我總結(jié)知識的地方,歡迎來到我的博客,我親愛的大佬??
以下正文開始

好,那就詳細記錄下這塊的知識。
前面記錄了在網(wǎng)頁端使用DSL語句對Elasticsearch的索引庫和文檔進行增刪改查的簡單操作。但是在日常的開發(fā)工作中,還是用Java語言操作比較多,因此需要使用Elasticsearch官方提供的RestClient操作索引庫和文檔。
首先準備一個索引庫名為hotel的庫并分析其中字段的數(shù)據(jù)結(jié)構(gòu),然后根據(jù)字段的名稱,數(shù)據(jù)類型,是否參與搜索,是否分詞,分詞器等條件來完善其mapping,在其內(nèi)部定義了一個名為“all”字段的屬性,這個字段目的是將其他同時參與搜索的字段cope_to在一起,搜索的時候根據(jù)“all”字段內(nèi)的查詢條件一起搜索,可以提高搜索效率:
PUT /hotel
{
"mappings": {
"properties": {
"id":{
"type": "keyword"
},
"name":{
"type": "text",
"analyzer": "ik_max_word",
"copy_to": "all"
},
"address":{
"type": "keyword",
"index": false
},
"price":{
"type": "integer"
},
"score":{
"type": "integer"
},
"brand":{
"type": "keyword",
"copy_to": "all"
},
"city":{
"type":"keyword"
},
"starName":{
"type": "keyword"
},
"business":{
"type": "keyword"
, "copy_to": "all"
},
"location":{
"type": "geo_point"
},
"pic":{
"type": "keyword",
"index": false
},
"all":{
"type": "text",
"analyzer": "ik_max_word"
}
}
}
}
那么,如何在idea中操作對索引庫和文檔進行操作呢?
倘若我們想要使用RestClient來操作,首要任務(wù)就是引入其依賴:
<!--elasticsearch-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.12.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>
第二步,在測試類中編寫測試方法,我們需要創(chuàng)建RestClient對象,然后對RestClient進行初始化,當然創(chuàng)建完成RestClient后需要銷毀,代碼如下:
private RestHighLevelClient client;
@BeforeEach //創(chuàng)建對象初始化
void setUp() {
client = new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://192.168.220.***:9200") //創(chuàng)建方法
));
}
@AfterEach //創(chuàng)建完成后銷毀
void tearDown() throws IOException {
client.close();
}
RestClient操作索引庫
創(chuàng)建索引庫
這里的創(chuàng)建索引庫方法和我們上面DSL語句的含義是一樣的,雖然描述方式有所不同。
- 第一行代碼創(chuàng)建索引庫,相當于DSL語句中的PUT /hotel
- 第二行代碼準備請求參數(shù),MAPPING_TEMPLATE為創(chuàng)建DSL語句中的內(nèi)容(除去PUT /hotel那些)
- 第三步調(diào)用client的indices()拿到操作索引庫的所有方法,然后取出create方法
@Test
void testCreateIndex() throws IOException {
// 1.準備Request PUT /hotel
CreateIndexRequest request = new CreateIndexRequest("hotel");
// 2.準備請求參數(shù)
request.source(MAPPING_TEMPLATE, XContentType.JSON);//這里將DSL語句封裝成了MAPPING_TEMPLATE,優(yōu)雅美觀
// 3.發(fā)送請求
client.indices().create(request, RequestOptions.DEFAULT);
}
可以進入indices方法的源碼,查看得返回的是indicesClient,如下:
public final IndicesClient indices() {
return this.indicesClient;
}
delete的方法的源碼,由此可見上面?zhèn)魅雛equest請求即可:
public final class IndicesClient {
private final RestHighLevelClient restHighLevelClient;
IndicesClient(RestHighLevelClient restHighLevelClient) {
this.restHighLevelClient = restHighLevelClient;
}
public AcknowledgedResponse delete(DeleteIndexRequest deleteIndexRequest, RequestOptions options) throws IOException {
return restHighLevelClient.performRequestAndParseEntity(deleteIndexRequest, IndicesRequestConverters::deleteIndex, options,
AcknowledgedResponse::fromXContent, emptySet());
}
}
刪除索引庫
根據(jù)以上信息,我們不難得出使用RestClient刪除索引庫和判斷索引庫是否存在的相關(guān)代碼:
@Test //判斷索引庫是否存在
void testExistsIndex() throws IOException {
// 1.準備Request,注意這塊是獲取索引庫請求而不是創(chuàng)建
GetIndexRequest request = new GetIndexRequest("hotel");
// 3.發(fā)送請求,調(diào)用exists方法
boolean isExists = client.indices().exists(request, RequestOptions.DEFAULT);
System.err.println(isExists ? "索引庫存在" : "索引庫不存在");
}
@Test //刪除索引庫操作
void testDeleteIndex() throws IOException {
// 1.準備Request,指定刪除哪個索引庫
DeleteIndexRequest request = new DeleteIndexRequest("hotel");
// 3.發(fā)送請求,調(diào)用delete方法
client.indices().delete(request, RequestOptions.DEFAULT);
}
綜上所述,索引庫操作的基本步驟:
? 初始化RestHighLevelClient
? 創(chuàng)建XxxIndexRequest。Xxx可以是Create,Get,Delete
? 準備DSL語句( Create時需要)
? 發(fā)送請求。調(diào)用RestHighLevelClient#indices().xxx()方法,xxx可以是create,exists,delete
RestClient操作文檔
操作文檔和操作索引庫一樣,需要完成RestClient的初始化和銷毀操作,這里不展現(xiàn)重復代碼了。
插入文檔
前面調(diào)用MybatisPlus中查詢的方法從數(shù)據(jù)庫中查詢出ID為61083的信息,由于索引庫和數(shù)據(jù)庫中的某字段不是很對應,所以做了一次轉(zhuǎn)換。之后開始操作文檔。
- 第一步,創(chuàng)建文檔,與POST /索引庫名稱/_doc/1相對應
- 第二步,準備json文檔,上部代碼已經(jīng)對數(shù)據(jù)json序列化了
- 第三步,直接調(diào)用index方法發(fā)送請求
private RestHighLevelClient client;
@Autowired
private IHotelService hotelService;
@Test
void testAddDocument() throws IOException {
// 1.查詢數(shù)據(jù)庫hotel數(shù)據(jù)
Hotel hotel = hotelService.getById(61083L);
// 2.轉(zhuǎn)換為HotelDoc
HotelDoc hotelDoc = new HotelDoc(hotel);
// 3.轉(zhuǎn)JSON
String json = JSON.toJSONString(hotelDoc);
// 1.準備Request
IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());//索引庫中對id的要求為"keyword",因此要轉(zhuǎn)換成string類型
// 2.準備請求參數(shù)DSL,其實就是文檔的JSON字符串
request.source(json, XContentType.JSON);
// 3.發(fā)送請求
client.index(request, RequestOptions.DEFAULT);
}
查詢文檔
根據(jù)id查詢文檔信息,相對應的DSL語句為:GET /數(shù)據(jù)庫名稱/_doc/1。查詢是新建GetRequest對象。
@Test
void testGetDocumentById() throws IOException {
// 1.準備Request // GET /hotel/_doc/{id}
GetRequest request = new GetRequest("hotel", "61083");
// 2.發(fā)送請求
GetResponse response = client.get(request, RequestOptions.DEFAULT);
// 3.解析響應結(jié)果
String json = response.getSourceAsString();
//查詢出來的對象是json形式,這里轉(zhuǎn)換成HotelDoc對象形式
HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
System.out.println("hotelDoc = " + hotelDoc);
}
修改文檔
前面介紹的修改有兩種方式,一種為全局修改,一種為增量修改,這里以增量修改為例(DSL語句:POST /數(shù)據(jù)庫名稱/_doc/1):
@Test
void testUpdateById() throws IOException {
// 1.準備Request
UpdateRequest request = new UpdateRequest("hotel", "61083");
// 2.準備參數(shù),這里是需要改變的參數(shù)
request.doc(
"price", "870"
);
// 3.發(fā)送請求
client.update(request, RequestOptions.DEFAULT);
}
文檔操作的基本步驟:
? 初始化RestHighLevelClient
? 創(chuàng)建XxxRequest。Xxx可以是Index,Get,Update,Delete
? 準備參數(shù)(Index和Update時需要)
? 發(fā)送請求。調(diào)用RestHighLevelClient.xxx()方法,xxx可以是index,get,update,delete
? 解析結(jié)果(Get時需要,將查詢出的json形式轉(zhuǎn)化為對象形式)
本篇文章就先分享到這里了,后續(xù)會繼續(xù)分享其他方面的知識,感謝大佬認真讀完支持咯~
文章到這里就結(jié)束了,如果有什么疑問的地方請指出,諸佬們一起討論??
希望能和諸佬們一起努力,今后我們頂峰相見??
再次感謝各位小伙伴兒們的支持??文章來源:http://www.zghlxwxcb.cn/news/detail-458385.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-458385.html
到了這里,關(guān)于ElasticSearch之RestClient操作索引庫和文檔的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!