3. 向索引库中导入数据

1. 准备数据库对象

java 复制代码
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("tb_hotel")
public class Hotel {

    @TableId(type = IdType.INPUT)
    private Long id;

    private String name;
    private String address;
    private Integer price;
    private Integer score;
    private String brand;
    private String city;
    private String starName;
    private String business;
    private String latitude;
    private String longitude;
    private String pic;
}

2. 准备文档对象

java 复制代码
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 与索引库的doc保持一致
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("tb_hotel")
public class HotelDoc {

    @TableId(type = IdType.INPUT)
    private Long id;

    private String name;
    private String address;
    private Integer price;
    private Integer score;
    private String brand;
    private String city;
    private String starName;
    private String business;
    private String location;    //地理坐标
    private String pic;

    public HotelDoc(Hotel hotel){
        this.id = hotel.getId();
        this.name = hotel.getName();
        this.address = hotel.getAddress();
        this.price = hotel.getPrice();
        this.score = hotel.getScore();
        this.brand = hotel.getBrand();
        this.city = hotel.getCity();
        this.starName = hotel.getStarName();
        this.business = hotel.getBusiness();
        //整合地理对象和es中的mappings保持一致
        this.location = hotel.getLatitude() + "," + hotel.getLongitude();
        this.pic = hotel.getPic();
    }
}

3. 向es中插入数据

java 复制代码
//向es中插入数据
    @GetMapping("inserDoc")
    public void inserDoc() throws IOException {
        List<Hotel> hotels = hotelMapper.selectList(null);
        for (int i = 0; i < hotels.size(); i++) {
            //doc准备
            Hotel hotel = hotels.get(i);
            HotelDoc hotelDoc = new HotelDoc(hotel);
            //准备request对象
            IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
            //本人使用的是7.8.0版本,但是依赖用的是6.8.6,因此加入默认的type类型为:_doc,否则会插入失败
            request.type("_doc");
            //准备json文档
            request.source(JSON.toJSONString(hotelDoc),XContentType.JSON);
            //发送请求
            restHighLevelClient.index(request,RequestOptions.DEFAULT);
        }
    }

4. 根据文档id查询文档记录

java 复制代码
@GetMapping("getDocById")
    public void getDocById() throws IOException {
        //1. 创建request对象
        GetRequest request = new GetRequest("hotel");
        request.id("1");//doc = 1
        request.type("_doc");
        //2.发送请求
        GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        String json = response.getSourceAsString();
        System.out.println(json);
    }
java 复制代码
2023-06-23 13:14:21.142  INFO 11932 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
{"address":"柳州东路1号","brand":"如家","business":"弘阳商圈","city":"南京市浦口区","id":1,"location":"33.33,131.33","name":"如家","pic":"http://www.bai.com/images/rujia.png","price":189,"score":7,"starName":"二星级"}
Disconnected from the target VM, address: '127.0.0.1:64333', transport: 'socket'

5 根据文档id更新文档

忍不了,升级了依赖到7.8.0

java 复制代码
// 根据id修改数据
    @GetMapping("updateDocById")
    public void updateDocById() throws IOException {
        //1. 创建request对象
        UpdateRequest request = new UpdateRequest("hotel","1");
        request.doc(
                "name","jack",
                "age",22
        );
        //2.发送请求
        UpdateResponse update = restHighLevelClient.update(request, RequestOptions.DEFAULT);
        System.out.println(update.getResult());
    }

更新结果

java 复制代码
2024-06-23 13:31:42.279  INFO 13972 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2024-06-23 13:31:42.279  INFO 13972 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2024-06-23 13:31:42.281  INFO 13972 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 2 ms
UPDATED
2024-06-23 13:32:08.321 ERROR 13972 --- [rRegistryThread] c.xxl.job.core.util.XxlJobRemotingUtil   : Connection refused: connect

6 删除文档

java 复制代码
//删除文档
    @GetMapping("delDocById")
    public void delDocById() throws IOException {
        //1. 创建request对象
        DeleteRequest request = new DeleteRequest("hotel","1");
        //2.发送请求
        DeleteResponse delete = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.getResult());
    }

删除成功

java 复制代码
2024-06-23 13:36:22.696  INFO 19580 --- [rRegistryThread] c.x.j.c.thread.ExecutorRegistryThread    : >>>>>>>>>>> xxl-job registry fail, registryParam:RegistryParam{registryGroup='EXECUTOR', registryKey='myXxlJob', registryValue='http://192.168.1.15:8088/'}, registryResult:ReturnT [code=500, msg=xxl-rpc remoting error(Connection refused: connect), for url : http://localhost:18080/xxl-job-admin/api/registry, content=null]
DELETED
2024-06-23 13:36:54.769 ERROR 19580 --- [rRegistryThread] c.xxl.job.core.util.XxlJobRemotingUtil   : Connection refused: connect

7 批量导入

java 复制代码
//批量数据导入
    @GetMapping("batchInsert")
    public void batchInsert() throws IOException {
        List<Hotel> hotels = hotelMapper.selectList(null);
        BulkRequest request = new BulkRequest();
        for (int i = 0; i < hotels.size(); i++) {
            request.add(new IndexRequest("hotel")
                    .id(hotels.get(i).getId().toString())
                    .source(JSON.toJSONString(hotels.get(i)),XContentType.JSON));
        }
        BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        System.out.println(bulk.status());
        System.out.println(bulk.getTook());
    }

插入成功

java 复制代码
2024-06-23 13:45:46.866  WARN 13928 --- [nio-8080-exec-2] com.zaxxer.hikari.util.DriverDataSource  : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.
2024-06-23 13:45:46.955  INFO 13928 --- [nio-8080-exec-2] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
OK
73ms
2024-06-23 13:45:58.035 ERROR 13928 --- [rRegistryThread] c.xxl.job.core.util.XxlJobRemotingUtil   : Connection refused: connect
相关推荐
天天扭码14 分钟前
五天SpringCloud计划——DAY2之单体架构和微服务架构的选择和转换原则
java·spring cloud·微服务·架构
程序猿进阶15 分钟前
堆外内存泄露排查经历
java·jvm·后端·面试·性能优化·oom·内存泄露
FIN技术铺20 分钟前
Spring Boot框架Starter组件整理
java·spring boot·后端
小曲程序27 分钟前
vue3 封装request请求
java·前端·typescript·vue
陈王卜44 分钟前
django+boostrap实现发布博客权限控制
java·前端·django
小码的头发丝、1 小时前
Spring Boot 注解
java·spring boot
java亮小白19971 小时前
Spring循环依赖如何解决的?
java·后端·spring
飞滕人生TYF1 小时前
java Queue 详解
java·队列
武子康1 小时前
大数据-230 离线数仓 - ODS层的构建 Hive处理 UDF 与 SerDe 处理 与 当前总结
java·大数据·数据仓库·hive·hadoop·sql·hdfs
武子康1 小时前
大数据-231 离线数仓 - DWS 层、ADS 层的创建 Hive 执行脚本
java·大数据·数据仓库·hive·hadoop·mysql