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
相关推荐
风_流沙4 分钟前
java 对ElasticSearch数据库操作封装工具类(对你是否适用嘞)
java·数据库·elasticsearch
ProtonBase33 分钟前
如何从 0 到 1 ,打造全新一代分布式数据架构
java·网络·数据库·数据仓库·分布式·云原生·架构
乐之者v39 分钟前
leetCode43.字符串相乘
java·数据结构·算法
TGB-Earnest2 小时前
【py脚本+logstash+es实现自动化检测工具】
大数据·elasticsearch·自动化
suweijie7684 小时前
SpringCloudAlibaba | Sentinel从基础到进阶
java·大数据·sentinel
公贵买其鹿5 小时前
List深拷贝后,数据还是被串改
java
xlsw_8 小时前
java全栈day20--Web后端实战(Mybatis基础2)
java·开发语言·mybatis
神仙别闹9 小时前
基于java的改良版超级玛丽小游戏
java
黄油饼卷咖喱鸡就味增汤拌孜然羊肉炒饭9 小时前
SpringBoot如何实现缓存预热?
java·spring boot·spring·缓存·程序员
暮湫9 小时前
泛型(2)
java