Utilizzare le librerie Python open source

Puoi scegliere tra tre librerie Python in BigQuery, in base al tuo caso d'uso.

Caso d'uso Dimensione massima dei dati Descrizione
bigquery-dataframes Elaborazione dei dati e operazioni di ML basate su Python con elaborazione lato server Scalabile a 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 Elaborazione dei dati basata 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 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 esegue il wrapping di tutte le API BigQuery. Per saperne di più, consulta la documentazione e il codice sorgente.

Utilizzare 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 semplice per l'esecuzione di query e il caricamento di DataFrame pandas in BigQuery. Si tratta di un wrapper sottile intorno alla libreria client BigQuery, google-cloud-bigquery.

Installare 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 principali differenze 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.

Eseguire 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, il progetto verrà determinato dalle credenziali predefinite.

bigquery-dataframes

import bigframes.pandas as bpd

# Set partial ordering mode as the default configuration for BigQuery
# DataFrames.
bpd.options.bigquery.ordering_mode = "partial"


def query_standard_sql(project_id: str = "your-project-id") -> bpd.DataFrame:
    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

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()

Eseguire query sui dati con la sintassi SQL precedente

L'esempio seguente mostra come eseguire una query utilizzando la sintassi SQL precedente. Per indicazioni sull'aggiornamento delle query a GoogleSQL, consulta la guida alla migrazione 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()

Utilizzare l'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 as the default configuration for BigQuery
# DataFrames.
bpd.options.bigquery.ordering_mode = "partial"


def query_bqstorage() -> pd.DataFrame:
    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

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()

Eseguire una query con una configurazione

L'invio di una configurazione con una richiesta dell'API BigQuery è necessario per eseguire determinate operazioni complesse, ad esempio 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, vengono 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 as the default configuration for BigQuery
# DataFrames.
bpd.options.bigquery.ordering_mode = "partial"


def query_parameters() -> bpd.DataFrame:
    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

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()

Caricare un DataFrame pandas in una tabella BigQuery

Sia pandas-gbq che google-cloud-bigquery supportano il caricamento dei dati da un DataFrame pandas a una nuova tabella in BigQuery. Le principali differenze includono le seguenti:

pandas-gbq google-cloud-bigquery
Supporto dei tipi 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 di array. Scegli Parquet per i valori di struct e array e CSV per la flessibilità di serializzazione di data e ora. Parquet è la scelta predefinita. Tieni presente che per caricare il DataFrame in una tabella è necessario installare pyarrow, il motore Parquet utilizzato per inviare i dati del DataFrame all'API BigQuery.
Caricare le configurazioni Facoltativamente, puoi specificare uno schema di tabella. Utilizza la classe LoadJobConfig, che contiene le proprietà per le varie opzioni di configurazione dell'API.

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 l'esecuzione di query sui dati e la scrittura dei dati nelle tabelle, non coprono molte delle funzionalità dell'API BigQuery, tra cui, a titolo esemplificativo:

Risolvere gli errori del pool di connessioni

Error string: Connection pool is full, discarding connection: bigquery.googleapis.com. Connection pool size: 10

Se utilizzi l'oggetto client BigQuery predefinito in Python, sei limitato a un massimo di 10 thread perché la dimensione predefinita del pool per Python HTTPAdapter è 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)