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
相关推荐
尚学教辅学习资料3 分钟前
基于SpringBoot的医药管理系统+LW示例参考
java·spring boot·后端·java毕业设计·医药管理
雷神乐乐19 分钟前
File.separator与File.separatorChar的区别
java·路径分隔符
小刘|24 分钟前
《Java 实现希尔排序:原理剖析与代码详解》
java·算法·排序算法
逊嘘43 分钟前
【Java语言】抽象类与接口
java·开发语言·jvm
筱源源1 小时前
Elasticsearch-linux环境部署
linux·elasticsearch
morris1311 小时前
【SpringBoot】Xss的常见攻击方式与防御手段
java·spring boot·xss·csp
七星静香1 小时前
laravel chunkById 分块查询 使用时的问题
java·前端·laravel
Jacob程序员1 小时前
java导出word文件(手绘)
java·开发语言·word
ZHOUPUYU1 小时前
IntelliJ IDEA超详细下载安装教程(附安装包)
java·ide·intellij-idea
stewie61 小时前
在IDEA中使用Git
java·git