Loading...
No results found.

Apply your skills in Google Cloud console

Select a Google Cloud Database for Your Applications

Get access to 700+ labs and courses

Configuring Vector Search in Spanner

Lab 1 hour universal_currency_alt 1 Credit show_chart Introductory
info This lab may incorporate AI tools to support your learning.
Get access to 700+ labs and courses

GSP1288

Overview

Imagine your applications searching your Spanner database and quickly identifying related data, even if the provided search phase is not actually included in the stored text! This is now possible by leveraging the power of Vertex AI text embeddings to conduct vector search within Spanner.

Spanner is a fully managed database service that offers transactional consistency at global scale and automatic, synchronous replication for high availability. In addition, you can leverage artificial intelligence (AI) functionality in Spanner to accomplish tasks such as building Generative AI applications and surfacing data in your Spanner database based on relevance to your specific search terms.

Vector search is a methodology that can be used to quickly find similar items based on their semantic meaning (rather than exact keyword matching) and can be applied to many types of data including audio, images, videos, and text. For text specifically, vector search enables you to find similar text items without needing their contents to match the exact text or phrase used in the search.

In this lab, you learn the fundamentals of configuring vector search in Spanner by first generating and storing text embeddings (vectors containing numerical representations of semantic meaning of text), and then using those text embeddings to perform fast similarity searches. This hands-on lab was adapted from the codelab titled Getting started with Spanner Vector Search and uses a dataset of bicycle products to highlight how vector search can be leveraged in Spanner to find the products most relevant to a search phrase without needing an exact match in the text.

What you'll do

In this lab, you learn how to:

  • Create an embeddings model in Spanner and configure it to a Vertex AI model endpoint
  • Create a table and load data in Spanner
  • Generate and store text embeddings in Spanner
  • Perform vector search in Spanner using text embeddings

Setup and requirements

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources are made available to you.

This hands-on lab lets you do the lab activities in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito (recommended) or private browser window to run this lab. This prevents conflicts between your personal account and the student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab—remember, once you start, you cannot pause a lab.
Note: Use only the student account for this lab. If you use a different Google Cloud account, you may incur charges to that account.

How to start your lab and sign in to the Google Cloud console

  1. Click the Start Lab button. If you need to pay for the lab, a dialog opens for you to select your payment method. On the left is the Lab Details pane with the following:

    • The Open Google Cloud console button
    • Time remaining
    • The temporary credentials that you must use for this lab
    • Other information, if needed, to step through this lab
  2. Click Open Google Cloud console (or right-click and select Open Link in Incognito Window if you are running the Chrome browser).

    The lab spins up resources, and then opens another tab that shows the Sign in page.

    Tip: Arrange the tabs in separate windows, side-by-side.

    Note: If you see the Choose an account dialog, click Use Another Account.
  3. If necessary, copy the Username below and paste it into the Sign in dialog.

    {{{user_0.username | "Username"}}}

    You can also find the Username in the Lab Details pane.

  4. Click Next.

  5. Copy the Password below and paste it into the Welcome dialog.

    {{{user_0.password | "Password"}}}

    You can also find the Password in the Lab Details pane.

  6. Click Next.

    Important: You must use the credentials the lab provides you. Do not use your Google Cloud account credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  7. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Google Cloud console opens in this tab.

Note: To access Google Cloud products and services, click the Navigation menu or type the service or product name in the Search field.

Task 1. Create an embeddings model in Spanner and configure it to a Vertex AI model endpoint

A Spanner instance named cymbal-retail and a database named cymbal-bicycles have been provisioned for you in this lab environment.

In this task, you start the overall workflow in Spanner by creating and configuring the embeddings model used to generate the text embeddings, which also auto-initiates the creation of the Spanner service account needed for later tasks. Specifically, you create an embeddings model named EmbeddingsModel and configure it to an endpoint for the Vertex AI text embeddings model named text-embedding-005.

  1. In the Google Cloud console, click on the Navigation menu () > View All Products. Under Databases, click on Spanner.

  2. On the Instances page, click on the instance named Cymbal Retail Spanner Instance to examine the instance details.

  3. Under Databases, click on the database named cymbal-bicycles.

  4. In the Spanner menu under Database, click Spanner Studio.

  5. On the Spanner Studio page, click New SQL editor tab to open a new query window.

  6. To create and configure the embeddings model to a Vertex AI model endpoint, copy and paste the following query in the query window, and click Run.

CREATE MODEL EmbeddingsModel INPUT( content STRING(MAX), ) OUTPUT( embeddings STRUCT<statistics STRUCT<truncated BOOL, token_count FLOAT32>, values ARRAY<FLOAT32>>, ) REMOTE OPTIONS ( endpoint = '//aiplatform.googleapis.com/projects/{{{project_0.project_id |Project ID}}}/locations/{{{project_0.default_region |Region}}}/publishers/google/models/text-embedding-005' );

Click Check my progress to verify the objective. Create an embeddings model and configure it to a Vertex AI model endpoint.

When the query has executed successfully, you see a message that says Update completed.

Remain in Spanner Studio and proceed to the next task.

Task 2. Create a new table and load products data

