如何从AppEngine数据存储中删除与查询匹配的实体?

时间:2013-11-24 22:13:39

标签: java google-app-engine google-cloud-datastore

如何从数据存储中删除与查询匹配的实体?有没有办法删除一些与简单查询匹配的对象?比如“之前删除所有带有日期的对象”或者可能删除所有具有值为mail@mail.com的属性电子邮件的实体?

如果有可能,请用java提供答案?

1 个答案:

答案 0 :(得分:1)

不幸的是,Java API不提供删除所有功能。您需要迭代查询结果,而不是删除所有实体。

AsyncDatastoreService ds = DatastoreServiceFactory.getAsyncDatastoreService();

// create query for your kind
Query query = new Query("Kind");

// we don't need anything else than the key
query.setKeysOnly();

// set the filter for date before now 
query.setFilter(
    new FilterPredicate(
        "date", 
        FilterOperator.LESS_THAN_OR_EQUAL, 
        new Date()));

PreparedQuery pq = ds.prepare(query);

// asIterable is more efficient than asList
for (Entity en : pq.asIterable()) {
    // delete each entity
    ds.delete(en.getKey());
}