2014-01-31 23 views
1

我想将这个前分贝光标code snippet复制到ndb中。 (向下滚动至Updating Existing Entities游标在ndb中如何工作?

我有2700条记录。这个游标背后的想法是遍历所有记录并用不同的键创建新记录。我需要一个开始时的快照,因为我不想让新创建的记录再次出现在光标中。

换句话说,光标只能遍历2700个初始记录。我正在尝试传递光标,但它不起作用。最后我得到了8500条记录。我期待2700 x 2 = 5400.所以它不知道怎么工作。

BATCH_SIZE = 100 # ideal batch size may vary based on entity size. 

def updateRecordSchema(cursor=None, num_updated=0): 
    query = Record.query() 
    records, cursor, more = query.fetch_page(BATCH_SIZE, start_cursor=cursor) 

    to_put = [] 
    to_delete = [] 
    for record in records: 
     new_record = Record(parent = record.user, 
          user = record.user, 
          record_date = record.record_date) 
     to_put.append(new_record) 
     to_delete.append(record) 

    if to_put: 
     ndb.put_multi(to_put) 
     num_updated += len(to_put) 
     logging.debug('Put %d entities to Datastore for a total of %d', len(to_put), num_updated) 
     deferred.defer(updateRecordSchema, cursor=cursor, num_updated=num_updated) 
    else: 
     logging.debug('UpdateSchema complete with %d updates!', num_updated) 

回答

1

这里的问题不是db vs ndb:你会有和db一样运行这段代码的问题。这是因为您添加了新的实体,与文档中仅修改现有文档的版本不同。由于查询没有排序,所以它默认为按键顺序,所以一些新的实体将在光标位置之前,因此在未来的运行中返回(新密钥随机分配,所以不会全部在前)。

要做的最好的事情就是在last_updated字段上添加一个过滤器,如果您的模型中有一个字段,或者可以使用其他字段来区分旧记录和新记录。