在刚才的新增当中,我们是一次新增一条数据。那么如果你将来的数据库里有数千上万的数据,你一次新增一个,那得多麻烦。所以我们还要学习一下批量导入功能。
也就是说批量的把数据库的数据写入索引库。那这里的需求是,首先利用mybatisplus去批量查询酒店数据,然后将查询到的酒店数据,也就是hotel把它转换成我们的hotelDoc文档类型。最后再利用我们的这个Bulk批处理方式实现批量新增:
- @Test
- void testCreateHotelIndex() throws IOException{
- //创建索引库 CreateIndexReqeust
- //1、创建Request对象:
- CreateIndexRequest request = new CreateIndexRequest("hotel");
- //2、请求参数:
- request.source(MAPPING_TEMPLATE, XContentType.JSON);
- //3、发送请求
- client.indices().create(request,RequestOptions.DEFAULT);
- }
-
- //1、创建DeleteIndexRequset
- DeleteIndexReqeust reqeust = new DeleteIndexReqeust("hotel");
- client.indices().delete(reqeust. ReqeustOptions.DEFAULT);
-
- //判读索引库是否存在:
- GetIndexReqeust request = new GetIndexRequest("hotel");
-
- boolean exists = client.indices().exists(reqeust, RequestOptions.DEFAULT);
-
-
-
-
-
- @Test
- void testBulkRequest() throws IOException{
-
- List
hotels = hoteService.list(); - BulkRequest request = new BulkRequest();
- for(Hotel hotel : hotels){
- HotelDoc hotelDoc = new HotelDoc(hotel);
- request.add(new IndexRequest("hotel"))
- .id(hotelDoc.getId().toString())
- .source(JSON.toJSONString(hotelDoc), XContentType.JSON);
- }
- // 发送请求
- client.bulk(request,RequestOptions.DEFAULT);
-
-
-
- }
用Stream+Map转换更优雅:
- @Test
- void testBulkRequest() throws IOException {
- List
hotels = hoteService.list(); - BulkRequest request = new BulkRequest();
-
- hotels.stream()
- .map(hotel -> new HotelDoc(hotel))
- .forEach(hotelDoc -> {
- try {
- request.add(new IndexRequest("hotel")
- .id(hotelDoc.getId().toString())
- .source(JSON.toJSONString(hotelDoc), XContentType.JSON));
- } catch (IOException e) {
- // Handle exception
- e.printStackTrace();
- }
- });
-
- client.bulk(request, RequestOptions.DEFAULT);
- }
其实是把多个 IndexRequest的请求合并到BulkRequest 对象里,然后一次性完成提交,这种就叫批处理,确实没有什么新东西, 就是把以前的那种新增的代码给它合到一起去提交了。
接下来我们就来学习第一种全文检索查询。全文检索查询它会对用户输入的内容做分词以后进行匹配。比较常见的用于这个搜索框的这种搜索

match和multi_match的区别是什么?一个是根据单字段查询,一个是根据多字段。而multi_match参与查询的字段越多,性能越差,建议利用copy to把多个要查的字段拷贝到一个字段当中