【问题标题】:Random value from cloud datastore来自云数据存储的随机值
【发布时间】:2021-12-01 17:52:48
【问题描述】:

我正在编写一个 python 程序来保存和检索云数据存储中的客户数据。我的实体如下所示:

entity.update({
        'customerId': args['customerId'],
        'name': args['name'],
        'email': args['email'],
        'city': args['city'],
        'mobile': args['mobile']
    })
    datastore_client.put(entity)

我已成功保存数据。现在,我想从记录中检索一个随机的电子邮件 ID。我写了以下代码:

def get_customer():
    query = datastore_client.query(kind='CustomerKind')
    results = list(query.fetch())
    chosen_customer = random.choice(results)
    print(chosen_customer)

但是我只得到一个随机的电子邮件 ID,我得到的是这样的整行:

<Entity('CustomerKind', 6206716152643584) {'customerId': '103', 'city': 'bhubaneswar', 'name': 'Amit', 'email': 'amit@gmail.com', 'mobile': '7879546732'}>

谁能建议我怎样才能只得到 'email': 'amit@gmail.com' ?我是数据存储区的新手。

【问题讨论】:

  • 你得到了整个条目。要从中提取,您也许可以使用chosen_customer["email"]

标签: python google-cloud-platform google-cloud-datastore datastore


【解决方案1】:

使用时

query = datastore_client.query(kind='CustomerKind')
results = list(query.fetch())

您正在从将返回的所有实体中检索所有属性。

相反,您可以使用projection query,它允许您仅从实体中检索指定的属性:

query = client.query(kind="CustomerKind")
query.projection = ["email"]
results = list(query.fetch())

对于这种情况,建议使用投影查询,在这种情况下,您只需要一些属性,因为它们reduce cost and latency

【讨论】:

    猜你喜欢
    • 2016-11-14
    • 1970-01-01
    • 2016-06-05
    • 2019-02-13
    • 2013-10-05
    • 1970-01-01
    • 2015-02-10
    • 2012-12-27
    • 1970-01-01
    相关资源
    最近更新 更多