Utilizza librerie Python open source

Puoi utilizzare le librerie Python open source in BigQuery per elaborare i dati, creare modelli di machine learning (ML) e gestire le tue risorse cloud utilizzando un codice familiare. La scelta della libreria giusta per il tuo workload può aiutarti a scalare in modo efficiente da script lato client leggeri all'elaborazione di terabyte di dati utilizzando il motore lato server di BigQuery.

Raccolta Caso d'uso Quantità massima di dati Descrizione
bigquery-dataframes Trattamento dati basato su Python e operazioni di ML con elaborazione lato server Scalabile per set di dati di più terabyte (pushdown lato server) API Pandas e scikit-learn implementate con pushdown lato server. Per saperne di più, consulta Introduzione a BigQuery DataFrames.
pandas-gbq Trattamento dati basato su Python utilizzando la copia dei dati lato client Limitata dalla memoria del client Consente di spostare i dati da e verso i DataFrame Python sul lato client. Per saperne di più, consulta la documentazione e il codice sorgente.
google-cloud-bigquery Deployment, amministrazione e query basate su SQL di BigQuery Limitata dalla memoria del client Pacchetto Python che aggrega tutte le API BigQuery. Per saperne di più, consulta la documentazione e il codice sorgente.

Utilizzo di BigQuery DataFrames, pandas-gbq e google-cloud-bigquery

La libreria BigQuery DataFrames (bigframes) fornisce un'API DataFrame e ML pythonica con elaborazione delle query lato server. La libreria pandas-gbq fornisce un'interfaccia per l'esecuzione di query e il caricamento di DataFrame pandas in BigQuery. È un wrapper sottile attorno alla libreria client di BigQuery, google-cloud-bigquery.

Installa le librerie

Per utilizzare gli esempi di codice in questa guida, installa i pacchetti bigframes, pandas-gbq e google-cloud-bigquery:

pip install --upgrade bigframes pandas-gbq 'google-cloud-bigquery[bqstorage,pandas]'

Query in corso

Tutte e tre le librerie supportano l'esecuzione di query sui dati archiviati in BigQuery. Le differenze principali tra le librerie includono:

bigquery-dataframes pandas-gbq google-cloud-bigquery
Sintassi SQL predefinita GoogleSQL GoogleSQL (configurabile con pandas_gbq.context.dialect) GoogleSQL
Configurazioni delle query Configurabile utilizzando i parametri bpd.options.bigquery o read_gbq Inviato come dizionario nel formato di una richiesta di query. Utilizza la classe QueryJobConfig, che contiene le proprietà per le varie opzioni di configurazione dell'API.

Esecuzione di query sui dati con la sintassi GoogleSQL

L'esempio seguente mostra come eseguire una query GoogleSQL con e senza specificare esplicitamente un progetto. Per tutte e tre le librerie, se non viene specificato un progetto, questo verrà determinato dalle credenziali predefinite.

bigquery-dataframes

import bigframes.pandas as bpd

# Set partial ordering mode for BigQuery DataFrames.
bpd.options.bigquery.ordering_mode = "partial"


def query_standard_sql(project_id: str = "your-project-id") -> bpd.DataFrame:
    """Runs a standard SQL query using BigQuery DataFrames."""
    sql = """
    SELECT name FROM `bigquery-public-data.usa_names.usa_1910_current`
    WHERE state = 'TX'
    LIMIT 100
    """

    # Run a query alongside existing SQL. The project will be determined from
    # default credentials.
    df = bpd.read_gbq(sql)

    # Run a query after explicitly specifying a project.
    bpd.close_session()
    bpd.options.bigquery.project = project_id
    df = bpd.read_gbq(sql)
    return df


# Run the sample:
# df = query_standard_sql("your-project-id")
# print(df.head())

pandas-gbq

import pandas

sql = """
    SELECT name
    FROM `bigquery-public-data.usa_names.usa_1910_current`
    WHERE state = 'TX'
    LIMIT 100
"""

# Run a Standard SQL query using the environment's default project
df = pandas.read_gbq(sql, dialect="standard")

# Run a Standard SQL query with the project set explicitly
project_id = "your-project-id"
df = pandas.read_gbq(sql, project_id=project_id, dialect="standard")

google-cloud-bigquery

from google.cloud import bigquery

client = bigquery.Client()
sql = """
    SELECT name
    FROM `bigquery-public-data.usa_names.usa_1910_current`
    WHERE state = 'TX'
    LIMIT 100
"""

# Run a Standard SQL query using the environment's default project
df = client.query(sql).to_dataframe()

# Run a Standard SQL query with the project set explicitly
project_id = "your-project-id"
df = client.query(sql, project=project_id).to_dataframe()

Esecuzione di query sui dati con la sintassi SQL precedente

L'esempio seguente mostra come eseguire una query utilizzando la sintassi SQL precedente. Consulta la guida alla migrazione a GoogleSQL per indicazioni su come aggiornare le query a GoogleSQL.

bigquery-dataframes

BigQuery DataFrames non supporta la sintassi SQL precedente. Utilizza invece la sintassi GoogleSQL.

