ES分布式搜索引擎-RestClient操作索引库

ES分布式搜索引擎-RestClient操作索引库

文章目录

一、利用JavaRestClient实现文档的CRUD

  1. 初始化JavaRestClient

    java 复制代码
    package cn.mannor.hotel;
    
    import org.apache.http.HttpHost;
    import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
    import org.elasticsearch.client.RequestOptions;
    import org.elasticsearch.client.RestClient;
    import org.elasticsearch.client.RestHighLevelClient;
    import org.elasticsearch.client.indices.CreateIndexRequest;
    import org.elasticsearch.client.indices.GetIndexRequest;
    import org.elasticsearch.common.xcontent.XContentType;
    import org.junit.jupiter.api.AfterEach;
    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.Test;
    
    import java.io.IOException;
    
    import static cn.mannor.hotel.constants.HotelConstants.MAPPING_TEMPLATE;
    
    public class HotelDocumentTest {
    
        private RestHighLevelClient restHighLevelClient; // 高级REST客户端,用于与Elasticsearch进行交互
    
    
    
        /**
         * 初始化测试环境,创建并配置RestHighLevelClient实例。
         */
        @BeforeEach
        void setUp() {
            this.restHighLevelClient = new RestHighLevelClient(RestClient.builder(
                    HttpHost.create("http://192.168.12.131:9200") // 设置Elasticsearch的地址和端口
            ));
        }
    
        /**
         * 测试结束后清理资源,关闭RestHighLevelClient实例。
         *
         * @throws IOException 如果关闭客户端时发生IO错误
         */
        @AfterEach
        void tearDown() throws IOException {
            this.restHighLevelClient.close(); // 关闭高级REST客户端,释放资源
        }
    }

!!!:

值得注意的是,由于document中的数据类型与数据库中数据的类型有所不同,比如经纬度---> 数据,所以就需要准备一个专门接受处理过的一个模型,注意新增数据是的代码编写方式。

java 复制代码
package cn.mannor.hotel.pojo;

import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
public class HotelDoc {
 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();
     this.location = hotel.getLatitude() + ", " + hotel.getLongitude();
     this.pic = hotel.getPic();
 }
}
  1. 利用JavaRestClient新增酒店数据

    java 复制代码
    @SpringBootTest
    public class HotelDocumentTest {
    
        private RestHighLevelClient restHighLevelClient; // 高级REST客户端,用于与Elasticsearch进行交互
    
        @Autowired
        private IHotelService iHotelService;
    
        @Test
        void addDocumentTest() throws IOException {
            Hotel hotel = iHotelService.getById(45845L); //获取数据
            HotelDoc hotelDoc = new HotelDoc(hotel);//处理文档中不同的数据类型
            //1.准备request对象
            IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
            //2.准备JOSN文档(由JSON转换过来)
            request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            //3.发送请求
            restHighLevelClient.index(request, RequestOptions.DEFAULT);
        }
    }
  2. 利用JavaRestClient根据id查询酒店数据

    java 复制代码
    @SpringBootTest
    public class HotelDocumentTest {
    
        private RestHighLevelClient restHighLevelClient; // 高级REST客户端,用于与Elasticsearch进行交互
    
        @Autowired
        private IHotelService iHotelService;
    
        @Test
        void getDocumentByIdTest() throws IOException {
    
            //1.准备request对象
            GetRequest request = new GetRequest("hotel", "45845");
    
            //2.发送请求,得到响应
            GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
            //3.解析响应结果
            String json = response.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            System.out.println(hotelDoc);
        }
    
    }
  3. 利用JavaRestClient删除酒店数据

    java 复制代码
    @SpringBootTest
    public class HotelDocumentTest {
    
        private RestHighLevelClient restHighLevelClient; // 高级REST客户端,用于与Elasticsearch进行交互
    
        @Autowired
        private IHotelService iHotelService;
    
        @Test
        void updateDocumentByIdTest() throws IOException {
    
            //1.准备request对象
            UpdateRequest request = new UpdateRequest("hotel", "45845");
            //2.准备文档,键值对形式
            request.doc(
                    "age", 18,
                    "name", "曼诺尔雷迪亚兹"
            );
            //3.发送请求
            restHighLevelClient.update(request, RequestOptions.DEFAULT);
        } 
    }
  4. 利用JavaRestClient修改酒店数据

    java 复制代码
    @SpringBootTest
    public class HotelDocumentTest {
    
        private RestHighLevelClient restHighLevelClient; // 高级REST客户端,用于与Elasticsearch进行交互
    
        @Autowired
        private IHotelService iHotelService;
    
        @Test
        void deleteDocumentByIdTest() throws IOException {
    
            //1.准备request对象
           DeleteRequest request = new DeleteRequest("hotel", "45845");
    
            //2.发送请求
            restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        }
    }

二、使用JavaRestClient批量导入数据到ES

  1. 利用mybatis-plus查询酒店数据

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

  3. 利用JavaRestClient中的Bulk批处理,实现批量新增文档,示例代码如下

    java 复制代码
    @SpringBootTest
    public class HotelDocumentTest {
    
        private RestHighLevelClient restHighLevelClient; // 高级REST客户端,用于与Elasticsearch进行交互
    
        @Autowired
        private IHotelService iHotelService;
    
        @Test
        void bulkDocumentTest() throws IOException {
    
            List<Hotel> hotels = iHotelService.list();
            //1.准备request对象
            BulkRequest request = new BulkRequest();
            //2.准备参数,添加多个Request
            for (Hotel hotel : hotels) {
                HotelDoc hotelDoc = new HotelDoc(hotel);
                request.add(new IndexRequest("hotel")
                        .id(hotelDoc.getId().toString())
                        .source(JSON.toJSONString(hotelDoc), XContentType.JSON));
            }
            //3.发送请求
            restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        }
    }
相关推荐
bubble小拾2 小时前
ElasticSearch高级功能详解与读写性能调优
大数据·elasticsearch·搜索引擎
weixin_453965002 小时前
[单master节点k8s部署]31.ceph分布式存储(二)
分布式·ceph·kubernetes
坎坎坷坷.2 小时前
分布式理论:拜占庭将军问题
分布式
不能放弃治疗3 小时前
重生之我们在ES顶端相遇第 18 章 - Script 使用(进阶)
elasticsearch
hengzhepa3 小时前
ElasticSearch备考 -- Search across cluster
学习·elasticsearch·搜索引擎·全文检索·es
Elastic 中国社区官方博客5 小时前
Elasticsearch:使用 LLM 实现传统搜索自动化
大数据·人工智能·elasticsearch·搜索引擎·ai·自动化·全文检索
慕雪华年6 小时前
【WSL】wsl中ubuntu无法通过useradd添加用户
linux·ubuntu·elasticsearch
Elastic 中国社区官方博客8 小时前
使用 Vertex AI Gemini 模型和 Elasticsearch Playground 快速创建 RAG 应用程序
大数据·人工智能·elasticsearch·搜索引擎·全文检索
极客先躯9 小时前
高级java每日一道面试题-2024年10月3日-分布式篇-分布式系统中的容错策略都有哪些?
java·分布式·版本控制·共识算法·超时重试·心跳检测·容错策略
alfiy9 小时前
Elasticsearch学习笔记(四) Elasticsearch集群安全配置一
笔记·学习·elasticsearch