Skip to main content

A library to handle JDBC ingestion from a SQL database in a simple and efficient way.

Project description

spark-jdbc-ingestor

A library to handle JDBC ingestion from an SQL database in a simple and efficient way.

Disclaimer

[!WARNING] This project is provided "as is" without any warranty of any kind, either express or implied. The author assumes no responsibility or liability for any damages or losses resulting from the use of this project. Use at your own risk.

Installing

From a repository:

pip install git+https://github.com/efranceschi/spark-jdbc-ingestor.git

From Pypi:

%pip install spark_jdbc_ingestor

Get started

Importing class

First, import the JdbcIngestor class and initialize an instance, passing an existing spark session, as well as the JDBC URL, username, password, and driver:

from spark_jdbc_ingestor import JdbcIngestor
jdbcIngestor = JdbcIngestor(spark=spark, url=jdbcUrl, user=user, password=password, driver=driver)

Enabling logging (optional)

When investigating certain situations it is a good idea to enable logging to better understand what is happening:

import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s[%(thread)d] - %(levelname)s - %(message)s')

Ingesting Data

Simple ingestion

The simplest way to do an ingestion is by specifying the source table and the target table:

df = (
    jdbcIngestor.from_table("source_table")
    .load()
    .overwrite("destination_table")
)

Using a column to partition the data

You can configure execution parallelism, causing data to be partitioned in a way that distributes the processing load among workers. Just choose a numeric, date, or timestamp column, as well as the number of partitions:

df = (
    jdbcIngestor.from_table("source_table")
    .load(partition_column="mycolumn", num_partitions=16)
    .overwrite("destination_table")
)

Writing the data

You can choose to overwrite:

df = (
    jdbcIngestor.from_table("source_table")
    .load()
    .overwrite("destination_table")
)

or append the data in the destination table:

df = (
    jdbcIngestor.from_table("source_table")
    .load()
    .append("destination_table")
)

Use a query instead of the table name

You can choose to use a query instead of a table. Just make sure you use the correct syntax, as shown in the following example:

df = (
    jdbcIngestor.from_query("(select * from source_table) as my_table")
    .load()
    .overwrite("destination_table")
)

Advanced Ingestion

Partial ingestion using filters

It is possible to perform partial ingestions by pushing predicates down to the JDBC database. This approach is especially useful for performing incremental ingestions, for example, based on dates or sequence identifiers.

The example below demonstrates the ingestion of yesterday's data:

from datetime import datetime, timedelta

yesterday = datetime.now() - timedelta(days=1)
start_date = yesterday.strftime('%Y-%m-%d 00:00:00')
end_date = yesterday.strftime('%Y-%m-%d 23:59:59')

df = (
    jdbcIngestor.from_table("source_table")
    .add_filter(
        f"last_changed between '{start_date}' and '{end_date}'"
    )
    .load()
    .overwrite("destination_table")
)

In this other example, only records with a sequence greater than 1000 are ingested:

last_id = 1000  # Assuming you can get this data from somewhere

df = (
    jdbcIngestor.from_table("source_table")
    .add_filter(
        f"id > {last_id}"
    )
    .load()
    .overwrite("destination_table")
)

You can also use the get last_value() utility function to easily get the largest value in the target database:

last_value = jdbcIngestor.get_last_value(
    table="destination_table",
    column="last_changed",
    default_value="1900-01-01 00:00:00",
)

Or you can combine everything at once:

df = (
    jdbcIngestor.from_table("source_table")
    .with_last_value(
        table="destination_table",
        column="last_changed",
        default_value="1900-01-01 00:00:00",
    )
    .load()
    .append("destination_table")
)

How to choose the best column for partitioning?

If you don't know which column to choose to partition your data, use the analyze() function to obtain statistics and help you make your decision. This function identifies all fields that qualify for partitioning and extracts the following information: min, max, avg, stddev, count, count distinct, as well as uniformity (count distinct / sample count) and completeness (count / sample count). The data is then ranked from the best column to the worst.

jdbcIngestor.from_table("source_table").analyze().show()

Advanced ingestion using threading

Sometimes the size of the tables can be very large. The example below uses threads to perform multiple ingestion operations, using filter push-downs in the source database to manually control the volume of data per day:

import logging
import concurrent.futures
from datetime import datetime, timedelta

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s[%(thread)d] - %(levelname)s - %(message)s')
logger = logging.getLogger("multi-thread-ingestor")

def load_data_between(start_time, end_time):
    try:
        logger.info(f"> Loading data from {start_time} to {end_time}")
        return (
            jdbcIngestor.from_table("source_table")
            .add_filter(f"last_changed between '{start_time}' and '{end_time}'")
            .load(partition_column="id", num_partitions=8)
            .append("destination_table")
        )
    finally:
        logger.info(f"< Finished loading data from {start_time} to {end_time}")

futures = []
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
    current_date, end_date = datetime(2020, 1, 1), datetime(2020, 12, 31)
    while current_date <= end_date:
        futures.append(
            executor.submit(
                load_data_between,
                current_date,
                current_date + timedelta(hours=23, minutes=59, seconds=59),
            )
        )
        current_date += timedelta(days=1)
    concurrent.futures.wait(futures)
    logger.info("Finished!")

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

spark_jdbc_ingestor-1.0.2.tar.gz (14.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

spark_jdbc_ingestor-1.0.2-py3-none-any.whl (10.2 kB view details)

Uploaded Python 3

File details

Details for the file spark_jdbc_ingestor-1.0.2.tar.gz.

File metadata

  • Download URL: spark_jdbc_ingestor-1.0.2.tar.gz
  • Upload date:
  • Size: 14.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for spark_jdbc_ingestor-1.0.2.tar.gz
Algorithm Hash digest
SHA256 3de49d68b234a0f6ae96220c43abe0bfd1d6b8d47ecf012426f7f7f68805c97c
MD5 38da4843682d6566e1e257235bc1f777
BLAKE2b-256 87e1ef3537c8f2f7f0b61b9ff0f4fb4979125048f0381383913158a69d5aa390

See more details on using hashes here.

Provenance

The following attestation bundles were made for spark_jdbc_ingestor-1.0.2.tar.gz:

Publisher: publish.yml on databricks-solutions/spark-jdbc-ingestor

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file spark_jdbc_ingestor-1.0.2-py3-none-any.whl.

File metadata

File hashes

Hashes for spark_jdbc_ingestor-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 d3fef37c41da06b999b1feae96bddbb47eb29aa3436f0d3adf688cdc471a4fda
MD5 15e1e640b98d39c94e74af84ec23dac2
BLAKE2b-256 1b2e59f47e62e5c68d6a6d571b5987491cf3a8c2837e7c0b58a899902fd10ec4

See more details on using hashes here.

Provenance

The following attestation bundles were made for spark_jdbc_ingestor-1.0.2-py3-none-any.whl:

Publisher: publish.yml on databricks-solutions/spark-jdbc-ingestor

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page