@SpringBootTest public class EsTest { // *** 作ES的对象,类似于RedisTemplate private RestHighLevelClient client; @Autowired private HotelService service; //对象创建完成时执行 @BeforeEach void setUp() { this.client = new RestHighLevelClient( RestClient.builder( HttpHost.create("http://192.168.207.20:9200"))); } //对象使用结束后执行 @AfterEach void tearDown() throws IOException { this.client.close(); } //测试resthighlevelclient @Test void init() { System.out.println("111111111111111"); } //测试创建索引 @Test void testCreateHotelIndex() throws IOException { CreateIndexRequest request = new CreateIndexRequest("hotel"); request.source(MAPPING_TEMPLATE, XContentType.JSON); client.indices().create(request, RequestOptions.DEFAULT); } // 测试删除索引 @Test void testDelHotelIndex() throws IOException { DeleteIndexRequest request = new DeleteIndexRequest("hotel"); client.indices().delete(request, RequestOptions.DEFAULT); } // 测试索引库是否存在 @Test void testExistsHotelIndex() throws IOException { GetIndexRequest request = new GetIndexRequest("hotel"); boolean exists = client.indices().exists(request, RequestOptions.DEFAULT); System.out.println(exists); } // 添加一条文档 @Test void testAddHotelDoc() throws IOException { Hotel hotel = service.getById(38609L); HotelDoc hotelDoc = new HotelDoc(hotel); String json = JSON.toJSONString(hotelDoc); IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString()); request.source(json, XContentType.JSON); client.index(request, RequestOptions.DEFAULT); } //获取一条文档 @Test void testGetHotelDoc() throws IOException { GetRequest request = new GetRequest("hotel").id("38609"); GetResponse response = client.get(request, RequestOptions.DEFAULT); String json = response.getSourceAsString(); System.out.println(json); } // 删除一条文档 @Test void testDelHotelDoc() throws IOException { DeleteRequest request = new DeleteRequest("hotel", "38609"); client.delete(request, RequestOptions.DEFAULT); } // 更新一条语句 @Test void testUpdateHotelDoc() throws IOException { UpdateRequest request = new UpdateRequest("hotel", "38609"); request.doc("address", "广灵二路888号", "business", "哈尔滨市道里区上海路"); client.update(request, RequestOptions.DEFAULT); } // 测试批量添加 @Test void testBunkAddHotelDoc() throws IOException { BulkRequest request = new BulkRequest("hotel"); List依赖list = service.list(); for (Hotel hotel : list) { HotelDoc hotelDoc = new HotelDoc(hotel); request.add(new IndexRequest() .id(hotelDoc.getId().toString()) .source(JSON.toJSONString(hotelDoc),XContentType.JSON)); } client.bulk(request,RequestOptions.DEFAULT); } }
如果你用了springboot 的父工程管理了依赖的版本,那么你在引入ES的依赖是就需要再次声明依赖的版本,因为父工程的默认依赖版本比较低。
org.springframework.boot spring-boot-starter-parent2.3.10.RELEASE 1.8 7.12.1 org.elasticsearch.client elasticsearch-rest-high-level-client
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)