Now that you have created and configured the embeddings model, you need the data for which you want to generate the text embeddings for vector search.

In this task, you create a new table containing descriptive columns for products (such as product names and inventory count) for a fictitious company named Cymbal Bicycles, plus an extra column for the vector embeddings for the product descriptions (to be generated in the next task). Last, you load a sample of the Cymbal Bicycles products data into the table in Spanner.

  1. In the Spanner Studio query editor, click Clear (along the same menu bar as Run) to remove the previous query.

  2. To create a new table named products, copy and paste the following query in the query window, and click Run.

CREATE TABLE products ( categoryId INT64 NOT NULL, productId INT64 NOT NULL, productName STRING(MAX) NOT NULL, productDescription STRING(MAX) NOT NULL, productDescriptionEmbedding ARRAY<FLOAT32>, createTime TIMESTAMP NOT NULL OPTIONS ( allow_commit_timestamp = true ), inventoryCount INT64 NOT NULL, priceInCents INT64, ) PRIMARY KEY(categoryId, productId);

The column named productDescriptionEmbedding is of the type ARRAY<FLOAT32>, which supports storage for the vector values that you create in the next task.

When the query has executed successfully, you see a message that says Update completed.

  1. Click Clear again (along the same menu bar as Run) to remove the previous query.

  2. To load data into the table, copy and paste the following query in the query window, and click Run.

Note that this query loads a small sample of products, but it includes all of the information needed for each of the 10 products loaded into the table.

INSERT INTO products (categoryId, productId, productName, productDescription, createTime, inventoryCount, priceInCents) VALUES (1, 1, "Cymbal Helios Helmet", "Safety meets style with the Cymbal children's bike helmet. Its lightweight design, superior ventilation, and adjustable fit ensure comfort and protection on every ride. Stay bright and keep your child safe under the sun with Cymbal Helios!", PENDING_COMMIT_TIMESTAMP(), 100, 10999), (1, 2, "Cymbal Sprout", "Let their cycling journey begin with the Cymbal Sprout, the ideal balance bike for beginning riders ages 2-4 years. Its lightweight frame, low seat height, and puncture-proof tires promote stability and confidence as little ones learn to balance and steer. Watch them sprout into cycling enthusiasts with Cymbal Sprout!", PENDING_COMMIT_TIMESTAMP(), 10, 13999), (1, 3, "Cymbal Spark Jr.", "Light, vibrant, and ready for adventure, the Spark Jr. is the perfect first bike for young riders (ages 5-8). Its sturdy frame, easy-to-use brakes, and puncture-resistant tires inspire confidence and endless playtime. Let the spark of cycling ignite with Cymbal!", PENDING_COMMIT_TIMESTAMP(), 34, 13900), (1, 4, "Cymbal Summit", "Conquering trails is a breeze with the Summit mountain bike. Its lightweight aluminum frame, responsive suspension, and powerful disc brakes provide exceptional control and comfort for experienced bikers navigating rocky climbs or shredding downhill. Reach new heights with Cymbal Summit!", PENDING_COMMIT_TIMESTAMP(), 0, 79999), (1, 5, "Cymbal Breeze", "Cruise in style and embrace effortless pedaling with the Breeze electric bike. Its whisper-quiet motor and long-lasting battery let you conquer hills and distances with ease. Enjoy scenic rides, commutes, or errands with a boost of confidence from Cymbal Breeze!", PENDING_COMMIT_TIMESTAMP(), 72, 129999), (1, 6, "Cymbal Trailblazer Backpack", "Carry all your essentials in style with the Trailblazer backpack. Its water-resistant material, multiple compartments, and comfortable straps keep your gear organized and accessible, allowing you to focus on the adventure. Blaze new trails with Cymbal Trailblazer!", PENDING_COMMIT_TIMESTAMP(), 24, 7999), (1, 7, "Cymbal Phoenix Lights", "See and be seen with the Phoenix bike lights. Powerful LEDs and multiple light modes ensure superior visibility, enhancing your safety and enjoyment during day or night rides. Light up your journey with Cymbal Phoenix!", PENDING_COMMIT_TIMESTAMP(), 87, 3999), (1, 8, "Cymbal Windstar Pump", "Flat tires are no match for the Windstar pump. Its compact design, lightweight construction, and high-pressure capacity make inflating tires quick and effortless. Get back on the road in no time with Cymbal Windstar!", PENDING_COMMIT_TIMESTAMP(), 36, 24999), (1, 9,"Cymbal Odyssey Multi-Tool","Be prepared for anything with the Odyssey multi-tool. This handy gadget features essential tools like screwdrivers, hex wrenches, and tire levers, keeping you ready for minor repairs and adjustments on the go. Conquer your journey with Cymbal Odyssey!", PENDING_COMMIT_TIMESTAMP(), 52, 999), (1, 10,"Cymbal Nomad Water Bottle","Stay hydrated on every ride with the Nomad water bottle. Its sleek design, BPA-free construction, and secure lock lid make it the perfect companion for staying refreshed and motivated throughout your adventures. Hydrate and explore with Cymbal Nomad!", PENDING_COMMIT_TIMESTAMP(), 42, 1299);

