【问题标题】:How do I batch upsert data into Google Cloud Spanner using the Python client library?如何使用 Python 客户端库将数据批量更新插入 Google Cloud Spanner?
【发布时间】:2019-07-08 01:13:42
【问题描述】:

我想将 pandas 数据框的内容插入到 Google Cloud Spanner 数据库中的表中。文档here 建议使用批处理对象的insert_or_update() 方法。

如果批处理对象是通过运行这个来创建的

from google.cloud import spanner_v1
client = spanner_v1.Client()
batch = client.batch()

那么这个对象没有那个方法可用。运行 dir(client) 会给我这些结果

['SCOPE', 
'_SET_PROJECT', 
'__class__', 
'__delattr__', 
'__dict__', 
'__dir__', 
'__doc__', 
'__eq__', 
'__format__', 
'__ge__', 
'__getattribute__', 
'__getstate__', 
'__gt__', 
'__hash__', 
'__init__', 
'__init_subclass__', 
'__le__', 
'__lt__', 
'__module__', 
'__ne__', 
'__new__', 
'__reduce__', 
'__reduce_ex__', 
'__repr__', 
'__setattr__', 
'__sizeof__', 
'__str__', 
'__subclasshook__', 
'__weakref__', 
'_credentials', 
'_database_admin_api', 
'_determine_default', 
'_http', 
'_http_internal', 
'_instance_admin_api', 
'_item_to_instance', 
'copy', 
'credentials', 
'database_admin_api', 
'from_service_account_json', 
'instance', 
'instance_admin_api', 
'list_instance_configs', 
'list_instances', 
'project', 
'project_name', 
'user_agent']

如何在 Spanner 中进行批量更新插入?

【问题讨论】:

    标签: python-3.x google-cloud-platform google-cloud-functions google-cloud-spanner


    【解决方案1】:

    sn-ps 有一个批量插入的例子。我检查了在 sn-p 中创建的批处理对象也有一个 insert_or_update 字段。

    https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/spanner/cloud-client/snippets.py#L72

    ['class', 'delattr', 'dict', 'doc', 'enter', 'exit', 'format', 'getattribute', 'hash', 'init', 'module', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str ', 'subclasshook', 'weakref', '_check_state', '_mutations', '_session', 'commit', 'committed', 'delete', 'insert ', 'insert_or_update', '替换', '更新']

    你可以试试吗?

    【讨论】:

    【解决方案2】:

    如果您有一个 pandas 数据框,这里是一个随机的 5 x 3 列 a、b、c,您可以将数据框转换为列名和行并批量插入。

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame(np.random.randint(low=0, high=10, size=(5, 3)),
                      columns=['a', 'b', 'c'])
    

    您可以通过从 df 中提取列和值并批量插入来将其插入 Google Cloud Spanner。

    from google.cloud import spanner
    
    spanner_client = spanner.Client()
    instance = spanner_client.instance(instance_id)
    database = instance.database(database_id)
    
    columns = df.columns
    values = df.values.tolist()
    
    with database.batch() as batch:
        batch.insert(
            table='table',
            columns=columns
            values=values
        )
    

    【讨论】:

      猜你喜欢
      • 2023-02-13
      • 2021-12-03
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      • 2017-07-09
      • 2017-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多