【发布时间】:2020-03-26 11:37:35
【问题描述】:
我是云大表的初学者,在使用云函数将数据从 pub/sub 写入大表时遇到很大问题。
云函数从 pubsub 获取消息,但问题在于下一步,将其写入 bigtable。
消息在 python 脚本中创建并发送到 pub/sub。
消息的一个例子:
b'{"eda":2.015176,"temperature":33.39,"bvp":-0.49,"x_acc":-36.0,"y_acc":-38.0,"z_acc":-128.0,"heart_rate": 83.78,"iddevice":15.0,"timestamp":"2019-12-01T20:01:36.927Z"}'
为了将它写入 bigtable,我创建了一个表:
from google.cloud import bigtable
from google.cloud.bigtable import column_family
client = bigtable.Client(project="projectid", admin=True)
instance = client.instance("bigtableinstance")
table = instance.table("bigtable1")
print('Creating the {} table.'.format(table))
print('Creating columnfamily cf1 with Max Version GC rule...')
max_versions_rule = column_family.MaxVersionsGCRule(2)
column_family_id = 'cf1'
column_families = {column_family_id: max_versions_rule}
if not table.exists():
table.create(column_families=column_families)
print("Table {} is created.".format(table))
else:
print("Table {} already exists.".format(table))
这没有问题。
现在我尝试使用 main 方法在云函数中使用以下 python 代码通过 pub/sub 将消息写入 bigtable:
import json
import base64
import os
from google.cloud import bigtable
from google.cloud.bigtable import column_family, row_filters
project_id = os.environ.get('projetid', 'UNKNOWN')
INSTANCE = 'bigtableinstance'
TABLE = 'bigtable1'
client = bigtable.Client(project=project_id, admin=True)
instance = client.instance(INSTANCE)
colFamily = "cf1"
def writeToBigTable(table, data):
# Parameters row_key (bytes) – The key for the row being created.
# Returns A row owned by this table.
row_key = data[colFamily]['iddevice'].value.encode()
row = table.row(row_key)
for colFamily in data.keys():
for key in data[colFamily].keys():
row.set_cell(colFamily,
key,
data[colFamily][key])
table.mutate_rows([row])
return data
def selectTable():
stage = os.environ.get('stage', 'dev')
table_id = TABLE + stage
table = instance.table(table_id)
return table
def main(event, context):
data = base64.b64decode(event['data']).decode('utf-8')
print("DATA: {}".format(data))
eda, temperature, bvp, x_acc, y_acc, z_acc, heart_rate, iddevice, timestamp = data.split(',')
table = selectTable()
data = {'eda': eda,
'temperature': temperature,
'bvp': bvp,
'x_acc':x_acc,
'y_acc':y_acc,
'z_acc':z_acc,
'heart_rate':heart_rate,
'iddevice':iddevice,
'timestamp':timestamp}
writeToBigTable(table, data)
print("Data Written: {}".format(data))
我尝试了不同的版本,但找不到解决方案。
感谢您的帮助。
一切顺利
多米尼克
【问题讨论】:
-
因为你是BigTable的初学者,所以我要问你这个问题:你有高吞吐量的顾虑吗?
-
不,没有高吞吐量。它是一个带有小数据集的原型。
-
好的,请注意 BigTable 的成本 ;-)。每秒最多 1M 的写入,您可以为此使用 BigQuery 流写入。
-
能否确保您使用的是最新版本的客户端库,然后使用 table. direct_row(row_key) 而不是 table.row(row_key)
标签: python google-cloud-functions google-cloud-bigtable