elasticsearch的RestAPI之操作文档(增删改)

RestClient操作文档

新增文档

将DB表中的数据同步到elasticsearch

1)查询数据库

1.1)数据库查询后的结果是一个Hotel类型的对象

复制代码
 1 @Data
 2 @TableName("tb_hotel")
 3 public class Hotel {
 4     @TableId(type = IdType.INPUT)
 5     private Long id;
 6     private String name;
 7     private String address;
 8     private Integer price;
 9     private Integer score;
10     private String brand;
11     private String city;
12     private String starName;
13     private String business;
14     private String longitude;
15     private String latitude;
16     private String pic;
17 }
复制代码

2)将查询结果的数据做成DSL语句

2.1)新增文档的DSL语句如下:

POST /{索引库名}/_doc/1
{
    "name": "Jack",
    "age": 21
}

2.2)创建一个与索引库结构吻合

查询结果的结构与索引库结构存在差异:

  • longitude和latitude需要合并为location
复制代码
 1 @Data
 2 @NoArgsConstructor
 3 public class HotelDoc {
 4     private Long id;
 5     private String name;
 6     private String address;
 7     private Integer price;
 8     private Integer score;
 9     private String brand;
10     private String city;
11     private String starName;
12     private String business;
13     private String location;
14     private String pic;
15 
16     public HotelDoc(Hotel hotel) {
17         this.id = hotel.getId();
18         this.name = hotel.getName();
19         this.address = hotel.getAddress();
20         this.price = hotel.getPrice();
21         this.score = hotel.getScore();
22         this.brand = hotel.getBrand();
23         this.city = hotel.getCity();
24         this.starName = hotel.getStarName();
25         this.business = hotel.getBusiness();
26         this.location = hotel.getLatitude() + ", " + hotel.getLongitude();
27         this.pic = hotel.getPic();
28     }
29 }
复制代码

3)将DB数据同步到elasticsearch

复制代码
 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 
10     // 1.准备Request对象 POST /hotel/_doc/{id}
11     IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
12     // 2.准备Json文档 {"name": "Jack",    "age": 21}
13     request.source(json, XContentType.JSON);
14     // 3.发送请求
15     client.index(request, RequestOptions.DEFAULT);
16 }
复制代码

新增文档步骤

  • 创建请求对象IndexRequest
  • 准备请求参数,也就是DSL中的JSON文档
  • 发送请求,通过索引库的操作对象的index方法发送请求

查询文档

1)查询的DSL语句如下:

GET /索引库名/_doc/{id}

查询结果是一个JSON,其中文档放在一个_source属性中,因此解析就是拿到_source,反序列化为Java对象即可。

2)查询文档

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

查询文档步骤

  • 创建请求对象GetRequest
  • 发送请求,通过索引库的操作对象的get方法发送请求,得到响应(GetResponse response)对象
  • 响应是一个JSON,其中文档放在一个_source属性中,通过通过响应对象的getSourceAsString方法获取_source,反序列化为Java对象即可

删除文档

1)DSL:

DELETE /索引库名/_doc/{id}

2)删除文档

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 }

删除文档步骤

  • 创建请求对象DeleteRequest
  • 发送请求,通过索引库的操作对象的delete方法发送请求

修改文档

修改文档两种方式:

  • 全量修改:本质是先根据id删除,再新增
  • 增量修改:修改文档中的指定字段值

在RestClient的API中,全量修改与新增的API完全一致,判断依据是ID:

  • 如果新增时,ID已经存在,则修改
  • 如果新增时,ID不存在,则新增

修改文档

复制代码
 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 }
复制代码

修改文档步骤

  • 创建请求对象UpdateRequest
  • 准备参数。也就是JSON文档,包含要修改的字段
  • 发送请求,通过索引库的操作对象的update方法发送请求

批量导入文档

案例需求:利用BulkRequest批量将数据库数据导入到索引库中

