Generate text embeddings by using the ML.GENERATE_EMBEDDING function

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 text embeddings by using data from a BigQuery standard 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 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 table
    • bigquery.models.getData on the model
    • bigquery.jobs.create

Before you begin

  1. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  2. Make sure that billing is enabled for your Google Cloud project.

  3. Enable the BigQuery, BigQuery Connection, and Vertex AI APIs.

    Enable the APIs

Create a dataset

Create a BigQuery dataset to store your ML model:

  1. In the Google Cloud console, go to the BigQuery page.

    Go to the BigQuery page

  2. In the Explorer pane, click your project name.

  3. Click View actions > Create dataset.

    Create dataset.

  4. On the Create dataset page, do the following:

    • For Dataset ID, enter bqml_tutorial.

    • For Location type, select Multi-region, and then select US (multiple regions in United States).

      The public datasets are stored in the US multi-region. For simplicity, store your dataset in the same location.

    • Leave the remaining default settings as they are, and click Create dataset.

      Create dataset page.

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:

Console

  1. Go to the BigQuery page.

    Go to BigQuery

  2. To create a connection, click Add, and then click Connections to external data sources.

  3. In the Connection type list, select Vertex AI remote models, remote functions and BigLake (Cloud Resource).

  4. In the Connection ID field, enter a name for your connection.

  5. Click Create connection.

  6. Click Go to connection.

  7. In the Connection info pane, copy the service account ID for use in a later step.

bq

  1. 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 region
    • PROJECT_ID: your Google Cloud project ID
    • CONNECTION_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...
    
  2. 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"}
    

Terraform

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:


# This queries the provider for project information.
data "google_project" "default" {}

# This creates a cloud resource connection in the US region named my_cloud_resource_connection.
# Note: The cloud resource nested object has only one output field - serviceAccountId.
resource "google_bigquery_connection" "default" {
  connection_id = "my_cloud_resource_connection"
  project       = data.google_project.default.project_id
  location      = "US"
  cloud_resource {}
}

To apply your Terraform configuration in a Google Cloud project, complete the steps in the following sections.

Prepare Cloud Shell

  1. Launch Cloud Shell.
  2. 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).

  1. In Cloud Shell, create a directory and a new file within that directory. The filename must have the .tf extension—for example main.tf. In this tutorial, the file is referred to as main.tf.
    mkdir DIRECTORY && cd DIRECTORY && touch main.tf
  2. 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.

  3. Review and modify the sample parameters to apply to your environment.
  4. Save your changes.
  5. 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

  1. 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.

  2. 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.

  3. 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 role.

If you plan to specify the endpoint as a URL 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', grant this role in the same project you specify in the URL.

If you plan to specify the endpoint by using the model name when you create the remote model, for example endpoint = 'text-embedding-004', grant this role in the same project where you plan to create the remote model.

Granting the role in a different project results in the error bqcx-1234567890-xxxx@gcp-sa-bigquery-condel.iam.gserviceaccount.com does not have the permission to access resource.

To grant the role, follow these steps:

Console

  1. Go to the IAM & Admin page.

    Go to IAM & Admin

  2. Click Grant access.

    The Add principals dialog opens.

  3. In the New principals field, enter the service account ID that you copied earlier.

  4. In the Select a role field, select Vertex AI, and then select Vertex AI User.

  5. Click Save.

gcloud

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

Replace the following:

  • PROJECT_NUMBER: your project number
  • MEMBER: the service account ID that you copied earlier

Create a model

  1. In the Google Cloud console, go to the BigQuery page.

    Go to BigQuery

  2. Using the SQL editor, create a remote model:

    CREATE OR REPLACE MODEL `PROJECT_ID.DATASET_ID.MODEL_NAME`
    REMOTE WITH CONNECTION `CONNECTION_ID`
    OPTIONS (ENDPOINT = 'ENDPOINT');
    

    Replace the following:

    • PROJECT_ID: your project ID
    • DATASET_ID: the ID of the dataset to contain the model
    • MODEL_NAME: the name of the model
    • CONNECTION_ID: the ID of your BigQuery connection

      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 name of the embedding model to use. This must be a text-embedding, text-multilingual-embedding, or multimodalembedding model. For more information about supported model versions and aliases, see ENDPOINT.

Generate text embeddings by using data from a table

Generate text embeddings with the ML.GENERATE_EMBEDDING function by using text data from a table column.

