使用 ElasticsearchOperations 从索引中删除所有文档
Delete all documents from index using ElasticsearchOperations
我正在尝试使用以下代码从 ES 的特定索引中删除所有文档:
@Autowired
protected ElasticsearchOperations elasticsearchOperations;
@BeforeEach
void beforeEach() {
Query query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
elasticsearchOperations.delete(query, elasticsearchOperations.getIndexCoordinatesFor(ReviewRequestDocument.class));
}
失败
java.lang.IllegalArgumentException: id must not be null
我很困惑,因为类似的方法适用于计算索引中的文档:
private long countReviewRequestDocuments() {
Query query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
return elasticsearchOperations.count(query, ReviewRequestDocument.class);
}
所以我的问题是从索引中删除所有文档的正确方法是什么?
我找到了解决方案:
@BeforeEach
void beforeEach() {
IndexCoordinates coordinates = elasticsearchOperations.getIndexCoordinatesFor(ReviewRequestDocument.class);
Query query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
String[] ids = elasticsearchOperations.search(query, ReviewRequestDocument.class, coordinates)
.stream()
.map(SearchHit::getId)
.toArray(String[]::new);
Query idsQuery = new NativeSearchQueryBuilder().withQuery(idsQuery().addIds(ids)).build();
elasticsearchOperations.delete(idsQuery, ReviewRequestDocument.class, coordinates);
assertThat(countReviewRequestDocuments()).isZero();
}
看起来ES不允许批量删除索引中的所有文档,所以解决方案是获取id然后将它们传递给删除查询。
从索引中删除所有文档在 Elasticsearch 中效率极低,这不是解决这个问题的方法
你最好删除索引然后从代码重新创建它
我正在尝试使用以下代码从 ES 的特定索引中删除所有文档:
@Autowired
protected ElasticsearchOperations elasticsearchOperations;
@BeforeEach
void beforeEach() {
Query query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
elasticsearchOperations.delete(query, elasticsearchOperations.getIndexCoordinatesFor(ReviewRequestDocument.class));
}
失败
java.lang.IllegalArgumentException: id must not be null
我很困惑,因为类似的方法适用于计算索引中的文档:
private long countReviewRequestDocuments() {
Query query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
return elasticsearchOperations.count(query, ReviewRequestDocument.class);
}
所以我的问题是从索引中删除所有文档的正确方法是什么?
我找到了解决方案:
@BeforeEach
void beforeEach() {
IndexCoordinates coordinates = elasticsearchOperations.getIndexCoordinatesFor(ReviewRequestDocument.class);
Query query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
String[] ids = elasticsearchOperations.search(query, ReviewRequestDocument.class, coordinates)
.stream()
.map(SearchHit::getId)
.toArray(String[]::new);
Query idsQuery = new NativeSearchQueryBuilder().withQuery(idsQuery().addIds(ids)).build();
elasticsearchOperations.delete(idsQuery, ReviewRequestDocument.class, coordinates);
assertThat(countReviewRequestDocuments()).isZero();
}
看起来ES不允许批量删除索引中的所有文档,所以解决方案是获取id然后将它们传递给删除查询。
从索引中删除所有文档在 Elasticsearch 中效率极低,这不是解决这个问题的方法
你最好删除索引然后从代码重新创建它