我使用了 org.elasticsearch:elasticsearch 6.8 版,连接性我使用了 TransportClient。然后我决定升级到 7.6 版,由于 TransportClient 已被弃用,我不得不通过 RestHighLevelClient 使用与弹性的连接。我正在使用存储库来处理 springframework 中的弹性数据。但是现在我没有通过存储库工作的弹性数据存储。我的存储库继承自 ElasticsearchRepository 接口(interface)。我使用标准的 saveAll 方法。
我有一个 MyPostgresModel 列表,我需要将其保存到 Elastic 中。我想快速完成这就是为什么我使用 @Transactional 并将 saveAll 方法与 Iterable 一起使用。 MyPostgresModel 具有 toDocument 方法来返回 MyElasticModel 对象。
这是作品:myElasticRepository.save(users.get(0).toDocument());
这行不通:myElasticRepository.saveAll(() -> users.stream().map(MyPostgresModel::toDocument).iterator());
我不知道。为什么不?这也会返回“缺少类型;7930:缺少类型;7931:..”错误。调试器告诉我弹性响应“400 Bad Request”状态 - 数据验证没有进行。
在我使用 TransportClient 之前一切正常,毕竟 TransportClient 和 RestHighLevelClient 使用一个通用的 ElasticsearchOperations 接口(interface)......
我使用以下配置类进行连接:
@Slf4j
@Configuration
@EnableElasticsearchRepositories(basePackages = "com.project.elastic.repository")
public class ElasticConfig extends AbstractElasticsearchConfiguration {
@Value("${spring.data.elastic.url}")
private String url;
@Override
public RestHighLevelClient elasticsearchClient() {
return RestClients.create(ClientConfiguration.create(url)).rest();
}
}
这是我的弹性模型的示例:
@Data
@Document(indexName = "user", type = "_doc", createIndex = false)
public class ElasticUser {
@Id
private final String id;
private final String address;
private final String firstName;
private final String lastName;
private final List<String> phones;
private final String gender;
public ElasticUser(
@NonNull String id,
@NonNull String address,
@NonNull String firstName,
@NonNull String lastName,
@NonNull List<String> phones,
@Nullable String gender
) {
this.id = id;
this.address = address;
this.firstName = firstName;
this.lastName = lastName;
this.phones = phones;
this.gender = gender;
}
}
服务方式:
@Transactional
public void saveUsers(@NonNull List<PostgresUser> users) {
// myElasticRepository.save(users.get(0).toDocument());
myElasticRepository.saveAll(() -> users.stream().map(PostgresUser::toDocument).iterator());
}
最佳答案
问题出在 Elasticsearch 版本上。我使用了 7.6.2 的客户端,我的弹性是 6.8.6。
关于java - 使用 ElasticsearchRepository 和 RestHighLevelClient 的方法 saveAll(list) 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61054593/