是的,BigQuery 可以通过 Cloud Functions 触发器来发送 Pub/Sub 消息。下面是 Python 代码示例:
import base64
import json
from google.cloud import pubsub_v1
def bq_to_pubsub(event, context):
"""Triggered by a change to a BigQuery table.
Args:
event (dict): Event payload.
context (google.cloud.functions.Context): Metadata for the event.
"""
if event['resource']['kind'] == 'bigquery#table':
dataset_id = event['resource']['datasetId']
table_id = event['resource']['tableId']
message = {'dataset_id': dataset_id, 'table_id': table_id}
project_id = 'my-project-id'
topic_name = 'my-topic-name'
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_name)
message_bytes = json.dumps(message).encode('utf-8')
future = publisher.publish(topic_path, data=message_bytes)
print(future.result())
else:
print('Unsupported resource:', event['resource']['kind'])
此代码将监视 BigQuery 表更改,当有更改时,它将创建一个包含表 ID 和数据集 ID 的消息,并将其发送到指定的 Pub/Sub 主题。注意,BigQuery 和 Pub/Sub 必须在同一个 Google Cloud 项目中才能执行此操作。