feat(新增): 插入文档,记得转换成JSON对象

This commit is contained in:
bunny 2024-03-31 20:31:59 +08:00
parent ae0449c991
commit 5d5a36b752
5 changed files with 58 additions and 6 deletions

View File

@ -1,5 +1,5 @@
<?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"
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>
@ -49,13 +49,13 @@
</exclusion>
</exclusions>
</dependency>
<!--FastJson-->
<!--FastJson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.71</version>
<version>2.0.47</version>
</dependency>
<dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>

View File

@ -2,7 +2,7 @@ server:
port: 8089
spring:
datasource:
url: jdbc:mysql://mysql:3306/tb_hotel?useSSL=false
url: jdbc:mysql://106.15.251.123:3305/tb_hotel?useSSL=false
username: root
password: "02120212"
driver-class-name: com.mysql.jdbc.Driver

View File

@ -0,0 +1,52 @@
package cn.itcast.hotel;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
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;
@SpringBootTest
public class HotelDocumentTest {
private RestHighLevelClient client;
@Autowired
private IHotelService hotelService;
@BeforeEach
void setup() throws Exception {
this.client = new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://192.168.1.4:9200"))
);
}
@AfterEach
void teardown() throws Exception {
this.client.close();
}
// 插入文档记得转换成JSON对象
@Test
void testAddDocument() throws Exception {
// 根据id查询酒店数据
Hotel hotel = hotelService.getById(61083L);
// 转换为文档类型其中有经纬度转换
HotelDoc hotelDoc = new HotelDoc(hotel);
// 1. 准备Request对象
IndexRequest request = new IndexRequest("hotel").id(String.valueOf(hotelDoc.getId()));
// 2. 准备JSON文档
request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
// 3. 发送请求
client.index(request, RequestOptions.DEFAULT);
}
}

View File

@ -2,7 +2,7 @@ server:
port: 8089
spring:
datasource:
url: jdbc:mysql://mysql:3306/tb_hotel?useSSL=false
url: jdbc:mysql://106.15.251.123:3305/tb_hotel?useSSL=false
username: root
password: "02120212"
driver-class-name: com.mysql.jdbc.Driver