【问题标题】:Google Datastore Auto Entity ID generationGoogle Datastore 自动实体 ID 生成
【发布时间】:2019-08-30 15:49:27
【问题描述】:

我想使用 python 在 Apache Beam 管道中获取由 Google Datastore 自动生成的 Google Datastore 的实体 ID(我不能使用 uuid)。

在 Datastore 中构建实体时,我使用以下代码传递实体种类和键值。

from googledatastore import helper as datastore_helper

entity = entity_pb2.Entity()
        datastore_helper.add_key_path(entity.key, entityName.get(), str(uuid.uuid4()))

在上面的代码中,我不能使用uuid.uuid4()根据项目要求随机生成唯一ID。我必须使用 Google Datastore 的自动 ID 生成。经过大量阅读,我仍然不确定将什么传递给数据存储助手以使其在不使用 uuid 的情况下处理唯一 id 生成。请帮忙。

【问题讨论】:

    标签: python google-cloud-datastore google-cloud-dataflow apache-beam


    【解决方案1】:

    这是由 sdk 强加的人为限制,WriteToDatastore 内的 if 语句:

      if client_entity.key.is_partial:
        raise ValueError('Entities to be written to Cloud Datastore must '
                         'have complete keys:\n%s' % client_entity)
    

    https://beam.apache.org/releases/pydoc/2.14.0/_modules/apache_beam/io/gcp/datastore/v1new/datastoreio.html#WriteToDatastore

    数据流步骤可以重新运行几次,所以我认为这个限制是为了防止您在数据存储中生成重复条目。

    WriteToDatastore 背后的函数是来自新的“云数据存储”库https://googleapis.dev/python/datastore/latest/index.htmlbatch.commit()(在write_mutations 中使用apache_beam/io/gcp/datastore/v1/helper.py):

    https://beam.apache.org/releases/pydoc/2.14.0/_modules/apache_beam/io/gcp/datastore/v1new/helper.html#write_mutations

    Cloud Datastore 库中的主要 Client() 类有一个 allocate_ids() 函数: https://googleapis.dev/python/datastore/latest/client.html?highlight=allocate_ids#google.cloud.datastore.client.Client.allocate_ids

    在将实体传递给WriteToDatastore之前,您应该能够使用它为您的实体自动生成 ID

    【讨论】:

    • 我尝试使用 allocate_ids() 但我无法让它生成 ID。你能给我更多关于如何让它返回唯一ID的见解吗?谢谢。
    • 它会抛出异常吗?它返回了什么?
    • 我发现有几个来自不同库的 allocate_ids() 函数。应用商店库在数据流上抛出未找到包错误,并且 googledatastore allocate_ids() 抛出无效参数。你能告诉我一个代码片段,它在调用时从谷歌数据存储中返回 16 位唯一 id 吗?如果我能得到它,它会解决这个问题。
    【解决方案2】:

    在 Cloud Datastore 中,如果在创建实体时省略了实体的数字 id,则数据存储区将使用“种类”生成一个。

    来自云数据存储客户端 API 的 allocateId() 允许您根据不完整/部分密钥生成 ID 块,通常仅在指定命名空间时。然后可以将其用作分配 id 的基础。

    更多信息和一些代码 sn-ps 可以在https://cloud.google.com/datastore/docs/concepts/entities#kinds_and_identifiers找到 还有在

    https://medium.com/google-cloud/entity-groups-ancestors-and-indexes-in-datastore-a-working-example-3ee40cc185ee

    有关谷歌云数据存储助手的 .add_key_path 的使用信息,helper.py 脚本位于https://github.com/GoogleCloudPlatform/google-cloud-datastore/blob/master/python/googledatastore/helper.py

    请参考第 153 行。

    【讨论】:

      猜你喜欢
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      • 1970-01-01
      • 2015-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多