When the query has executed successfully, you see a message that says This statement inserted 10 rows and did not return any rows.

Click Check my progress to verify the objective. Create a new table and load the products data.

Task 3. Generate and store text embeddings for the products data

With the creation of the embeddings model in Task 1, you also initiated the creation of the Spanner service account used to access the embeddings model via the Vertex AI model endpoint.

In this task, you begin by ensuring that this service account has the role needed to access the Vertex AI endpoint. Then, you run a query to generate the embeddings for the product descriptions and store them in the products table.

Grant Cloud Spanner API Service Agent role to the Spanner service account

  1. In the Google Cloud console, on the Navigation menu (), select IAM & Admin > IAM.

  2. Click Grant access.

  3. For New principals, enter the Spanner service account ID: service-@gcp-sa-spanner.iam.gserviceaccount.com

Note: If you do not see this service account, more time may be needed for the service account to provision after Task 1. Close this window, and wait 3 minutes before repeating steps 2-3.
  1. For Select a role, search for Cloud Spanner API Service Agent using the filter, and select it to populate the Role box.

  2. Click Save.

Note: If you receive a message that states No change - principal already exists on the policy, you may proceed to the next section without attempting to grant the role again.

Update the productDescriptionEmbedding column to store the generated text embeddings

Now that you have ensured the Spanner service account has the appropriate role, you can generate the text embeddings for the product descriptions and add them to the products table.

  1. Return to Spanner Studio by following steps 1-4 in Task 1.

  2. Copy and paste the following query into the query window to update the column named productDescriptionEmbedding with the generated embeddings, and click Run.

UPDATE products p1 SET productDescriptionEmbedding = (SELECT embeddings.values from ML.PREDICT(MODEL EmbeddingsModel, (SELECT productDescription as content FROM products p2 where p2.productId=p1.productId))) WHERE categoryId=1; Note: If you receive an error message similar to Permission denied on the resource, wait a few minutes for the permissions that you assigned in the previous steps to fully propagate, and then run the query again.

When the query has executed successfully, you see a message that says 10 rows updated by your query.

Click Check my progress to verify the objective. Generate and store text embeddings for the products data.

Remain in Spanner Studio and proceed to the next task.

Task 4. Perform vector search using text embeddings in Spanner

After generating and storing the text embeddings for the product descriptions, your data is now ready for your first real time vector search!

In this task, you run a query to perform similarity search based on the phrase I'd like to buy a starter bike for my 3 year old child and quickly return the top 5 most relevant products, despite there not being an exact match for this text in the product data.

  1. In the Spanner Studio query editor, click Clear (along the same menu bar as Run) to remove the previous query.

  2. To perform a vector search using the text embeddings, copy and paste the following query in the query window, and click Run.

SELECT productName, productDescription, inventoryCount, COSINE_DISTANCE( productDescriptionEmbedding, ( SELECT embeddings.values FROM ML.PREDICT( MODEL EmbeddingsModel, (SELECT "I'd like to buy a starter bike for my 3 year old child" as content) ) ) ) as distance FROM products WHERE inventoryCount > 0 ORDER BY distance LIMIT 5;

This query uses the values in the productDescriptionEmbedding column to find the top 5 database rows that are the most semantically similar to the search phrase I'd like to buy a starter bike for my 3 year old child.

Note that the embedding for the search phase is generated dynamically in the query. Feel free to explore this query more by replacing I'd like to buy a starter bike for my 3 year old child in the code above with a new search term of your choice.

The output resembles the following:

productName productDescription inventoryCount distance
Cymbal Sprout Let their cycling journey begin with the Cymbal Sprout, the ideal balance bike for beginning riders ages 2-4 years... 10 0.3094387191860244
Cymbal Spark Jr. Light, vibrant, and ready for adventure, the Spark Jr. is the perfect first bike for young riders (ages 5-8)... 34 0.3412342902117166
Cymbal Helios Helmet Safety meets style with the Cymbal children's bike helmet... 100 0.4197863319656684
Cymbal Breeze Cruise in style and embrace effortless pedaling with the Breeze electric bike... 72 0.485231776523978
Cymbal Phoenix Lights See and be seen with the Phoenix bike lights... 87 0.5251486508206732

Click Check my progress to verify the objective. Perform vector search using text embeddings in Spanner.

Congratulations!

In this lab, you learned how to create an embeddings model in Spanner and configure it to a Vertex AI model endpoint, generate and store text embeddings in a Spanner table, and perform vector search in Spanner using the stored text embeddings.

Next steps / Learn more

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated February 10, 2025

Lab Last Tested February 10, 2025

Copyright 2025 Google LLC. All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.

Previous Next

Before you begin

  1. Labs create a Google Cloud project and resources for a fixed time
  2. Labs have a time limit and no pause feature. If you end the lab, you'll have to restart from the beginning.
  3. On the top left of your screen, click Start lab to begin

This content is not currently available

We will notify you via email when it becomes available

Great!

We will contact you via email if it becomes available

One lab at a time

Confirm to end all existing labs and start this one

Use private browsing to run the lab

Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
Preview