本文参考黑马 分布式Elastic search
Elasticsearch是一款非常强大的开源搜索引擎,具备非常多强大功能,可以帮助我们从海量数据中快速找到需要的内容
初始化RestHighLevelClient
为了与索引库操作分离,我们再次参加一个测试类,做两件事情:
文档测试类
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import java.util.List;
/**
 * @author whc
 * @date 2023/2/28 15:01
 */
@SpringBootTest
public class HotelDocumentTest {
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private IHotelService hotelService;
    @BeforeEach
    void setUp() {
           this.restHighLevelClient = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("IP地址:9200")
        ));
    }
    @AfterEach
    void tearDown() throws IOException {
        this.restHighLevelClient.close();
    }
}
 
测试类初始化 RestClient完毕。
下面我们通过RestClient 对 文档进行 增删改查操作,以便更加深层次的理解。
需求: 将酒店数据从数据库查询出来,通过RestClient写入到ElasticSearch中。
实体类与索引库实体类的转换
数据库返回的结果是一个Hotel类型的对象,属性如下:
@Data
@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 longitude;
    private String latitude;
    private String pic;
}
 
那么问题来了,我们的ElasticSearch 索引库的结构与实体类不一致该怎么办?
例如:经纬度,索引库中是 通过location来实现的,通过 , 分割开 。 实体类中则是两个单独的属性。
因此,我们需要定义一个新的对象,将该属性进行合并从而达到我们想要的结果
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();
    }
}
 
语法说明
新增文档的DSL语句如下:
POST /{索引库名}/_doc/1
{
    "name": "Jack",
    "age": 20
}
 
Java代码如下

可以看到与创建索引库类似,同样是三步走:
变化的地方在于,这里直接使用**client.xxx()的API,不再需要client.indices()**了。
完整代码测试新增文档
@Test
void testAddDocument() throws IOException {
    //获取酒店数据
    Hotel hotel = hotelService.getById(36934L);
	HotelDoc hotelDoc = new HotelDoc(hotel);
	//1.创建request对象
    IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
    //2.准备参数
    request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
    //3.发送请求
    restHighLevelClient.index(request, RequestOptions.DEFAULT);
}
 
执行即可。
查询的DSL语句如下:
GET /索引库名/_doc/{id}
 
大致分为2步
不过查询的目的是得到结果,解析为HotelDoc,因此难点是结果的解析。完整代码如下:

可以看到,结果是一个 JSON,其中文档放在一个_source属性中,因此解析就是拿到_source,反序列化为Java对象即可。
与之前类似,也是分为三步
完整代码
@Test
void testGetDocument() throws IOException {
    //1.创建request对象
    GetRequest request = new GetRequest("hotel", "36934");
    //2.发送请求
    GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
    String sourceAsString = response.getSourceAsString();
    System.out.println(sourceAsString);
}
 
结果如下:

修改是分为两种方式:
在RestClient的API中,全量修改与新增的API完全一致,判断依据是ID:
这里我们主要介绍 增量修改
代码示例如下:

与之前类似,主要分为三步
完整代码
@Test
void testUpdateDocument() throws IOException {
    //1.创建request对象
    UpdateRequest request = new UpdateRequest("hotel", "36934");
    //2.准备参数
    request.doc(
        "price", "456",
        "starName", "三钻"
    );
    //3.发送请求
    restHighLevelClient.update(request, RequestOptions.DEFAULT);
}
 
修改结果
执行完毕修改后,再次通过get请求查看修改结果

删除的DSL为是这样的:
DELETE /hotel/_doc/{id}
 
与查询相比,仅仅是请求方式从DELETE变成GET,可以想象Java代码应该依然分为三步:
完整Java代码
@Test
void testDeleteDocument() throws IOException {
    //1.创建request对象
    DeleteRequest request = new DeleteRequest("hotel", "36934");
    //2.发送请求
    restHighLevelClient.delete(request, RequestOptions.DEFAULT);
}
 
查看删除结果
执行完毕后,调用get请求查看结果

需求:利用BulkRequest批量将数据库数据导入到索引库中。
步骤如下:
批量处理BulkRequest,其本质就是将多个普通的CRUD请求组合在一起发送。
其中提供了一个add方法,用来添加其他请求

可以看到,能添加的请求包括:
因此Bulk中添加了多个IndexRequest,就是批量新增功能了。示例:

依旧是分为三步:
导入酒店数据后,将代码改为for循环即可
完整Java代码
@Test
void testBulk() throws IOException {
    //获取酒店数据
    List hotels = hotelService.list();
    //1.创建bulk请求
    BulkRequest request = new BulkRequest();
    //2.添加批量处理的请求
    for (Hotel hotel : hotels) {
        HotelDoc hotelDoc = new HotelDoc(hotel);
        request.add(new IndexRequest("hotel").
                    id(hotel.getId().toString()).source(JSON.toJSONString(hotelDoc), XContentType.JSON));
    }
    //3.发送请求
    restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
}
  
查看执行结果
执行完毕后,执行 以下DSL语句批量查询

执行完毕,导入成功。
以上就是【Bug 终结者】对 微服务分布式搜索引擎 Elastic Search RestClient 操作文档 的简单介绍,ES搜索引擎无疑是最优秀的分布式搜索引擎,使用它,可大大提高项目的灵活、高效性! 技术改变世界!!!
如果这篇【文章】有帮助到你,希望可以给【Bug 终结者】点个赞👍,创作不易,如果有对【后端技术】、【前端领域】感兴趣的小可爱,也欢迎关注❤️❤️❤️ 【Bug 终结者】❤️❤️❤️,我将会给你带来巨大的【收获与惊喜】💝💝💝!
上一篇:vue项目中使用scss