ElasticSearch/src/test/java/cn/itcast/hotel/HotelDocumentTest.java

68 lines
2.2 KiB
Java
Raw Normal View History

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;
2024-03-31 20:38:49 +08:00
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
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);
}
2024-03-31 20:38:49 +08:00
// 查询文档操作
@Test
void testGetDocuments() throws Exception {
// 准备Request
GetRequest request = new GetRequest("hotel", "61083");
// 发送请求
GetResponse response = client.get(request, RequestOptions.DEFAULT);
// 解析响应结果
String json = response.getSourceAsString();
System.out.println(JSON.parseObject(json, HotelDoc.class));
}
}