SpringBoot 批量索引数据到 Elasticsearch - 使用 Bulk API 代码示例
以下是一个使用 Spring Boot 的代码示例,演示如何通过 Bulk API 将数据批量索引到 Elasticsearch。
首先,在 pom.xml 文件中添加以下依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
接下来,在 application.properties 文件中配置 Elasticsearch 的连接信息:
spring.data.elasticsearch.cluster-nodes=localhost:9200
然后,创建一个索引的实体类,例如:
import org.springframework.data.elasticsearch.annotations.Document;
@Document(indexName = 'my_index', type = 'my_type')
public class MyEntity {
private String id;
private String name;
// 其他属性和 getter/setter 方法省略
}
接着,创建一个 Elasticsearch 的 Repository 接口,用于执行索引的操作:
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface MyEntityRepository extends ElasticsearchRepository<MyEntity, String> {
}
最后,在你的业务逻辑中使用该 Repository 接口来进行批量索引操作,例如:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Autowired
private MyEntityRepository myEntityRepository;
public void bulkIndex() {
List<MyEntity> entities = new ArrayList<>();
// 构造要索引的数据
for (int i = 0; i < 1000; i++) {
MyEntity entity = new MyEntity();
entity.setId(UUID.randomUUID().toString());
entity.setName('Entity ' + i);
entities.add(entity);
}
myEntityRepository.saveAll(entities);
}
}
通过调用 myEntityRepository.saveAll(entities) 方法,可以将数据批量索引到 Elasticsearch 中。
请注意,上述代码示例中使用的是 Spring Data Elasticsearch 库,该库提供了一套方便的 API 来与 Elasticsearch 进行交互。你也可以使用其他的 Elasticsearch 客户端库来执行 Bulk API 操作,只需稍作调整即可。
原文地址: https://www.cveoy.top/t/topic/pkld 著作权归作者所有。请勿转载和采集!