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

85 lines
2.7 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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.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.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;
@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);
}
// 查询文档操作
@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));
}
// 更新文档
@Test
void testUpdateDocument() throws IOException {
// 1. Request准备
UpdateRequest request = new UpdateRequest("hotel", "61083");
// 准备请求参数
request.doc(
"price", "666",
"startName", "四钻"
);
// 发送请求
client.update(request, RequestOptions.DEFAULT);
}
}