Utilizzare librerie Python open source

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

Caso d'uso Quantità massima di dati Descrizione
bigquery-dataframes Operazioni di elaborazione dei dati e 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 il pushdown lato server. Per ulteriori informazioni, consulta la documentazione su Introduzione a BigQuery DataFrames.
pandas-gbq Elaborazione dei dati basata su Python utilizzando la copia dei dati lato client Limitato 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 Limitato dalla memoria del client Pacchetto Python che racchiude 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 Python DataFrame e ML con l'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. È 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 proprietà per le varie opzioni di configurazione dell'API.

Eseguire query sui dati con la sintassi GoogleSQL

Il seguente esempio 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 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

Il seguente esempio mostra come eseguire una query utilizzando la sintassi SQL precedente. Consulta la guida alla migrazione a GoogleSQL per indicazioni sull'aggiornamento delle 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 di 15-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()

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 vengono fornite classi di configurazione dei job, ad esempio QueryJobConfig, che contengono le proprietà necessarie per configurare job complessi.

Il seguente esempio 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()

Caricamento di un DataFrame pandas in una tabella BigQuery

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

bigquery-dataframes pandas-gbq google-cloud-bigquery
Supporto dei tipi Converte il DataFrame Pandas locale in un bigframes.pandas.DataFrame utilizzando read_pandas (utilizzando Parquet o CSV in background), supportando valori nidificati e di array. Poi lo salvi in una tabella con 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 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 pyarrow, il motore Parquet utilizzato per inviare i dati DataFrame all'API BigQuery, deve essere installato per caricare il DataFrame in una tabella.
Carica configurazioni Utilizza il parametro if_exists ('fail', 'replace' o 'append') quando salvi con to_gbq. Puoi anche specificare uno schema della tabella. Utilizza la classe LoadJobConfig, che contiene proprietà per le varie opzioni di configurazione dell'API.

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 upload_from_dataframe(
    table_id: str = "your-project.your_dataset.your_table_name",
) -> bpd.DataFrame:
    # 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

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 scrivere dati nelle tabelle, non coprono molte delle funzionalità dell'API BigQuery, tra cui:

Risoluzione dei problemi relativi agli 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, puoi utilizzare un massimo di 10 thread perché la dimensione del pool predefinita 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)