删除所有小于 Elasticsearch 中某个值的元素

delete all elements which is less than a value in Elasticsearch

我在 Elasticsearch 中保存了以下 json 数据:

   {
   "id":"1234",
   "expirationDate":"17343234234",
   "paths":"http:localhost:9090",
   "work":"software dev",
   "family":{
      "baba":"jams",
      "mother":"ela"
   }
},
{
   "id":"00021",
   "expirationDate":"0123234",
   "paths":"http:localhost:8080",
   "work":"software engi",
   "family":{
      "baba":"stev",
      "mother":"hela"
   }
}

我想在 springdata Elasticsearch

中使用 QueryBuilder 删除其 expirationDate 小于今天的所有 ids 列表

好吧,delete by query 是正确的选择。

POST /{your_index_name}/_delete_by_query
{
  "query": {
    "range": {
      "expirationDate": {
        "lt": "{your_timestamp}"
      }
    }
  } 
}

java client documentation 表示您可以这样构建请求:

BulkByScrollResponse response =
  new DeleteByQueryRequestBuilder(client, DeleteByQueryAction.INSTANCE)
    .filter(QueryBuilders.matchQuery("gender", "male")) 
    .source("persons")                                  
    .get();                                             
long deleted = response.getDeleted();

这标记为supported by Spring-data-elasticsearch since version 3.2

例如,您可以使用 query derivation :

In addition to query methods, query derivation for both count and delete queries is available.

在附录 C 中,您可以看到 IsLessThan 是一个查询派生关键字,这意味着应该立即支持以下内容:

interface YourRepository extends CrudRepository<User, Long> {
  long deleteByExpirationDateIsLessThan(long timestamp);
}

通过使用查询推导,您让 spring 执行(祈祷它会做“正确的事情”)。

但您也可以使用 ElasticsearchRestTemplate#delete(如果您使用的是旧版 ElasticsearchTemplate,效果相同)。

这允许您传入任何 spring-data 查询(本机、字符串或条件)。