SpringBoot 实现 elasticsearch 索引操作(RestHighLevelClient 的应用)



在这里插入图片描述

RestHighLevelClientElasticsearch 官方提供的Java高级客户端,用于与Elasticsearch集群进行交互和执行各种操作。

主要特点和功能如下

强类型:RestHighLevelClient 提供了强类型的 API,可以在编码过程中获得更好的类型安全性和 IDE 支持。

兼容性:RestHighLevelClient 是 Elasticsearch 官方推荐的 Java 客户端,在 Elasticsearch 版本升级时会保证与 Elasticsearch 的兼容性。

高级功能:RestHighLevelClient 支持 Elasticsearch 的所有高级功能,例如索引、搜索、聚合、分页、批量操作、文档更新、删除等操作。

异步执行:RestHighLevelClient 还支持异步方式执行操作,可以通过提供的异步回调方法处理返回结果。

索引管理:RestHighLevelClient 提供了索引管理相关的 API,包括创建索引、映射定义、设置索引的分片和副本等操作。

搜索与聚合:RestHighLevelClient 支持复杂的搜索和聚合操作,可以使用查询条件、过滤条件、排序、范围查询等来获取所需的数据。

安全认证:RestHighLevelClient 支持配置安全认证信息,例如提供用户名和密码进行身份验证。

执行配置:RestHighLevelClient 可以配置连接超时、请求超时、重试策略等执行参数,以满足特定的需求和优化性能。

RestHighLevelClient是一个功能强大的Java客户端,可以轻松地与Elasticsearch集群进行交互,并支持许多高级功能和配置选项。


来实操吧…

0. 引入依赖

<dependency>
	<groupId>org.elasticsearch.client</groupId>
	<artifactId>elasticsearch-rest-high-level-client</artifactId>
	<version>7.12.1</version>
</dependency>

1. 实例创建与关闭

private RestHighLevelClient client;

void setUp() {
    
    
    this.client = new RestHighLevelClient(RestClient.builder(
            HttpHost.create("http://IP:9200")
    ));
}

void tearDown() throws IOException {
    
    
    this.client.close();
}

2. 创建索引

@RequestMapping("/create")
public String createHotelIndex() throws IOException {
    
    
    setUp();
    // 1.创建Request对象 "name" 是需要创建的索引名 一般在项目中只创建一次 所以这里是写死的
    CreateIndexRequest request = new CreateIndexRequest("name");
    // 2.准备请求的参数:DSL语句
    request.source(MAPPING_TEMPLATE, XContentType.JSON);
    // 3.发送请求
    CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);

    tearDown();

    return createIndexResponse.isAcknowledged() ? "创建成功" : "创建失败";
}

3. 测试索引库存在不存在

@RequestMapping("/testExistsHotelIndex/{indexName}")
public String testExistsHotelIndex(@PathVariable("indexName") String indexName) throws IOException {
    
    

	setUp();
	
	// 1.创建Request对象
	GetIndexRequest request = new GetIndexRequest(indexName);
	// 2.发送请求
	boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
	
	tearDown();
	
	return exists ? "索引库已经存在!" : "索引库不存在!";
}

4. 删除索引库

@RequestMapping("/testDeleteHotelIndex")
void testDeleteHotelIndex() throws IOException {
    
    
    setUp();
    // 1.创建Request对象
    DeleteIndexRequest request = new DeleteIndexRequest("索引名称");
    // 2.发送请求
    client.indices().delete(request, RequestOptions.DEFAULT);
    tearDown();
}

5. 遍历导入数据

不建议遍历导入,这样效率低低

@RequestMapping("/addAll")
public List<HotelDoc> addAll() throws IOException {
    
    
    List<Hotel> list = hotelService.list();
    List<HotelDoc> docList = list.stream().map(p -> new HotelDoc(p)).collect(Collectors.toList());

    setUp();

    for (HotelDoc hotelDoc : docList) {
    
    
        String jsonString = JSON.toJSONString(hotelDoc);
        // 1.准备Request对象
        IndexRequest request = new IndexRequest("索引名称").id(hotelDoc.getId().toString());
        // 2.准备Json文档
        request.source(jsonString, XContentType.JSON);
        // 3.发送请求
        IndexResponse index = client.index(request, RequestOptions.DEFAULT);
        System.out.println(hotelDoc.getName() + ":" + index.status());
    }

    tearDown();
    return null;
}

6. 批量导入数据(推荐)

@RequestMapping("/testBulkRequest")
public void testBulkRequest() throws IOException {
    
    
	List<Hotel> hotels = hotelService.list();
	
	setUp();
	
	// 1.创建Request
	BulkRequest request = new BulkRequest();
	// 2.准备参数,添加多个新增的Request
	for (Hotel hotel : hotels) {
    
    
		// 2.1.转换为文档类型HotelDoc
		HotelDoc hotelDoc = new HotelDoc(hotel);
		// 2.2.创建新增文档的Request对象
		request.add(new IndexRequest("索引名称")
			.id(hotelDoc.getId().toString())
			.source(JSON.toJSONString(hotelDoc), XContentType.JSON));
	}
	// 3.发送请求
	client.bulk(request, RequestOptions.DEFAULT);
	
	tearDown();
}


在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_60915009/article/details/131322097