ML.PROCESS_DOCUMENT function
in combination with Document AI's layout parser to build a RAG pipeline
based on key information extracted from a PDF file.
ML.PROCESS_DOCUMENT function
to parse the PDF contents into chunks and then write that content to a
BigQuery table.ML.PROCESS_DOCUMENT function, and then writing that content to a
BigQuery table.VECTOR_SEARCH function
on the embeddings to identify semantically similar PDF content.AI.GENERATE function
to generate text, using vector search results to augment the prompt input and
improve results.
In this document, you use the following billable components of Google Cloud:
To generate a cost estimate based on your projected usage,
use the pricing calculator.
When you finish the tasks that are described in this document, you can avoid continued billing by deleting the resources that you created. For more information, see Clean up.
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
roles/resourcemanager.projectCreator), which contains the
resourcemanager.projects.create permission. Learn how to grant
roles.
Verify that billing is enabled for your Google Cloud project.
Enable the BigQuery, BigQuery Connection, Vertex AI, Document AI, and Cloud Storage APIs.
Roles required to enable APIs
To enable APIs, you need the serviceusage.services.enable permission. If you
created the project, then you likely already have this permission through the
Owner role (roles/owner). Otherwise, you can get this permission through the
Service Usage Admin role (roles/serviceusage.serviceUsageAdmin).
Learn how to grant roles.
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
roles/resourcemanager.projectCreator), which contains the
resourcemanager.projects.create permission. Learn how to grant
roles.
Verify that billing is enabled for your Google Cloud project.
Enable the BigQuery, BigQuery Connection, Vertex AI, Document AI, and Cloud Storage APIs.
Roles required to enable APIs
To enable APIs, you need the serviceusage.services.enable permission. If you
created the project, then you likely already have this permission through the
Owner role (roles/owner). Otherwise, you can get this permission through the
Service Usage Admin role (roles/serviceusage.serviceUsageAdmin).
Learn how to grant roles.
Make sure that you have the following role or roles on the project: Storage Admin, Document AI Editor, BigQuery Admin, Project IAM Admin
In the Google Cloud console, go to the IAM page.
Go to IAMIn the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.
In the Google Cloud console, go to the IAM page.
Go to IAMIn the New principals field, enter your user identifier. This is typically the email address for a Google Account.
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
To initialize the gcloud CLI, run the following command:
gcloud initCreate or select a Google Cloud project.
Roles required to select or create a project
roles/resourcemanager.projectCreator), which contains the
resourcemanager.projects.create permission. Learn how to grant
roles.
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace PROJECT_ID with a name for the Google Cloud project you are creating.
Select the Google Cloud project that you created:
gcloud config set project PROJECT_ID
Replace PROJECT_ID with your Google Cloud project name.
Verify that billing is enabled for your Google Cloud project.
Enable the BigQuery, BigQuery Connection, Vertex AI, Document AI, and Cloud Storage APIs:
Roles required to enable APIs
To enable APIs, you need the serviceusage.services.enable permission. If you
created the project, then you likely already have this permission through the
Owner role (roles/owner). Otherwise, you can get this permission through the
Service Usage Admin role (roles/serviceusage.serviceUsageAdmin).
Learn how to grant roles.
gcloud services enable bigquery.googleapis.combigqueryconnection.googleapis.com aiplatform.googleapis.com documentai.googleapis.com storage.googleapis.com
Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
To initialize the gcloud CLI, run the following command:
gcloud initCreate or select a Google Cloud project.
Roles required to select or create a project
roles/resourcemanager.projectCreator), which contains the
resourcemanager.projects.create permission. Learn how to grant
roles.
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace PROJECT_ID with a name for the Google Cloud project you are creating.
Select the Google Cloud project that you created:
gcloud config set project PROJECT_ID
Replace PROJECT_ID with your Google Cloud project name.
Verify that billing is enabled for your Google Cloud project.
Enable the BigQuery, BigQuery Connection, Vertex AI, Document AI, and Cloud Storage APIs:
Roles required to enable APIs
To enable APIs, you need the serviceusage.services.enable permission. If you
created the project, then you likely already have this permission through the
Owner role (roles/owner). Otherwise, you can get this permission through the
Service Usage Admin role (roles/serviceusage.serviceUsageAdmin).
Learn how to grant roles.
gcloud services enable bigquery.googleapis.combigqueryconnection.googleapis.com aiplatform.googleapis.com documentai.googleapis.com storage.googleapis.com
Grant roles to your user account. Run the following command once for each of the following
IAM roles:
roles/storage.admin,
roles/documentai.editor,
roles/bigquery.admin,
roles/resourcemanager.projectIamAdmin
gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE
Replace the following:
PROJECT_ID: Your project ID.USER_IDENTIFIER: The identifier for your user
account. For example, myemail@example.com.
ROLE: The IAM role that you grant to your user account.Create a BigQuery dataset to store your ML model.
In the Google Cloud console, go to the BigQuery page.
In the Explorer pane, click your project name.
Click View actions > Create dataset
On the Create dataset page, do the following:
For Dataset ID, enter bqml_tutorial.
For Location type, select Multi-region, and then select US.
Leave the remaining default settings as they are, and click Create dataset.
To create a new dataset, use the
bq mk --dataset command.
Create a dataset named bqml_tutorial with the data location set to US.
bq mk --dataset \ --location=US \ --description "BigQuery ML tutorial dataset." \ bqml_tutorial
Confirm that the dataset was created:
bq lsCall the datasets.insert
method with a defined dataset resource.
{ "datasetReference": { "datasetId": "bqml_tutorial" } }
Create a Cloud resource connection and get the connection's service account. Create the connection in the same location.
You can skip this step if you either have a default connection configured, or you have the BigQuery Admin role.
Select one of the following options:Go to the BigQuery page.
In the left pane, click Explorer:

If you don't see the left pane, click Expand left pane to open the pane.
In the Explorer pane, expand your project name, and then click Connections.
On the Connections page, click Create connection.
For Connection type, choose Vertex AI remote models, remote functions, BigLake and Spanner (Cloud Resource).
In the Connection ID field, enter a name for your connection.
For Location type, select a location for your connection. The connection should be colocated with your other resources such as datasets.
Click Create connection.
Click Go to connection.
In the Connection info pane, copy the service account ID for use in a later step.
Use the CREATE CONNECTION statement:
In the Google Cloud console, go to the BigQuery page.
In the query editor, enter the following statement:
CREATE CONNECTION [IF NOT EXISTS] `CONNECTION_NAME` OPTIONS ( connection_type = "CLOUD_RESOURCE", friendly_name = "FRIENDLY_NAME", description = "DESCRIPTION" );
Replace the following:
CONNECTION_NAME: the name of the connection in
either the
PROJECT_ID.LOCATION.CONNECTION_ID,
LOCATION.CONNECTION_ID, or
CONNECTION_ID format. If the project or location
are omitted, then they are inferred from the project and location where
the statement is run.
FRIENDLY_NAME (optional): a descriptive name for
the connection.
DESCRIPTION (optional): a description of the
connection.
Click Run.
For more information about how to run queries, see Run an interactive query.
In a command-line environment, create a connection:
bq mk --connection --location=REGION --project_id=PROJECT_ID \ --connection_type=CLOUD_RESOURCE CONNECTION_ID
The --project_id parameter overrides the default project.
Replace the following:
REGION: your
connection regionPROJECT_ID: your Google Cloud project IDCONNECTION_ID: an ID for your
connectionWhen you create a connection resource, BigQuery creates a unique system service account and associates it with the connection.
Troubleshooting: If you get the following connection error, update the Google Cloud SDK:
Flags parsing error: flag --connection_type=CLOUD_RESOURCE: value should be one of...
Retrieve and copy the service account ID for use in a later step:
bq show --connection PROJECT_ID.REGION.CONNECTION_ID
The output is similar to the following:
name properties
1234.REGION.CONNECTION_ID {"serviceAccountId": "connection-1234-9u56h9@gcp-sa-bigquery-condel.iam.gserviceaccount.com"}
Before trying this sample, follow the Python setup instructions in the BigQuery quickstart using client libraries. For more information, see the BigQuery Python API reference documentation.
To authenticate to BigQuery, set up Application Default Credentials. For more information, see Set up authentication for client libraries.
Before trying this sample, follow the Node.js setup instructions in the BigQuery quickstart using client libraries. For more information, see the BigQuery Node.js API reference documentation.
To authenticate to BigQuery, set up Application Default Credentials. For more information, see Set up authentication for client libraries.
Use the
google_bigquery_connection
resource.
To authenticate to BigQuery, set up Application Default Credentials. For more information, see Set up authentication for client libraries.
The following example creates a Cloud resource connection named
my_cloud_resource_connection in the US region:
To apply your Terraform configuration in a Google Cloud project, complete the steps in the following sections.
Set the default Google Cloud project where you want to apply your Terraform configurations.
You only need to run this command once per project, and you can run it in any directory.
export GOOGLE_CLOUD_PROJECT=PROJECT_ID
Environment variables are overridden if you set explicit values in the Terraform configuration file.
Each Terraform configuration file must have its own directory (also called a root module).
.tf extension—for example main.tf. In this
tutorial, the file is referred to as main.tf.
mkdir DIRECTORY && cd DIRECTORY && touch main.tf
If you are following a tutorial, you can copy the sample code in each section or step.
Copy the sample code into the newly created main.tf.
Optionally, copy the code from GitHub. This is recommended when the Terraform snippet is part of an end-to-end solution.
terraform init
Optionally, to use the latest Google provider version, include the -upgrade
option:
terraform init -upgrade
terraform plan
Make corrections to the configuration as necessary.
yes
at the prompt:
terraform apply
Wait until Terraform displays the "Apply complete!" message.
Select one of the following options:
Go to the IAM & Admin page.
Click Grant Access.
The Add principals dialog opens.
In the New principals field, enter the service account ID that you copied earlier.
In the Select a role field, select Document AI, and then select Document AI Viewer.
Click Add another role.
In the Select a role field, select Cloud Storage, and then select Storage Object Viewer.
Click Add another role.
In the Select a role field, search for Agent Platform User.
Click Save.
Use the
gcloud projects add-iam-policy-binding command:
gcloud projects add-iam-policy-binding 'PROJECT_NUMBER' --member='serviceAccount:MEMBER' --role='roles/documentai.viewer' --condition=None gcloud projects add-iam-policy-binding 'PROJECT_NUMBER' --member='serviceAccount:MEMBER' --role='roles/storage.objectViewer' --condition=None gcloud projects add-iam-policy-binding 'PROJECT_NUMBER' --member='serviceAccount:MEMBER' --role='roles/aiplatform.user' --condition=None
Replace the following:
PROJECT_NUMBER: your project number.MEMBER: the service account ID that you
copied earlier.To upload the sample PDF to Cloud Storage, follow these steps:
scf23.pdf sample PDF by going to
https://www.federalreserve.gov/publications/files/scf23.pdf
and clicking download
.scf23.pdf file to the bucket.Create an object table over the PDF file in Cloud Storage:
In the Google Cloud console, go to the BigQuery page.
In the query editor, run the following statement:
CREATE OR REPLACE EXTERNAL TABLE `bqml_tutorial.pdf` WITH CONNECTION `LOCATION.CONNECTION_ID` OPTIONS( object_metadata = 'SIMPLE', uris = ['gs://BUCKET/scf23.pdf']);
Replace the following:
LOCATION: the connection location.CONNECTION_ID: the ID of your
BigQuery connection.
When you view the connection details
in the Google Cloud console, the CONNECTION_ID is the value in the last section of
the fully qualified connection ID that is shown in
Connection ID, for example
projects/myproject/locations/connection_location/connections/myconnection.
BUCKET: the Cloud Storage bucket
containing the scf23.pdf file. The full uri option value should look
similar to ['gs://mybucket/scf23.pdf'].Create a document processor
based on the layout parser processor
in the us multi-region. Copy the prediction endpoint from the
Processor details page to use in the next section.
Create a remote model to access the Document AI processor:
In the Google Cloud console, go to the BigQuery page.
In the query editor, run the following statement:
CREATE OR REPLACE MODEL `bqml_tutorial.parser_model` REMOTE WITH CONNECTION `LOCATION.CONNECTION_ID` OPTIONS(remote_service_type = 'CLOUD_AI_DOCUMENT_V1', document_processor = 'PROCESSOR_ID');
Replace the following:
LOCATION: the connection location.CONNECTION_ID: the ID of your
BigQuery connection.
When you view the connection details
in the Google Cloud console, the CONNECTION_ID is the value in the last section of
the fully qualified connection ID that is shown in
Connection ID, for example
projects/myproject/locations/connection_location/connections/myconnection.
PROCESSOR_ID: the document processor ID. To find
this value, view the processor details,
and then look at the ID row in the Basic Information section.Use the document processor with the ML.PROCESS_DOCUMENT function to parse the
PDF file into chunks, and then write that content to a table. The
ML.PROCESS_DOCUMENT function returns the PDF chunks in JSON format.
In the Google Cloud console, go to the BigQuery page.
In the query editor, run the following statement:
CREATE or REPLACE TABLEbqml_tutorial.chunked_pdfAS ( SELECT * FROM ML.PROCESS_DOCUMENT( MODELbqml_tutorial.parser_model, TABLEbqml_tutorial.pdf, PROCESS_OPTIONS => (JSON '{"layout_config": {"chunking_config": {"chunk_size": 250}}}') ) );
Extract the PDF content and metadata information from the JSON data returned
by the ML.PROCESS_DOCUMENT function, and then write that content to a
table:
In the Google Cloud console, go to the BigQuery page.
In the query editor, run the following statement to parse the PDF content:
CREATE OR REPLACE TABLEbqml_tutorial.parsed_pdfAS ( SELECT uri, JSON_EXTRACT_SCALAR(json , '$.chunkId') AS id, JSON_EXTRACT_SCALAR(json , '$.content') AS content, JSON_EXTRACT_SCALAR(json , '$.pageFooters[0].text') AS page_footers_text, JSON_EXTRACT_SCALAR(json , '$.pageSpan.pageStart') AS page_span_start, JSON_EXTRACT_SCALAR(json , '$.pageSpan.pageEnd') AS page_span_end FROMbqml_tutorial.chunked_pdf, UNNEST(JSON_EXTRACT_ARRAY(ml_process_document_result.chunkedDocument.chunks, '$')) json );
In the query editor, run the following statement to view a subset of the parsed PDF content:
SELECT * FROM `bqml_tutorial.parsed_pdf` ORDER BY id LIMIT 5;
The output is similar to the following:
+-----------------------------------+------+------------------------------------------------------------------------------------------------------+-------------------+-----------------+---------------+ | uri | id | content | page_footers_text | page_span_start | page_span_end | +-----------------------------------+------+------------------------------------------------------------------------------------------------------+-------------------+-----------------+---------------+ | gs://mybucket/scf23.pdf | c1 | •BOARD OF OF FEDERAL GOVERN NOR RESERVE SYSTEM RESEARCH & ANALYSIS | NULL | 1 | 1 | | gs://mybucket/scf23.pdf | c10 | • In 2022, 20 percent of all families, 14 percent of families in the bottom half of the usual ... | NULL | 8 | 9 | | gs://mybucket/scf23.pdf | c100 | The SCF asks multiple questions intended to capture whether families are credit constrained, ... | NULL | 48 | 48 | | gs://mybucket/scf23.pdf | c101 | Bankruptcy behavior over the past five years is based on a series of retrospective questions ... | NULL | 48 | 48 | | gs://mybucket/scf23.pdf | c102 | # Percentiles of the Distributions of Income and Net Worth | NULL | 48 | 49 | +-----------------------------------+------+------------------------------------------------------------------------------------------------------+-------------------+-----------------+---------------+
Generate embeddings for the parsed PDF content and then write them to a table:
In the Google Cloud console, go to the BigQuery page.
In the query editor, run the following statement:
CREATE OR REPLACE TABLE `bqml_tutorial.embeddings` AS ( SELECT *, AI.EMBED(content, endpoint => 'text-embedding-005').result AS embedding FROM bqml_tutorial.parsed_pdf );
Run a vector search against the parsed PDF content.
The following query takes text input, creates an embedding for that input
using the AI.EMBED function, and then uses the VECTOR_SEARCH
function to match the input embedding with the most similar PDF content
embeddings. The results are the top ten PDF chunks that are most related
to changes in family net worth.
Go to the BigQuery page.
In the query editor, run the following SQL statement:
SELECT distance, base.id AS chunk_id, base.page_span_start AS start_page, base.page_span_end AS end_page, base.content FROM VECTOR_SEARCH( TABLE `bqml_tutorial.embeddings`, 'embedding', query_value => AI.EMBED( 'Did the typical family net worth increase? If so, by how much?', endpoint => 'text-embedding-005').result, top_k => 3, OPTIONS => '{"fraction_lists_to_search": 0.01}') ORDER BY distance DESC;
The output is similar to the following:
+----------+----------+------------+----------+-----------------------------------+ | distance | chunk_id | start_page | end_page | content | +----------+----------+------------+----------+-----------------------------------+ | 0.645685 | 26 | 17 | 18 | 18 Between the first quarter of | | | | | | 2019 and the first quarter of... | +----------+----------+------------+----------+-----------------------------------+ | 0.602665 | 30 | 19 | 21 | ## Net Worth by Family | | | | | | Characteristics... | +----------+----------+------------+----------+-----------------------------------+ | 0.599438 | 24 | 17 | 21 | # Net Worth | | | | | | The net improvements in... | +----------+----------+------------+----------+-----------------------------------+
Perform a vector search on the embeddings to identify semantically similar
PDF content, and then use the AI.GENERATE function with the vector
search results to augment the prompt input and improve the text generation
results. In this case, the query uses information from the PDF chunks to answer
a question about the change in family net worth over the past decade.
In the Google Cloud console, go to the BigQuery page.
In the query editor, run the following statement:
SELECT AI.GENERATE( CONCAT('Did the typical family net worth change? How does this compare the SCF survey a decade earlier? Be concise and use the following context:', STRING_AGG(FORMAT("context: %s", base.content), ',\n') ), endpoint => 'gemini-2.5-pro' ).result AS response FROM VECTOR_SEARCH( TABLE `bqml_tutorial.embeddings`, 'embedding', query_value => AI.EMBED( 'Did the typical family net worth increase? If so, by how much?', endpoint => 'text-embedding-005').result, top_k => 3, OPTIONS => '{"fraction_lists_to_search": 0.01}')
The output is similar to the following:
+-------------------------------------------------------------------------+ | response | +-------------------------------------------------------------------------+ | Yes, the typical family net worth changed significantly. | | | | Real median net worth surged 37% between the 2019 and 2022 SCF surveys. | | This contrasts sharply with a decade earlier (2010-2013), when real | | median net worth decreased 2%. | +-------------------------------------------------------------------------+
To avoid incurring charges to your Google Cloud account for the resources used in this tutorial, either delete the project that contains the resources, or keep the project and delete the individual resources.
Delete a Google Cloud project:
gcloud projects delete PROJECT_ID
ML.PROCESS_DOCUMENT function.Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-07-21 UTC.