步骤如下:

  • 利用mybatis-plus查询酒店数据

  • 将查询到的酒店数据(Hotel)转换为文档类型数据(HotelDoc)

  • 利用JavaRestClient中的BulkRequest批处理,实现批量新增文档

语法说明

批量处理BulkRequest,其本质就是将多个普通的CRUD请求组合在一起发送。

 

可以看到,能添加的请求包括:

  • IndexRequest,也就是新增
  • UpdateRequest,也就是修改
  • DeleteRequest,也就是删除

因此Bulk中添加了多个IndexRequest,就是批量新增功能了。示例:

复制代码
 1 @Test
 2     void testBulkRequest() throws IOException {
 3         // 查询所有的酒店数据
 4         List<Hotel> list = hotelService.list();
 5 
 6         // 1.准备Request
 7         BulkRequest request = new BulkRequest();
 8         // 2.准备参数
 9         for (Hotel hotel : list) {
10             // 2.1.转为HotelDoc
11             HotelDoc hotelDoc = new HotelDoc(hotel);
12             // 2.2.转json
13             String json = JSON.toJSONString(hotelDoc);
14             // 2.3.添加请求
15             request.add(new IndexRequest("hotel").id(hotel.getId().toString()).source(json, XContentType.JSON));
16         }
17 
18         // 3.发送请求
19         client.bulk(request, RequestOptions.DEFAULT);
20     }
复制代码

完整代码

复制代码
@SpringBootTest
class HotelDocumentTest {

    private RestHighLevelClient client;

    @Autowired
    private IHotelService hotelService;

    @Test
    void testAddDocument() throws IOException {
        // 1.查询数据库hotel数据
        Hotel hotel = hotelService.getById(61083L);
        // 2.转换为HotelDoc
        HotelDoc hotelDoc = new HotelDoc(hotel);
        // 3.转JSON
        String json = JSON.toJSONString(hotelDoc);

        // 1.准备Request
        IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
        // 2.准备请求参数DSL,其实就是文档的JSON字符串
        request.source(json, XContentType.JSON);
        // 3.发送请求
        client.index(request, RequestOptions.DEFAULT);
    }

    @Test
    void testGetDocumentById() throws IOException {
        // 1.准备Request      // GET /hotel/_doc/{id}
        GetRequest request = new GetRequest("hotel", "61083");
        // 2.发送请求
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        // 3.解析响应结果
        String json = response.getSourceAsString();

        HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
        System.out.println("hotelDoc = " + hotelDoc);
    }

    @Test
    void testDeleteDocumentById() throws IOException {
        // 1.准备Request      // DELETE /hotel/_doc/{id}
        DeleteRequest request = new DeleteRequest("hotel", "61083");
        // 2.发送请求
        client.delete(request, RequestOptions.DEFAULT);
    }

    @Test
    void testUpdateById() throws IOException {
        // 1.准备Request
        UpdateRequest request = new UpdateRequest("hotel", "61083");
        // 2.准备参数
        request.doc(
                "price", "870"
        );
        // 3.发送请求
        client.update(request, RequestOptions.DEFAULT);
    }

    @Test
    void testBulkRequest() throws IOException {
        // 查询所有的酒店数据
        List<Hotel> list = hotelService.list();

        // 1.准备Request
        BulkRequest request = new BulkRequest();
        // 2.准备参数
        for (Hotel hotel : list) {
            // 2.1.转为HotelDoc
            HotelDoc hotelDoc = new HotelDoc(hotel);
            // 2.2.转json
            String json = JSON.toJSONString(hotelDoc);
            // 2.3.添加请求
            request.add(new IndexRequest("hotel").id(hotel.getId().toString()).source(json, XContentType.JSON));
        }

        // 3.发送请求
        client.bulk(request, RequestOptions.DEFAULT);
    }

    @BeforeEach
    void setUp() {
        client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.232.128:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        client.close();
    }
}
View Code
复制代码

 

posted @   一杯水M  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示