新增文档:发送用index

先从数据库获取pojo对象 在把此pojo对象转换为索引pojo对象(里面有些属性是需要处理的)
再把此pojo对象转为json字符串
新建一个索引请求对象(使用.id可以指定id索引) 参数为索引库名
请求对象用source方法 参数为json字符串和类型
连接对象使用index方法 发送请求 参数为请求对象和 默认请求选项

  1. @Test
  2. void testAddDocument() throws IOException {
  3. // 1.根据id查询酒店数据
  4. Hotel hotel = hotelService.getById(61083L);
  5. // 2.转换为文档类型
  6. HotelDoc hotelDoc = new HotelDoc(hotel);
  7. // 3.将HotelDoc转json
  8. String json = JSON.toJSONString(hotelDoc);
  9. // 1.准备Request对象
  10. IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
  11. // 2.准备Json文档
  12. request.source(json, XContentType.JSON);
  13. // 3.发送请求
  14. client.index(request, RequestOptions.DEFAULT);
  15. }

查询文档:

新建一个查询请求对象 参数数据库名和指定id
使用连接对象 的get方法 发送请求 参数为请求对象和默认请求选项 返回值为GetResponse类型的响应对象
把响应对象 获取source 字符串
把json字符串 解析成对象

  1. @Test
  2. void testGetDocumentById() throws IOException {
  3. // 1.准备Request
  4. GetRequest request = new GetRequest("hotel", "61082");
  5. // 2.发送请求,得到响应
  6. GetResponse response = client.get(request, RequestOptions.DEFAULT);
  7. // 3.解析响应结果
  8. String json = response.getSourceAsString();
  9. HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
  10. System.out.println(hotelDoc);
  11. }

删除文档:

新建一个 删除请求对象 参数为数据库名和id
连接对象使用delete方法 发送删除请求

  1. @Test
  2. void testDeleteDocument() throws IOException {
  3. // 1.准备Request
  4. DeleteRequest request = new DeleteRequest("hotel", "61083");
  5. // 2.发送请求
  6. client.delete(request, RequestOptions.DEFAULT);
  7. }

修改文档:

新建一个更新请求对象 参数为索引库名和 id
请求对象使用doc方法 参数为一个属性 一个属性值 交替的字符串形式
使用连接对象 的update方法 发送请求 参数为请求对象和默认方法

  1. @Test
  2. void testUpdateDocument() throws IOException {
  3. // 1.准备Request
  4. UpdateRequest request = new UpdateRequest("hotel", "61083");
  5. // 2.准备请求参数
  6. request.doc(
  7. "price", "952",
  8. "starName", "四钻"
  9. );
  10. // 3.发送请求
  11. client.update(request, RequestOptions.DEFAULT);
  12. }

批量导入:

先利用mybatisplus构建的服务类 使用list方法 获取 全部 po对象集合
新建一个批量请求对象
遍历list集合 把每一个po对象转为ES的po对象 并使用批量请求对对象的add方法添加已经设置好数据的基本请求对象
最后使用连接对象的bulk批量方法 发送请求 请求参数为批量请求对象和默认选项

  1. @Test
  2. void testBulkRequest() throws IOException {
  3. // 批量查询酒店数据
  4. List<Hotel> hotels = hotelService.list();
  5. // 1.创建Request
  6. BulkRequest request = new BulkRequest();
  7. // 2.准备参数,添加多个新增的Request
  8. for (Hotel hotel : hotels) {
  9. // 2.1.转换为文档类型HotelDoc
  10. HotelDoc hotelDoc = new HotelDoc(hotel);
  11. // 2.2.创建新增文档的Request对象
  12. request.add(new IndexRequest("hotel")
  13. .id(hotelDoc.getId().toString())
  14. .source(JSON.toJSONString(hotelDoc), XContentType.JSON));
  15. }
  16. // 3.发送请求
  17. client.bulk(request, RequestOptions.DEFAULT);
  18. }