Generate image embeddings by using the ML.GENERATE_EMBEDDING function
Stay organized with collections
Save and categorize content based on your preferences.
This document shows you how to create a BigQuery ML
remote model
that references a
Vertex AI embedding model.
You then use that model with the
ML.GENERATE_EMBEDDING
function
to create image embeddings by using data from a
BigQuery
object table.
Required roles
To create a connection, you need membership in the following Identity and Access Management (IAM) role:
roles/bigquery.connectionAdmin
To grant permissions to the connection's service account, you need the following permission:
resourcemanager.projects.setIamPolicy
To create an object table, you need the following permissions:
bigquery.tables.create
bigquery.tables.update
bigquery.connections.delegate
To create the model using BigQuery ML, you need the following IAM permissions:
bigquery.jobs.create
bigquery.models.create
bigquery.models.getData
bigquery.models.updateData
bigquery.models.updateMetadata
To run inference, you need the following permissions:
bigquery.tables.getData
on the tablebigquery.models.getData
on the modelbigquery.jobs.create
Before you begin
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the BigQuery, BigQuery Connection, Cloud Storage, and Vertex AI APIs.
Create a dataset
Create a BigQuery dataset to store your object table and 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, type a name for the dataset.
For Location type, select a location for the dataset.
Click Create dataset.
Create a connection
Create a Cloud resource connection and get the connection's service account. Create the connection in the same location as the dataset you created in the previous step.
Select one of the following options:
Go to the BigQuery page.
In the Explorer pane, click
Add data.The Add data dialog opens.
In the Filter By pane, in the Data Source Type section, select Databases.
Alternatively, in the Search for data sources field, you can enter
Vertex AI
.In the Featured data sources section, click Vertex AI.
Click the Vertex AI Models: BigQuery Federation solution card.
In the Connection type list, select Vertex AI remote models, remote functions and BigLake (Cloud Resource).
In the Connection ID field, enter a name for your connection.
Click Create connection.
Click Go to connection.
In the Connection info pane, copy the service account ID for use in a later step.
In a command-line environment, create a connection:
bq mk --connection --location=
REGION --project_id=PROJECT_ID \ --connection_type=CLOUD_RESOURCECONNECTION_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 connection
When 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"}
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.
Prepare Cloud Shell
- Launch Cloud Shell.
-
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.
Prepare the directory
Each Terraform configuration file must have its own directory (also called a root module).
-
In Cloud Shell, create a directory and a new
file within that directory. The filename must have the
.tf
extension—for examplemain.tf
. In this tutorial, the file is referred to asmain.tf
.mkdir
DIRECTORY && cdDIRECTORY && 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.
- Review and modify the sample parameters to apply to your environment.
- Save your changes.
-
Initialize Terraform. You only need to do this once per directory.
terraform init
Optionally, to use the latest Google provider version, include the
-upgrade
option:terraform init -upgrade
Apply the changes
-
Review the configuration and verify that the resources that Terraform is going to create or
update match your expectations:
terraform plan
Make corrections to the configuration as necessary.
-
Apply the Terraform configuration by running the following command and entering
yes
at the prompt:terraform apply
Wait until Terraform displays the "Apply complete!" message.
- Open your Google Cloud project to view the results. In the Google Cloud console, navigate to your resources in the UI to make sure that Terraform has created or updated them.
Give the service account access
Grant the connection's service account the Vertex AI User and Storage Object Viewer roles.
To grant the roles, follow these steps:
Go to the IAM & Admin page.
Click
Add.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 Vertex AI, and then select Vertex AI User.
Click Add another role.
In the Select a role field, choose Cloud Storage, and then select Storage Object Viewer.
Click Save.
Use the
gcloud projects add-iam-policy-binding
command.
gcloud projects add-iam-policy-binding 'PROJECT_NUMBER ' --member='serviceAccount:MEMBER ' --role='roles/aiplatform.user' --condition=None gcloud projects add-iam-policy-binding 'PROJECT_NUMBER ' --member='serviceAccount:MEMBER ' --role='roles/storage.objectViewer' --condition=None
Replace the following:
PROJECT_NUMBER
: the project number of the project in which to grant the role.MEMBER
: the service account ID that you copied earlier.
Create an object table
To analyze images without moving them from Cloud Storage, create an object table.
To create an object table:
Use the
CREATE EXTERNAL TABLE
statement.
In the Google Cloud console, go to the BigQuery Studio page.
In the query editor, enter the following statement:
CREATE EXTERNAL TABLE `
PROJECT_ID .DATASET_ID .TABLE_NAME ` WITH CONNECTION {`PROJECT_ID .REGION .CONNECTION_ID `| DEFAULT} OPTIONS( object_metadata = 'SIMPLE', uris = ['BUCKET_PATH '[,...]], max_staleness =STALENESS_INTERVAL , metadata_cache_mode = 'CACHE_MODE ');Replace the following:
PROJECT_ID
: your project ID.DATASET_ID
: the ID of the dataset that you created.TABLE_NAME
: the name of the object table.REGION
: the region or multi-region that contains the connection.CONNECTION_ID
: the ID of the connection that you created.When you view the connection details in the Google Cloud console, this 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
.To use a default connection, specify
DEFAULT
instead of the connection string containingPROJECT_ID.REGION.CONNECTION_ID
.BUCKET_PATH
: the path to the Cloud Storage bucket that contains the images, in the format['gs://bucket_name/[folder_name/]*']
.The Cloud Storage bucket that you use should be in the same project where you plan to create the model and call the
ML.GENERATE_EMBEDDING
function. If you want to call theML.GENERATE_EMBEDDING
function in a different project than the one that contains the Cloud Storage bucket used by the object table, you must grant the Storage Admin role at the bucket level to theservice-A@gcp-sa-aiplatform.iam.gserviceaccount.com
service account.STALENESS_INTERVAL
: specifies whether cached metadata is used by operations against the object table, and how fresh the cached metadata must be in order for the operation to use it. For more information on metadata caching considerations, see Metadata caching for performance.To disable metadata caching, specify 0. This is the default.
To enable metadata caching, specify an interval literal value between 30 minutes and 7 days. For example, specify
INTERVAL 4 HOUR
for a 4 hour staleness interval. With this value, operations against the table use cached metadata if it has been refreshed within the past 4 hours. If the cached metadata is older than that, the operation retrieves metadata from Cloud Storage instead.CACHE_MODE
: specifies whether the metadata cache is refreshed automatically or manually. For more information on metadata caching considerations, see Metadata caching for performance.Set to
AUTOMATIC
for the metadata cache to be refreshed at a system-defined interval, usually somewhere between 30 and 60 minutes.Set to
MANUAL
if you want to refresh the metadata cache on a schedule you determine. In this case, you can call theBQ.REFRESH_EXTERNAL_METADATA_CACHE
system procedure to refresh the cache.You must set
CACHE_MODE
ifSTALENESS_INTERVAL
is set to a value greater than 0.
Click
Run.
For more information about how to run queries, see Run an interactive query.
Use the
bq mk
command.
bq mk --table \ --external_table_definition=BUCKET_PATH @REGION .CONNECTION_ID \ --object_metadata=SIMPLE \ --max_staleness=STALENESS_INTERVAL \ --metadata_cache_mode=CACHE_MODE \PROJECT_ID :DATASET_ID .TABLE_NAME
Replace the following:
BUCKET_PATH
: the path to the Cloud Storage bucket that contains the images, in the format['gs://bucket_name/[folder_name/]*']
.The Cloud Storage bucket that you use should be in the same project where you plan to create the model and call the
ML.GENERATE_EMBEDDING
function. If you want to call theML.GENERATE_EMBEDDING
function in a different project than the one that contains the Cloud Storage bucket used by the object table, you must grant the Storage Admin role at the bucket level to theservice-A@gcp-sa-aiplatform.iam.gserviceaccount.com
service account.REGION
: the region or multi-region that contains the connection.CONNECTION_ID
: the ID of the connection that you created.When you view the connection details in the Google Cloud console, this 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
.STALENESS_INTERVAL
: specifies whether cached metadata is used by operations against the object table, and how fresh the cached metadata must be in order for the operation to use it. For more information on metadata caching considerations, see Metadata caching for performance.To disable metadata caching, specify 0. This is the default.
To enable metadata caching, specify an interval literal value between 30 minutes and 7 days. For example, specify
INTERVAL 4 HOUR
for a 4 hour staleness interval. With this value, operations against the table use cached metadata if it has been refreshed within the past 4 hours. If the cached metadata is older than that, the operation retrieves metadata from Cloud Storage instead.CACHE_MODE
: specifies whether the metadata cache is refreshed automatically or manually. For more information on metadata caching considerations, see Metadata caching for performance.Set to
AUTOMATIC
for the metadata cache to be refreshed at a system-defined interval, usually somewhere between 30 and 60 minutes.Set to
MANUAL
if you want to refresh the metadata cache on a schedule you determine. In this case, you can call theBQ.REFRESH_EXTERNAL_METADATA_CACHE
system procedure to refresh the cache.You must set
CACHE_MODE
ifSTALENESS_INTERVAL
is set to a value greater than 0.PROJECT_ID
: your project ID.DATASET_ID
: the ID of the dataset that you created.TABLE_NAME
: the name of the object table.
Create a model
In the Google Cloud console, go to the BigQuery page.
Using the SQL editor, create a remote model:
CREATE OR REPLACE MODEL `
PROJECT_ID .DATASET_ID .MODEL_NAME ` REMOTE WITH CONNECTION `PROJECT_ID .REGION .CONNECTION_ID ` OPTIONS (ENDPOINT = 'ENDPOINT ');Replace the following:
PROJECT_ID
: your project ID.DATASET_ID
: the ID of the dataset that you created previously.MODEL_NAME
: the name of the model.REGION
: the region or multi-region that contains the connection.CONNECTION_ID
: the ID of the connection that you created.When you view the connection details in the Google Cloud console, this 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
.ENDPOINT
: the embedding model to use, in this casemultimodalembedding@001
.If you specify a URL as the endpoint when you create the remote model, for example
endpoint = 'https://us-central1-aiplatform.googleapis.com/v1/projects/myproject/locations/us-central1/publishers/google/models/text-embedding-004'
, make sure that the project that you specify in the URL is the project in which you have granted the Vertex AI user role to the connection's. service account.
Generate image embeddings
Generate image embeddings with the
ML.GENERATE_EMBEDDING
function
by using image data from an object table:
SELECT * FROM ML.GENERATE_EMBEDDING( MODEL<var>PROJECT_ID</var>.<var>DATASET_ID</var>.<var>MODEL_NAME</var>
, TABLE<var>PROJECT_ID</var>.<var>DATASET_ID</var>.<var>TABLE_NAME</var>
, STRUCT(FLATTEN_JSON AS flatten_json_output,OUTPUT_DIMENSIONALITY AS output_dimensionality) );
Replace the following:
PROJECT_ID
: your project ID.DATASET_ID
: the ID of the dataset that contains the model.MODEL_NAME
: the name of the remote model over amultimodalembedding@001
model.TABLE_NAME
: the name of the object table that contains the images to embed.FLATTEN_JSON
: aBOOL
value that indicates whether to parse the embedding into a separate column. The default value isTRUE
.OUTPUT_DIMENSIONALITY
: anINT64
value that specifies the number of dimensions to use when generating embeddings. Valid values are128
,256
,512
, and1408
. The default value is1408
. For example, if you specify256 AS output_dimensionality
, then theml_generate_embedding_result
output column contains 256 embeddings for each input value.
Example
The following example shows how to create embeddings for the images in
the images
object table:
SELECT * FROM ML.GENERATE_EMBEDDING( MODEL `mydataset.embedding_model`, TABLE `mydataset.images`, STRUCT(TRUE AS flatten_json_output, 512 AS output_dimensionality) );