当前位置:网站首页>Restclient operation document
Restclient operation document
2022-07-19 04:54:00 【Ozawa can't Java】
In order to separate from the index library operation , Let's take part in a test class again , Do two things :
initialization RestHighLevelClient
Our hotel data is in the database , Need to use IHotelService Go to query , So inject this
@SpringBootTest public class HotelDocumentTest { @Autowired private IHotelService hotelService; private RestHighLevelClient client; @BeforeEach void setUp() { this.client = new RestHighLevelClient(RestClient.builder( HttpHost.create("http://192.168.150.101:9200") )); } @AfterEach void tearDown() throws IOException { this.client.close(); } }1. The new document
We need to query the hotel data in the database , write in elasticsearch in .
1.1. Index library entity class
The result of database query is Hotel Object of type . The structure is as follows :
@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;
}
It is different from our index library structure :
longitude and latitude Need to merge into location
therefore , We need to define a new type , Consistent with the index library structure :
@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();
}
}
1.2. Syntax description
New document DSL The statement is as follows :
POST /{ Index library name }/_doc/1
{
"name": "Jack",
"age": 21
}
Corresponding java Code as shown :

You can see that it is similar to creating an index library , It's also a three-step process :
1) establish Request object
2) Prepare request parameters , That is to say DSL Medium JSON file
3) Send a request
What has changed is , I'm going to use it directly here client.xxx() Of API, No longer need client.indices() 了 .
The overall steps of the code are as follows :
1) according to id Query hotel data Hotel
2) take Hotel Encapsulated in the HotelDoc
3) take HotelDoc Serialize to JSON
4) establish IndexRequest, Specify the index library name and id
5) Prepare request parameters , That is to say JSON file
6) Send a request
@Test
void testAddDocument() throws IOException {
// 1. according to id Query hotel data
Hotel hotel = hotelService.getById(61083L);
// 2. Convert to document type
HotelDoc hotelDoc = new HotelDoc(hotel);
// 3. take HotelDoc turn json
String json = JSON.toJSONString(hotelDoc);
// 1. Get ready Request object
IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
// 2. Get ready Json file
request.source(json, XContentType.JSON);
// 3. Send a request
client.index(request, RequestOptions.DEFAULT);
}2. Query the document
2.1. Syntax description
Of the query DSL The statement is as follows :
GET /hotel/_doc/{id}
Similar to before , It's also three steps :
1) Get ready Request object . This is a query , So it is GetRequest
2) Send a request , Get the results . Because it's a query , This call client.get() Method
3) Analysis results , That's right JSON Do deserialization
@Test
void testGetDocumentById() throws IOException {
// 1. Get ready Request
GetRequest request = new GetRequest("hotel", "61082");
// 2. Send a request , Get a response
GetResponse response = client.get(request, RequestOptions.DEFAULT);
// 3. Analytical response results
String json = response.getSourceAsString();
HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
System.out.println(hotelDoc);
}
3. Delete the document
Delete the DSL For this :
DELETE /hotel/_doc/{id}
Compared with query , Just a request from DELETE become GET, As you can imagine Java The code should still be three steps :
1) Get ready Request object , Because it's deletion , This time it is DeleteRequest object . To specify the index library name and id
2) Prepare parameters , No arguments
3) Send a request . Because it's deletion , So it is client.delete() Method
@Test
void testDeleteDocument() throws IOException {
// 1. Get ready Request
DeleteRequest request = new DeleteRequest("hotel", "61083");
// 2. Send a request
client.delete(request, RequestOptions.DEFAULT);
}
4. Modify the document
4.1. Syntax description
Modify the two ways we talked about :
Full revision : The essence is based on id Delete , Add new
Incremental changes : Modify the specified field value in the document
stay RestClient Of API in , Fully modified and newly added API Exactly the same , The basis of judgment is ID:
If you add ,ID Already exist , The modified
If you add ,ID non-existent , Then add

