Ingest structured data from Google BigQuery tables and queries into Semantica’s KG pipeline.
Extract data from BigQuery tables, queries, and schemas into Semantica with Application Default Credentials or service-account key-file authentication.
Use environment variables (or a .env file with python-dotenv) to keep configuration out of source code. BigQueryIngestor() with no arguments reads from BIGQUERY_* environment variables automatically, once BIGQUERY_PROJECT is set.
Download a JSON key file from the GCP console under
IAM & Admin → Service Accounts → [your service account] → Keys.
Store it outside version control and inject it via a secret manager or
mounted volume.The service account requires at minimum the BigQuery Data Viewer
(roles/bigquery.dataViewer) and BigQuery Job User
(roles/bigquery.jobUser) roles on the project.
data = ingestor.ingest_table( "orders", where="status = 'shipped' AND created_date >= '2024-01-01'", order_by="created_date DESC", limit=50000,)print(f"Fetched {data.row_count} rows from {data.table_name}")
where and order_by accept raw SQL fragments. They are validated against
a blocklist (statement separators, UNION, DML/DDL keywords, comment sequences)
but are intended for trusted, operator-controlled input. Do not pass raw
end-user text directly to these parameters.
# project and dataset on the ingestor default to the connector's values;# you can override them at the call site for cross-project queries.data = ingestor.ingest_table( "daily_sales", project="reporting-project", dataset="warehouse",)
data = ingestor.ingest_query(""" SELECT customer_id, SUM(amount) AS total_amount, COUNT(*) AS order_count FROM `my-project`.`sales`.`orders` WHERE DATE(created_at) >= '2024-01-01' GROUP BY customer_id ORDER BY total_amount DESC LIMIT 1000""")print(f"Query returned {data.row_count} rows")
The query string is passed verbatim to BigQuery. The caller is responsible for
correctness and safety of the SQL.
tables = ingestor.list_tables()print(f"Tables in dataset: {tables}")# ['customers', 'orders', 'products', 'returns']# Or specify a different datasettables = ingestor.list_tables(dataset="analytics", project="my-other-project")
Convert ingested rows to the Semantica document format for use with
GraphBuilder:
documents = ingestor.export_as_documents( data, id_field="order_id", # field to use as document ID text_fields=["customer_name", "product_name", "notes"],)print(f"Created {len(documents)} documents")# Each document:# {# "id": "ORD-12345",# "text": "Alice Smith Widget Pro Shipped on time",# "metadata": {# "source": "bigquery",# "table": "orders",# "project": "my-gcp-project",# "dataset": "sales",# "location": "US",# "row_data": { ... full original row ... }# }# }
Feed the documents directly into GraphBuilder:
from semantica.kg import GraphBuilderbuilder = GraphBuilder()kg = builder.build(documents)
When text_fields is omitted, all str-typed column values in each row are
joined to form the document text. Integer, float, Decimal, and None values
are excluded from the default text composition.
Prefer the context manager for batches of queries — it opens one client on
entry and closes it on exit, so every call inside the with block reuses the
same authenticated session:
ImportError: BigQuery ingestion requires optional dependency 'google-cloud-bigquery'Install the optional extra:
pip install "semantica[db-bigquery]"
google.auth.exceptions.DefaultCredentialsErrorNo credentials were found in the environment. Either:
Run gcloud auth application-default login for local development, or
Set GOOGLE_APPLICATION_CREDENTIALS to the path of a service-account JSON key file, or
Set BIGQUERY_CREDENTIALS_FILE to the path of a service-account JSON key file.
google.api_core.exceptions.ForbiddenThe service account or user account does not have permission to access the
dataset or table. Ensure the account has at minimum:
roles/bigquery.dataViewer on the dataset or project
roles/bigquery.jobUser on the project
ValidationError: Invalid BigQuery project IDProject IDs may contain letters, digits, hyphens, and underscores, and must
start with a letter. Numeric-only or leading-hyphen project IDs are rejected.ValidationError: Invalid table_nameTable and dataset names must start with a letter or underscore and contain
only letters, digits, and underscores. Hyphens are not permitted in table or
dataset names (use underscores instead).Slow queriesUse limit and where to restrict the rows fetched. For large analytical
queries, consider using ingest_query() with a pre-aggregated SQL statement
rather than ingesting raw table rows.