首页 > 解决方案 > 使用springboot插入elasticsearch数据流会引发错误“数据流中只允许写入op_type为create的操作”

问题描述

我们正在使用

    @Repository
public interface ElasticSearchExampleRepository
    extends ElasticsearchRepository<ExampleEntity, String> {}

当我们尝试使用 repository.saveAll 进行批量插入以写入数据流时,我们收到以下错误。

 org.springframework.data.elasticsearch.BulkFailureException: Bulk operation has failures. Use ElasticsearchException.getFailedDocuments() for detailed messages [{e4c5f33e-4e96-4e1b-840e-fba413ab5ad1=ElasticsearchException[Elasticsearch exception [type=illegal_argument_exception, reason=only write ops with an op_type of create are allowed in data streams

有没有办法改变op_type to create我们的spring boot java应用程序?

标签: spring-bootelasticsearchspring-data-elasticsearch

解决方案


saveAll为底层批量操作创建数据时,它将单个实体转换为IndexQuery实例(https://github.com/spring-projects/spring-data-elasticsearch/blob/main/src/main/java/org/springframework/data /elasticsearch/core/AbstractElasticsearchTemplate.java#L222-L243)。

一个IndexQuery对象可以有OpType集合,默认是null,导致默认行为。

您需要ElasticsearchOperations.bulkIndex(java.util.List<org.springframework.data.elasticsearch.core.query.IndexQuery>, org.springframework.data.elasticsearch.core.mapping.IndexCoordinates)直接使用该方法而不是使用存储库saveAll方法,并且在构建IndexQuery对象时将其设置OpTypecreate.

不是最舒服的方式,但目前是 Spring Data Elasticsearch 中唯一的一种。


推荐阅读