Similar to before , It's also three steps :
1) Get ready Request object . This is a revision , So it is UpdateRequest
2) Prepare parameters . That is to say JSON file , It contains the fields to be modified
3) Update the document . This call client.update() Method
@Test
void testUpdateDocument() throws IOException {
// 1. Get ready Request
UpdateRequest request = new UpdateRequest("hotel", "61083");
// 2. Prepare request parameters
request.doc(
"price", "952",
"starName", " Four drill "
);
// 3. Send a request
client.update(request, RequestOptions.DEFAULT);
}
5. Batch import documents
Case needs : utilize BulkRequest Batch import database data into the index library .
Steps are as follows :
utilize mybatis-plus Query hotel data
The queried hotel data (Hotel) Convert to document type data (HotelDoc)
utilize JavaRestClient Medium BulkRequest The batch , Realize batch addition of documents
5.1. Syntax description
Batch processing BulkRequest, Its essence is to integrate multiple ordinary CRUD Requests are sent together .
It provides a add Method , Used to add other requests :
You can see , Requests that can be added include :
IndexRequest, That is, new
UpdateRequest, That is to modify
DeleteRequest, Delete
In fact, it's still three steps :
1) establish Request object . Here is BulkRequest
2) Prepare parameters . Batch parameters , It's the others Request object , Here are many IndexRequest
3) Initiate request . This is batch processing , The method called is client.bulk() Method
@Test
void testBulkRequest() throws IOException {
// Batch query of hotel data
List<Hotel> hotels = hotelService.list();
// 1. establish Request
BulkRequest request = new BulkRequest();
// 2. Prepare parameters , Add multiple new Request
for (Hotel hotel : hotels) {
// 2.1. Convert to document type HotelDoc
HotelDoc hotelDoc = new HotelDoc(hotel);
// 2.2. Create a new document Request object
request.add(new IndexRequest("hotel")
.id(hotelDoc.getId().toString())
.source(JSON.toJSONString(hotelDoc), XContentType.JSON));
}
// 3. Send a request
client.bulk(request, RequestOptions.DEFAULT);
}6. Summary
Basic steps of document operation :
initialization RestHighLevelClient
establish XxxRequest.XXX yes Index、Get、Update、Delete、Bulk
Prepare parameters (Index、Update、Bulk The need when )
Send a request . call RestHighLevelClient#.xxx() Method ,xxx yes index、get、update、delete、bulk
Analysis results (Get The need when )
边栏推荐
猜你喜欢

Tidb performance optimization overview

数据库取配置文件字段,然后进行数据处理和判断

2022最新版校园跑腿小程序源码
[论文精读]BERT

Simple UI funny text conversion Emoji expression wechat applet supports sentence word conversion_ Source code

【Lipschitz】基于matlab的Lipschitz李氏指数仿真

C language dynamic memory development and flexible array

DSL查询文档

UE-插件 ElectronicNodes 5.0.0/4.23-4.27

Project structure of wechat applet
随机推荐
DSL查询文档
TiDB 性能优化概述
MYSQL数据库表A数据同步到表B
masm32写程序
shardingproxy分库分表实战及同类产品对比
Warriors of the Visual Studio, Assemble! (Visual Studio的勇士们,汇编吧!) 原创 2009年07月12日 19:40:00 标签:汇编 /mic
RestAPI
Overview of CKS core knowledge points
Construction and application of knowledge map de (VII): large scale knowledge map pre training
itext修改pdf文字
Efficient insertion of references in word with thousands of words and many pictures
【FPGA教程案例26】在FPGA中通过verilog来实现小数的基础运算
HighTec 新建 AURIX TC37X demo 工程
Tidb learning
Advanced query of MySQL table
DSL搜索结果处理,包括排序,分页,高亮
Construction and application of knowledge map de (VI): storage, service and quality of knowledge map
npm安装教程
'ionic' is not an internal or external command, nor is it a runnable program or batch file.
Emqx pressure test tread pit for your reference