如何使用Python客户端库将数据批量插入Google Cloud Spanner?

问题描述 投票:0回答:2

我想将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中批量upsert?

python-3.x google-cloud-platform google-cloud-functions google-cloud-spanner
2个回答
3
投票

这些片段有一个批量插入的例子。我检查了在代码段中创建的批处理对象还有一个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' ,'删除','插入','insert_or_update','替换','更新']

你能尝试一下吗?


3
投票

如果您有一个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
    )
© www.soinside.com 2019 - 2024. All rights reserved.