pandas-gbq

import pandas

sql = """
    SELECT name
    FROM [bigquery-public-data:usa_names.usa_1910_current]
    WHERE state = 'TX'
    LIMIT 100
"""

df = pandas.read_gbq(sql, dialect="legacy")

google-cloud-bigquery

from google.cloud import bigquery

client = bigquery.Client()
sql = """
    SELECT name
    FROM [bigquery-public-data:usa_names.usa_1910_current]
    WHERE state = 'TX'
    LIMIT 100
"""
query_config = bigquery.QueryJobConfig(use_legacy_sql=True)

df = client.query(sql, job_config=query_config).to_dataframe()

Utilizzo dell'API BigQuery Storage per scaricare risultati di grandi dimensioni

Utilizza l'API BigQuery Storage per velocizzare i download di risultati di grandi dimensioni da 15 a 31 volte.

bigquery-dataframes

import bigframes.pandas as bpd
import pandas as pd

# Set partial ordering mode for BigQuery DataFrames.
bpd.options.bigquery.ordering_mode = "partial"


def query_bqstorage() -> pd.DataFrame:
    """Queries BigQuery and downloads results using the BigQuery Storage API."""
    sql = """
    SELECT name FROM `bigquery-public-data.usa_names.usa_1910_current`
    WHERE state = 'TX'
    LIMIT 100
    """

    # Read query results into a server-side DataFrame without downloading data.
    df = bpd.read_gbq(sql)

    # When downloading results to an in-memory pandas DataFrame,
    # bigquery-dataframes automatically uses the BigQuery Storage API if
    # installed.
    pandas_df = df.to_pandas()
    return pandas_df


# Run the sample:
# pandas_df = query_bqstorage()
# print(pandas_df.head())

pandas-gbq

import pandas

sql = "SELECT * FROM `bigquery-public-data.irs_990.irs_990_2012`"

# Use the BigQuery Storage API to download results more quickly.
df = pandas.read_gbq(sql, dialect="standard", use_bqstorage_api=True)

google-cloud-bigquery

from google.cloud import bigquery

client = bigquery.Client()
sql = "SELECT * FROM `bigquery-public-data.irs_990.irs_990_2012`"

# The client library uses the BigQuery Storage API to download results to a
# pandas dataframe if the API is enabled on the project, the
# `google-cloud-bigquery-storage` package is installed, and the `pyarrow`
# package is installed.
df = client.query(sql).to_dataframe()

Esecuzione di una query con una configurazione

L'invio di una configurazione con una richiesta API BigQuery è necessario per eseguire determinate operazioni complesse, come l'esecuzione di una query con parametri o la specifica di una tabella di destinazione per archiviare i risultati della query. In bigquery-dataframes (read_gbq) e pandas-gbq, la configurazione deve essere inviata come dizionario nel formato di una richiesta di query. In google-cloud-bigquery, sono fornite classi di configurazione dei job, come QueryJobConfig, che contengono le proprietà necessarie per configurare job complessi.

L'esempio seguente mostra come eseguire una query con parametri denominati.

bigquery-dataframes

import bigframes.pandas as bpd

# Set partial ordering mode for BigQuery DataFrames.
bpd.options.bigquery.ordering_mode = "partial"


def query_parameters() -> bpd.DataFrame:
    """Queries BigQuery using BigQuery DataFrames with query parameters."""
    sql = """
    SELECT name FROM `bigquery-public-data.usa_names.usa_1910_current`
    WHERE state = @state
    LIMIT 100
    """

    query_config = {
        "query": {
            "parameterMode": "NAMED",
            "queryParameters": [
                {
                    "name": "state",
                    "parameterType": {"type": "STRING"},
                    "parameterValue": {"value": "TX"},
                }
            ],
        }
    }

    df = bpd.read_gbq(sql, configuration=query_config)
    return df


# Run the sample:
# df = query_parameters()
# print(df.head())

pandas-gbq

import pandas

sql = """
    SELECT name
    FROM `bigquery-public-data.usa_names.usa_1910_current`
    WHERE state = @state
    LIMIT @limit
"""
query_config = {
    "query": {
        "parameterMode": "NAMED",
        "queryParameters": [
            {
                "name": "state",
                "parameterType": {"type": "STRING"},
                "parameterValue": {"value": "TX"},
            },
            {
                "name": "limit",
                "parameterType": {"type": "INTEGER"},
                "parameterValue": {"value": 100},
            },
        ],
    }
}

df = pandas.read_gbq(sql, configuration=query_config)

google-cloud-bigquery

from google.cloud import bigquery

client = bigquery.Client()
sql = """
    SELECT name
    FROM `bigquery-public-data.usa_names.usa_1910_current`
    WHERE state = @state
    LIMIT @limit
"""
query_config = bigquery.QueryJobConfig(
    query_parameters=[
        bigquery.ScalarQueryParameter("state", "STRING", "TX"),
        bigquery.ScalarQueryParameter("limit", "INTEGER", 100),
    ]
)

