How to perform bulk update on AppEngine Datastore

醉酒当歌 提交于 2019-12-22 17:55:38

问题


The following code is not working. Does anyone know how I might get it to work?

Query q = new Query("Product");
    Iterable<Entity> entities = datastore.prepare(q).asIterable();
    for (Entity entity : datastore.prepare(q).asIterable()) {
        entity.setProperty(“sale”, false);
    }
    datastore.put(entities);

sale is a completely new field that I am adding to the entity kind. So it does not exist yet.

UPDATE

I fixed it as below but the code is still not working

Query q = new Query("Product");
    Iterable<Entity> entities = datastore.prepare(q).asIterable();
    for (Entity entity : entities) {
        entity.setProperty(“sale”, false);
    }
    datastore.put(entities);

回答1:


Maybe someone else can explain to you why exactly it does not work, but I know how to make it work.

For some reason the entities iterable does not behave like a proper Java collection. In a Java collection, the elements are pointers. But for whatever reason, here each entity that you get inside the for-loop is an independent deep copy. So instead, do the following and it will work

    Query q = new Query("Product");
    List<Entity> products = new ArrayList<Entity>();
    for (Entity entity : datastore.prepare(q).asIterable()) {
        entity.setProperty("sale", false);
        products.add(entity);
    }
    datastore.put(products);



回答2:


There is an error in your code. You never update entities. It should be:

Query q = new Query("Product");
List<Entity> entities = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());

for (Entity entity : entities) {
    entity.setProperty(“sale”, false);
}
datastore.put(entities);


来源:https://stackoverflow.com/questions/28116488/how-to-perform-bulk-update-on-appengine-datastore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!