allocateIds() 如何在 Cloud Datastore 模式下工作?

How does allocateIds() work in Cloud Datastore Mode?

在新的数据存储模式文档中,有 mention of allocateIds() method。但是,除了一个段落之外,没有示例代码说明如何使用此方法。

我试图在每次创建新实体时分配一个 ID,以便我可以将该 ID 保存为实体本身的 属性。

我假设在伪代码中,它是这样工作的:

    user_id = allocateIds(number_id_ids=1)
    user_key = datastore_client.key(kind='User', user_id)
    user = datastore.Entity(key=user_key)
    user.update({ 'user_id': user_id })  # Allows a get_user_by_id() query
    datastore_client.put(user)

allocateIds() 在实践中究竟如何运作?

当您调用 allocateIds() 函数时,它会调用 class Key(object) 的一个新实例,当调用 "Key" 的构造函数时,它会接受您提供的所有参数 allocateIds并通过 _combine_args 方法重新组合它们。这就是生成密钥的原因。

(如果您想自己查看代码)

来源:https://googleapis.dev/python/datastore/latest/_modules/google/cloud/datastore/key.html#Key

是的,allocateIds() 应该适用于您希望从数据存储模式获取 ID 并将其用作 ID 和 属性 值的情况:

from google.cloud import datastore

client = datastore.Client()

# Allocate a single ID in kind User
# Returns list of keys
keys = client.allocate_ids(client.key('User'), 1)

# Get key from list
key = keys[0]
print(key.id)

# Create a User entity using our key
user = datastore.Entity(key)

# Add ID as a field
user.update({
    'user_id': key.id
})

# Commit to database
client.put(user)

# Query based on full key

query = client.query(kind='User')
query.key_filter(user.key, '=')

results = list(query.fetch())
print(results)

对于您只需要一个自动 ID 的大多数其他情况,您可以跳过 allocate_ids:

# Create a User entity
# Use an incomplete key so Datastore assigns an ID
user = datastore.Entity(client.key('User'))

# Add some data
user.update({
    'foo': 'bar'
})

# Datastore allocates an ID when you call client.put
client.put(user)

# user.key now contains an ID
user_id = user.key.id
print(user_id)

# Query with the ID and key

query = client.query(kind='User')
query.key_filter(user.key, '=')

results = list(query.fetch())
print(results)