df = client.query(sql, job_config=query_config).to_dataframe()

Caricamento di un DataFrame pandas in una tabella BigQuery

Tutte e tre le librerie supportano il caricamento di dati da un DataFrame pandas in una nuova tabella in BigQuery. Le differenze principali includono:

bigquery-dataframes pandas-gbq google-cloud-bigquery
Supporto dei tipi Converte il DataFrame utilizzando read_pandas e lo scrive in una tabella utilizzando to_gbq. Converte il DataFrame in formato CSV prima di inviarlo all'API, che non supporta valori nidificati o di array. Converte il DataFrame in formato Parquet o CSV prima di inviarlo all'API, che supporta valori nidificati e array. Scegli Parquet per i valori di struct e array e CSV per la flessibilità di serializzazione di date e ore. Parquet è la scelta predefinita. Tieni presente che pyarrow, ovvero il motore parquet utilizzato per inviare i dati del DataFrame all'API BigQuery, deve essere installato per caricare il DataFrame in una tabella.
Configurazioni di caricamento Configura il comportamento con i parametri to_gbq, ad esempio if_exists. Facoltativamente, puoi specificare uno schema della tabella. Utilizza la classe LoadJobConfig, che contiene le proprietà per le varie opzioni di configurazione dell'API.

bigquery-dataframes

import bigframes.pandas as bpd
import pandas as pd

# Set partial ordering mode for BigQuery DataFrames.
bpd.options.bigquery.ordering_mode = "partial"


def upload_from_dataframe(
    table_id: str = "your-project.your_dataset.your_table_name",
) -> bpd.DataFrame:
    """Uploads an in-memory pandas DataFrame to a BigQuery table using BigQuery DataFrames."""
    # Create a local pandas DataFrame.
    df = pd.DataFrame(
        {
            "my_string": ["a", "b", "c"],
            "my_int64": [1, 2, 3],
            "my_float64": [4.0, 5.0, 6.0],
        }
    )

    # Convert the local pandas DataFrame to a BigQuery DataFrame.
    bq_df = bpd.read_pandas(df)

    # Write the DataFrame to a BigQuery table.
    bq_df.to_gbq(table_id, if_exists="replace")
    return bq_df


# Run the sample:
# bq_df = upload_from_dataframe("your-project.your_dataset.your_table_name")
# print(bq_df.head())

pandas-gbq

import pandas

df = pandas.DataFrame(
    {
        "my_string": ["a", "b", "c"],
        "my_int64": [1, 2, 3],
        "my_float64": [4.0, 5.0, 6.0],
        "my_timestamp": [
            pandas.Timestamp("1998-09-04T16:03:14"),
            pandas.Timestamp("2010-09-13T12:03:45"),
            pandas.Timestamp("2015-10-02T16:00:00"),
        ],
    }
)
table_id = "my_dataset.new_table"

df.to_gbq(table_id)

google-cloud-bigquery

Il pacchetto google-cloud-bigquery richiede la libreria pyarrow per serializzare un DataFrame pandas in un file Parquet.

Installa il pacchetto pyarrow:

pip install pyarrow

from google.cloud import bigquery
import pandas

df = pandas.DataFrame(
    {
        "my_string": ["a", "b", "c"],
        "my_int64": [1, 2, 3],
        "my_float64": [4.0, 5.0, 6.0],
        "my_timestamp": [
            pandas.Timestamp("1998-09-04T16:03:14"),
            pandas.Timestamp("2010-09-13T12:03:45"),
            pandas.Timestamp("2015-10-02T16:00:00"),
        ],
    }
)
client = bigquery.Client()
table_id = "my_dataset.new_table"
# Since string columns use the "object" dtype, pass in a (partial) schema
# to ensure the correct BigQuery data type.
job_config = bigquery.LoadJobConfig(
    schema=[
        bigquery.SchemaField("my_string", "STRING"),
    ]
)

job = client.load_table_from_dataframe(df, table_id, job_config=job_config)

# Wait for the load job to complete.
job.result()

Funzionalità non supportate da pandas-gbq e bigquery-dataframes

Sebbene le librerie pandas-gbq e bigquery-dataframes forniscano interfacce utili per eseguire query sui dati e scriverli nelle tabelle, non coprono molte delle funzionalità dell'API BigQuery, tra cui, a titolo esemplificativo:

Risoluzione dei problemi del pool di connessioni

Stringa di errore: Connection pool is full, discarding connection: bigquery.googleapis.com. Connection pool size: 10

Se utilizzi l'oggetto client BigQuery predefinito in Python, hai un limite massimo di 10 thread perché la dimensione predefinita del pool per HTTPAdapter Python è 10. Per utilizzare più di 10 connessioni, crea un oggetto requests.adapters.HTTPAdapter personalizzato. Ad esempio:

client = bigquery.Client()
adapter = requests.adapters.HTTPAdapter(pool_connections=128,
pool_maxsize=128,max_retries=3)
client._http.mount("https://",adapter)
client._http._auth_request.session.mount("https://",adapter)
query_job = client.query(QUERY)