Skip to main content

Loading Data from Google Cloud Storage to AlloyDB with dlt in Python

tip

We will be using the dlt PostgreSQL destination to connect to AlloyDB. You can get the connection string for AlloyDB from the GCP AlloyDB Console.

Need help deploying these pipelines, or figuring out how to run them in your data stack?

Join our Slack community or book a call with our support engineer Violetta.

This documentation provides a guide for loading data from Google Cloud Storage to AlloyDB using the open-source Python library dlt. Google Cloud Storage is a verified source that seamlessly streams CSV, Parquet, and JSONL files with the reader source. AlloyDB for PostgreSQL is a fully managed, PostgreSQL-compatible database service designed for demanding workloads, including hybrid transactional and analytical processing. It combines a Google-built database engine with a cloud-based, multi-node architecture to deliver enterprise-grade performance, reliability, and availability. The dlt library simplifies the process of transferring data between these services, ensuring efficient and reliable data handling. For more information on Google Cloud Storage, visit their website.

dlt Key Features

- **Governance Support**: `dlt` pipelines offer robust governance support through pipeline metadata utilization, schema enforcement and curation, and schema change alerts. [Learn more](https://dlthub.com/docs/build-a-pipeline-tutorial)
- **Scaling and Finetuning**: `dlt` provides several mechanisms and configuration options to scale up and finetune pipelines, including parallel execution and memory buffer adjustments. [Learn more](https://dlthub.com/docs/reference/performance)
- **Filesystem & Buckets**: Store data in remote file systems and bucket storages like S3, Google Storage, or Azure Blob Storage using `dlt`. [Learn more](https://dlthub.com/docs/dlt-ecosystem/destinations/filesystem)
- **Snowflake and Cloud Storage Integration**: Use Snowflake with S3 or Google Cloud Storage as staging destinations. `dlt` will upload files in the parquet format to the bucket provider and ask Snowflake to copy their data directly into the database. [Learn more](https://dlthub.com/docs/dlt-ecosystem/destinations/snowflake)
- **BigQuery/GCS Staging Support**: BigQuery supports GCS as a file staging destination. `dlt` will upload files in the parquet format to GCS and ask BigQuery to copy their data directly into the database. [Learn more](https://dlthub.com/docs/dlt-ecosystem/destinations/bigquery)

Getting started with your pipeline locally

0. Prerequisites

dlt requires Python 3.8 or higher. Additionally, you need to have the pip package manager installed, and we recommend using a virtual environment to manage your dependencies. You can learn more about preparing your computer for dlt in our installation reference.

1. Install dlt

First you need to install the dlt library with the correct extras for AlloyDB:

pip install "dlt[postgres]"

The dlt cli has a useful command to get you started with any combination of source and destination. For this example, we want to load data from Google Cloud Storage to AlloyDB. You can run the following commands to create a starting point for loading data from Google Cloud Storage to AlloyDB:

# create a new directory
mkdir filesystem_gcs_pipeline
cd filesystem_gcs_pipeline
# initialize a new pipeline with your source and destination
dlt init filesystem postgres
# install the required dependencies
pip install -r requirements.txt

The last command will install the required dependencies for your pipeline. The dependencies are listed in the requirements.txt:


dlt[postgres]>=0.4.3a0
openpyxl>=3.0.0

You now have the following folder structure in your project:

filesystem_gcs_pipeline/
├── .dlt/
│ ├── config.toml # configs for your pipeline
│ └── secrets.toml # secrets for your pipeline
├── filesystem/ # folder with source specific files
│ └── ...
├── filesystem_pipeline.py # your main pipeline script
├── requirements.txt # dependencies for your pipeline
└── .gitignore # ignore files for git (not required)

2. Configuring your source and destination credentials

The dlt cli will have created a .dlt directory in your project folder. This directory contains a config.toml file and a secrets.toml file that you can use to configure your pipeline. The automatically created version of these files look like this:

generated config.toml

# put your configuration values here

[runtime]
log_level="WARNING" # the system log level of dlt
# use the dlthub_telemetry setting to enable/disable anonymous usage data reporting, see https://dlthub.com/docs/telemetry
dlthub_telemetry = true

[sources.filesystem]
bucket_url = "bucket_url" # please set me up!

generated secrets.toml

# put your secret values and credentials here. do not share this file and do not push it to github

[sources.filesystem.credentials]
aws_access_key_id = "aws_access_key_id" # please set me up!
aws_secret_access_key = "aws_secret_access_key" # please set me up!

[destination.postgres]
dataset_name = "dataset_name" # please set me up!

[destination.postgres.credentials]
database = "database" # please set me up!
password = "password" # please set me up!
username = "username" # please set me up!
host = "host" # please set me up!
port = 5432
connect_timeout = 15

2.1. Adjust the generated code to your usecase

Further help setting up your source and destinations
  • Read more about setting up the Google Cloud Storage source in our docs.
  • Read more about setting up the AlloyDB destination in our docs.

The default filesystem source is configured to load from AWS S3. To load to Google Cloud Storage, update the [sources.filesystem.credentials] section in your secrets.toml.

[sources.filesystem.credentials]
client_email="Please set me up!"
private_key="Please set me up!"
project_id="Please set me up!"

You can also set up your bucket_url and file_glob in the config.toml

[sources.filesystem] # use [sources.readers.credentials] for the "readers" source
bucket_url='gcs://my_bucket'
file_glob="*"

3. Running your pipeline for the first time

The dlt cli has also created a main pipeline script for you at filesystem_pipeline.py, as well as a folder filesystem that contains additional python files for your source. These files are your local copies which you can modify to fit your needs. In some cases you may find that you only need to do small changes to your pipelines or add some configurations, in other cases these files can serve as a working starting point for your code, but will need to be adjusted to do what you need them to do.

The main pipeline script will look something like this:


import os
import posixpath
from typing import Iterator

import dlt
from dlt.sources import TDataItems

try:
from .filesystem import FileItemDict, filesystem, readers, read_csv # type: ignore
except ImportError:
from filesystem import (
FileItemDict,
filesystem,
readers,
read_csv,
)


TESTS_BUCKET_URL = posixpath.abspath("../tests/filesystem/samples/")


def stream_and_merge_csv() -> None:
"""Demonstrates how to scan folder with csv files, load them in chunk and merge on date column with the previous load"""
pipeline = dlt.pipeline(
pipeline_name="standard_filesystem_csv",
destination='postgres',
dataset_name="met_data",
)
# met_data contains 3 columns, where "date" column contain a date on which we want to merge
# load all csvs in A801
met_files = readers(
bucket_url=TESTS_BUCKET_URL, file_glob="met_csv/A801/*.csv"
).read_csv()
# tell dlt to merge on date
met_files.apply_hints(write_disposition="merge", merge_key="date")
# NOTE: we load to met_csv table
load_info = pipeline.run(met_files.with_name("met_csv"))
print(load_info)
print(pipeline.last_trace.last_normalize_info)

# now let's simulate loading on next day. not only current data appears but also updated record for the previous day are present
# all the records for previous day will be replaced with new records
met_files = readers(
bucket_url=TESTS_BUCKET_URL, file_glob="met_csv/A801/*.csv"
).read_csv()
met_files.apply_hints(write_disposition="merge", merge_key="date")
load_info = pipeline.run(met_files.with_name("met_csv"))

# you can also do dlt pipeline standard_filesystem_csv show to confirm that all A801 were replaced with A803 records for overlapping day
print(load_info)
print(pipeline.last_trace.last_normalize_info)


def read_csv_with_duckdb() -> None:
pipeline = dlt.pipeline(
pipeline_name="standard_filesystem",
destination='postgres',
dataset_name="met_data_duckdb",
)

# load all the CSV data, excluding headers
met_files = readers(
bucket_url=TESTS_BUCKET_URL, file_glob="met_csv/A801/*.csv"
).read_csv_duckdb(chunk_size=1000, header=True)

load_info = pipeline.run(met_files)

print(load_info)
print(pipeline.last_trace.last_normalize_info)


def read_csv_duckdb_compressed() -> None:
pipeline = dlt.pipeline(
pipeline_name="standard_filesystem",
destination='postgres',
dataset_name="taxi_data",
full_refresh=True,
)

met_files = readers(
bucket_url=TESTS_BUCKET_URL,
file_glob="gzip/*",
).read_csv_duckdb()

load_info = pipeline.run(met_files)
print(load_info)
print(pipeline.last_trace.last_normalize_info)


def read_parquet_and_jsonl_chunked() -> None:
pipeline = dlt.pipeline(
pipeline_name="standard_filesystem",
destination='postgres',
dataset_name="teams_data",
)
# When using the readers resource, you can specify a filter to select only the files you
# want to load including a glob pattern. If you use a recursive glob pattern, the filenames
# will include the path to the file inside the bucket_url.

# JSONL reading (in large chunks!)
jsonl_reader = readers(TESTS_BUCKET_URL, file_glob="**/*.jsonl").read_jsonl(
chunksize=10000
)
# PARQUET reading
parquet_reader = readers(TESTS_BUCKET_URL, file_glob="**/*.parquet").read_parquet()
# load both folders together to specified tables
load_info = pipeline.run(
[
jsonl_reader.with_name("jsonl_team_data"),
parquet_reader.with_name("parquet_team_data"),
]
)
print(load_info)
print(pipeline.last_trace.last_normalize_info)


def read_custom_file_type_excel() -> None:
"""Here we create an extract pipeline using filesystem resource and read_csv transformer"""

# instantiate filesystem directly to get list of files (FileItems) and then use read_excel transformer to get
# content of excel via pandas

@dlt.transformer(standalone=True)
def read_excel(
items: Iterator[FileItemDict], sheet_name: str
) -> Iterator[TDataItems]:
import pandas as pd

for file_obj in items:
with file_obj.open() as file:
yield pd.read_excel(file, sheet_name).to_dict(orient="records")

freshman_xls = filesystem(
bucket_url=TESTS_BUCKET_URL, file_glob="../custom/freshman_kgs.xlsx"
) | read_excel("freshman_table")

load_info = dlt.run(
freshman_xls.with_name("freshman"),
destination='postgres',
dataset_name="freshman_data",
)
print(load_info)


def copy_files_resource(local_folder: str) -> None:
"""Demonstrates how to copy files locally by adding a step to filesystem resource and the to load the download listing to db"""
pipeline = dlt.pipeline(
pipeline_name="standard_filesystem_copy",
destination='postgres',
dataset_name="standard_filesystem_data",
)

# a step that copies files into test storage
def _copy(item: FileItemDict) -> FileItemDict:
# instantiate fsspec and copy file
dest_file = os.path.join(local_folder, item["relative_path"])
# create dest folder
os.makedirs(os.path.dirname(dest_file), exist_ok=True)
# download file
item.fsspec.download(item["file_url"], dest_file)
# return file item unchanged
return item

# use recursive glob pattern and add file copy step
downloader = filesystem(TESTS_BUCKET_URL, file_glob="**").add_map(_copy)

# NOTE: you do not need to load any data to execute extract, below we obtain
# a list of files in a bucket and also copy them locally
# listing = list(downloader)
# print(listing)

# download to table "listing"
# downloader = filesystem(TESTS_BUCKET_URL, file_glob="**").add_map(_copy)
load_info = pipeline.run(
downloader.with_name("listing"), write_disposition="replace"
)
# pretty print the information on data that was loaded
print(load_info)
print(pipeline.last_trace.last_normalize_info)


def read_files_incrementally_mtime() -> None:
pipeline = dlt.pipeline(
pipeline_name="standard_filesystem_incremental",
destination='postgres',
dataset_name="file_tracker",
)

# here we modify filesystem resource so it will track only new csv files
# such resource may be then combined with transformer doing further processing
new_files = filesystem(bucket_url=TESTS_BUCKET_URL, file_glob="csv/*")
# add incremental on modification time
new_files.apply_hints(incremental=dlt.sources.incremental("modification_date"))
load_info = pipeline.run((new_files | read_csv()).with_name("csv_files"))
print(load_info)
print(pipeline.last_trace.last_normalize_info)

# load again - no new files!
new_files = filesystem(bucket_url=TESTS_BUCKET_URL, file_glob="csv/*")
# add incremental on modification time
new_files.apply_hints(incremental=dlt.sources.incremental("modification_date"))
load_info = pipeline.run((new_files | read_csv()).with_name("csv_files"))
print(load_info)
print(pipeline.last_trace.last_normalize_info)


if __name__ == "__main__":
copy_files_resource("_storage")
stream_and_merge_csv()
read_parquet_and_jsonl_chunked()
read_custom_file_type_excel()
read_files_incrementally_mtime()
read_csv_with_duckdb()
read_csv_duckdb_compressed()

Provided you have set up your credentials, you can run your pipeline like a regular python script with the following command:

python filesystem_pipeline.py

4. Inspecting your load result

You can now inspect the state of your pipeline with the dlt cli:

dlt pipeline filesystem_pipeline info

You can also use streamlit to inspect the contents of your AlloyDB destination for this:

# install streamlit
pip install streamlit
# run the streamlit app for your pipeline with the dlt cli:
dlt pipeline filesystem_pipeline show

5. Next steps to get your pipeline running in production

One of the beauties of dlt is, that we are just a plain Python library, so you can run your pipeline in any environment that supports Python >= 3.8. We have a couple of helpers and guides in our docs to get you there:

The Deploy section will show you how to deploy your pipeline to

  • Deploy with GitHub Actions: Learn how to deploy a pipeline using GitHub Actions, a CI/CD runner that you can use for free. Follow the guide here.
  • Deploy with Airflow and Google Composer: Discover how to deploy a pipeline with Airflow and Google Composer, a managed Airflow environment provided by Google. Check out the guide here.
  • Deploy with Google Cloud Functions: Find out how to deploy a pipeline using Google Cloud Functions, a serverless compute service. Read the guide here.
  • Other Deployment Options: Explore additional methods for deploying a pipeline, including various cloud and on-premise solutions. Learn more here.

The running in production section will teach you about:

  • How to Monitor your pipeline: Learn how to effectively monitor your pipeline to ensure smooth operations and quick issue resolution. How to Monitor your pipeline
  • Set up alerts: Set up alerts to get notified about critical issues and changes in your pipeline. Set up alerts
  • Set up tracing: Implement tracing to gain insights into the pipeline's execution and performance metrics. And set up tracing

Additional pipeline guides

This demo works on codespaces. Codespaces is a development environment available for free to anyone with a Github account. You'll be asked to fork the demo repository and from there the README guides you with further steps.
The demo uses the Continue VSCode extension.

Off to codespaces!

DHelp

Ask a question

Welcome to "Codex Central", your next-gen help center, driven by OpenAI's GPT-4 model. It's more than just a forum or a FAQ hub – it's a dynamic knowledge base where coders can find AI-assisted solutions to their pressing problems. With GPT-4's powerful comprehension and predictive abilities, Codex Central provides instantaneous issue resolution, insightful debugging, and personalized guidance. Get your code running smoothly with the unparalleled support at Codex Central - coding help reimagined with AI prowess.