Typically, you want to use a text-embedding or text-multilingual-embedding model for text-only use cases, and use a multimodalembedding model for cross-modal search use cases, where embeddings for text and visual content are generated in the same semantic space.

text embedding

Generate text embeddings by using a remote model over an embedding model:

SELECT *
FROM ML.GENERATE_EMBEDDING(
  MODEL `PROJECT_ID.DATASET_ID.MODEL_NAME`,
  TABLE PROJECT_ID.DATASET_ID.TABLE_NAME,
  STRUCT(FLATTEN_JSON AS flatten_json_output,
    TASK_TYPE AS task_type,
    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 an embedding model.
  • TABLE_NAME: the name of the table that contains the text to embed. This table must have a column that's named content, or you can use an alias to use a differently named column.
  • FLATTEN_JSON: a BOOL value that indicates whether to parse the embedding into a separate column. The default value is TRUE.
  • TASK_TYPE: a STRING literal that specifies the intended downstream application to help the model produce better quality embeddings. TASK_TYPE accepts the following values:
    • RETRIEVAL_QUERY: specifies that the given text is a query in a search or retrieval setting.
    • RETRIEVAL_DOCUMENT: specifies that the given text is a document in a search or retrieval setting.

      When using this task type, it is helpful to include the document title in the query statement in order to improve embedding quality. You can use the title option to specify the name of the column that contains the document title, otherwise the document title must be in a column either named title or aliased as title, for example:

            SELECT *
            FROM
              ML.GENERATE_EMBEDDING(
                MODEL mydataset.embedding_model,
                (SELECT abstract as content, header as title, publication_number
                FROM mydataset.publications),
                STRUCT(TRUE AS flatten_json_output, 'RETRIEVAL_DOCUMENT' as task_type)
            );
            
    • SEMANTIC_SIMILARITY: specifies that the given text will be used for Semantic Textual Similarity (STS).
    • CLASSIFICATION: specifies that the embeddings will be used for classification.
    • CLUSTERING: specifies that the embeddings will be used for clustering.
  • OUTPUT_DIMENSIONALITY: an INT64 value that specifies the number of dimensions to use when generating embeddings. For example, if you specify 256 AS output_dimensionality, then the ml_generate_embedding_result output column contains 256 embeddings for each input value.

    You can only use this argument if the remote model that you specify in the model argument uses one of the following models as an endpoint:

    • text-embedding-004 or later
    • text-multilingual-embedding-002 or later

multimodal embedding

Generate text embeddings by using a remote model over the multimodalembedding model:

SELECT *
FROM ML.GENERATE_EMBEDDING(
  MODEL `PROJECT_ID.DATASET_ID.MODEL_NAME`,
  TABLE PROJECT_ID.DATASET_ID.TABLE_NAME,
  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 a multimodalembedding@001 model.
  • TABLE_NAME: the name of the table that contains the text to embed. This table must have a column that's named content, or you can use an alias to use a differently named column.
  • FLATTEN_JSON: a BOOL that indicates whether to parse the embedding into a separate column. The default value is TRUE.
  • OUTPUT_DIMENSIONALITY: an INT64 value that specifies the number of dimensions to use when generating embeddings. Valid values are 128, 256, 512, and 1408. The default value is 1408. For example, if you specify 256 AS output_dimensionality, then the ml_generate_embedding_result output column contains 256 embeddings for each input value.

Generate text embeddings by using data from a query

Generate text embeddings with the ML.GENERATE_EMBEDDING function by using text data provided by a query and a remote model over an embedding model.

Typically, you want to use a text-embedding or text-multilingual-embedding model for text-only use cases, and use a multimodalembedding model for cross-modal search use cases, where embeddings for text and visual content are generated in the same semantic space.

text embedding

Generate text embeddings by using a remote model over the embedding model:

SELECT *
FROM ML.GENERATE_EMBEDDING(
  MODEL `PROJECT_ID.DATASET_ID.MODEL_NAME`,
  (CONTENT_QUERY),
  STRUCT(FLATTEN_JSON AS flatten_json_output,
    TASK_TYPE AS task_type,
    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 an embedding model.
  • CONTENT_QUERY: a query whose result contains a STRING column called content.
  • FLATTEN_JSON: a BOOL value that indicates whether to parse the embedding into a separate column. The default value is TRUE.
  • TASK_TYPE: a STRING literal that specifies the intended downstream application to help the model produce better quality embeddings. TASK_TYPE accepts the following values:
    • RETRIEVAL_QUERY: specifies that the given text is a query in a search or retrieval setting.
    • RETRIEVAL_DOCUMENT: specifies that the given text is a document in a search or retrieval setting.

      When using this task type, it is helpful to include the document title in the query statement in order to improve embedding quality. You can use the title option to specify the name of the column that contains the document title, otherwise the document title must be in a column either named title or aliased as title, for example:

                SELECT *
                FROM
                  ML.GENERATE_EMBEDDING(
                    MODEL mydataset.embedding_model,
                    (SELECT abstract as content, header as title, publication_number
                    FROM mydataset.publications),
                    STRUCT(TRUE AS flatten_json_output, 'RETRIEVAL_DOCUMENT' as task_type)
                );
                
    • SEMANTIC_SIMILARITY: specifies that the given text will be used for Semantic Textual Similarity (STS).
    • CLASSIFICATION: specifies that the embeddings will be used for classification.
    • CLUSTERING: specifies that the embeddings will be used for clustering.
  • OUTPUT_DIMENSIONALITY: an INT64 value that specifies the number of dimensions to use when generating embeddings. For example, if you specify 256 AS output_dimensionality, then the ml_generate_embedding_result output column contains 256 embeddings for each input value.

    You can only use this argument if the remote model that you specify in the model argument uses one of the following models as an endpoint:

    • text-embedding-004 or later
    • text-multilingual-embedding-002 or later

multimodal embedding

Generate text embeddings by using a remote model over the multimodalembedding model:

SELECT *
FROM ML.GENERATE_EMBEDDING(
  MODEL `PROJECT_ID.DATASET_ID.MODEL_NAME`,
  (CONTENT_QUERY),
  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 a multimodalembedding@001 model.
  • CONTENT_QUERY: a query whose result contains a STRING column called content.
  • FLATTEN_JSON: a BOOL that indicates whether to parse the embedding into a separate column. The default value is TRUE.
  • OUTPUT_DIMENSIONALITY: an INT64 value that specifies the number of dimensions to use when generating embeddings. Valid values are 128, 256, 512, and 1408. The default value is 1408. For example, if you specify 256 AS output_dimensionality, then the ml_generate_embedding_result output column contains 256 embeddings for each input value.

Examples

The following examples show how to call the ML.GENERATE_EMBEDDING function on a table and a query.

Embed text in a table

The following example shows a request to embed the content column of the text_data table:

SELECT *
FROM
  ML.GENERATE_EMBEDDING(
    MODEL `mydataset.embedding_model`,
    TABLE mydataset.text_data,
    STRUCT(TRUE AS flatten_json_output, 'CLASSIFICATION' AS task_type)
  );

Use embeddings to rank semantic similarity

The following example embeds a collection of movie reviews and orders them by cosine distance to the review "This movie was average" using the ML.DISTANCE function. A smaller distance indicates more semantic similarity.

WITH movie_review_embeddings AS (
  SELECT *
  FROM
    ML.GENERATE_EMBEDDING(
      MODEL `bqml_tutorial.embedding_model`,
      (
        SELECT "Movie 1" AS title, "This movie was fantastic" AS content
        UNION ALL
        SELECT "Movie 2" AS title, "This was the best movie I've ever seen!!" AS content
        UNION ALL
        SELECT "Movie 3" AS title, "This movie was just okay..." AS content
        UNION ALL
        SELECT "Movie 4" AS title, "This movie was terrible." AS content
      ),
      STRUCT(TRUE AS flatten_json_output)
    )
),
average_review_embedding AS (
  SELECT ml_generate_embedding_result
  FROM
    ML.GENERATE_EMBEDDING(
      MODEL `bqml_tutorial.embedding_model`,
      (SELECT "This movie was average" AS content),
      STRUCT(TRUE AS flatten_json_output)
    )
)
SELECT
  content,
  ML.DISTANCE(
    (SELECT ml_generate_embedding_result FROM average_review_embedding),
    ml_generate_embedding_result,
    'COSINE'
  ) AS distance_to_average_review
FROM
  movie_review_embeddings
ORDER BY distance_to_average_review;

The result is the following:

+------------------------------------------+----------------------------+
| content                                  | distance_to_average_review |
+------------------------------------------+----------------------------+
| This movie was just okay...              | 0.062789813467745592       |
| This movie was fantastic                 |  0.18579561313064263       |
| This movie was terrible.                 |  0.35707466240930985       |
| This was the best movie I've ever seen!! |  0.41844932504542975       |
+------------------------------------------+----------------------------+