Cloud SQL for MySQL 中的矢量嵌入功能使用入门

1. 简介

在此 Codelab 中,您将学习如何使用 Cloud SQL for MySQL AI 集成功能,通过嵌入进行语义搜索,以及如何通过对向量数据建立索引来提高性能。

8aa6ba3bc12a1593.png

前提条件

  • 对 Google Cloud 和 Google Cloud 控制台有基本的了解
  • 具备命令行界面和 Cloud Shell 方面的基本经验

学习内容

  • 如何部署 Cloud SQL for MySQL 实例
  • 如何创建数据库并启用 Cloud SQL AI 集成
  • 如何将数据加载到数据库中
  • 如何使用 Cloud SQL Studio
  • 如何在 Cloud SQL 中使用 Vertex AI 嵌入模型
  • 如何使用 Agent Platform Studio
  • 如何使用 Gemini Enterprise Agent Platform 模型丰富结果
  • 如何使用向量索引提升性能

所需条件

  • Google Cloud 账号和 Google Cloud 项目
  • 网络浏览器,例如 Chrome

2. 设置和要求

项目设置

  1. 登录 Google Cloud 控制台。如果您还没有 Gmail 或 Google Workspace 账号,则必须创建一个 Google 账号。

请改用个人账号,而不是工作账号或学校账号。

  1. 创建新项目或重复使用现有项目。如需在 Google Cloud 控制台中创建新项目,请点击工具栏中的选择项目。

295004821bab6a87.png

在“选择项目”窗口中,按“新建项目”按钮,系统随即会打开一个用于新建项目的对话框。

37d264871000675d.png

在对话框中,输入项目名称并选择位置。

96d86d3d5655cdbe.png

  • 项目名称是此项目参与者的显示名称。Google API 不会使用项目名称,并且您可以随时更改项目名称。
  • 项目 ID 在所有 Google Cloud 项目中是唯一的,并且是不可变的(一经设置便无法更改)。Google Cloud 控制台会自动生成一个唯一 ID,但您可以自定义该 ID。如果您不喜欢生成的 ID,可以生成另一个随机 ID,也可以提供自己的 ID 来检查其可用性。在大多数 Codelab 中,您都需要引用项目 ID,该 ID 通常用 占位符标识。
  • 此外,还有第三个值,即部分 API 使用的项目编号,供您参考。如需详细了解所有这三个值,请参阅创建和管理项目文档。

启用结算功能

您可以通过以下两种方式启用结算功能。您可以使用个人结算账号,也可以按照以下步骤兑换积分。

兑换 Google Cloud 赠金(可选)

如需运行此研讨会,您需要拥有一个有余额的结算账号。使用研讨会组织者提供的积分,或者使用此 Codelab 顶部横幅中提供的积分开始学习。如果您已关联结算账号,则可以跳过此步骤。

设置个人结算账号

如果您使用 Google Cloud 赠金设置了结算,则可以跳过此步骤。

如需设置个人结算账号,请在 Google Cloud Billing 控制台中启用结算功能。

注意:

  • 完成本实验所用的 Google Cloud 资源费用不到 5 美元。
  • 请按照本实验结束时的步骤删除资源,以免产生进一步的费用。
  • 新用户符合参与 300 美元免费试用计划的条件。
  • 新用户和现有用户都可以使用 Cloud SQL 免费试用实例开始使用 Cloud SQL

启动 Cloud Shell

虽然您可以从计算机远程操作 Google Cloud,但在此 Codelab 中,您将使用 Google Cloud Shell,这是一个在云端运行的命令行环境。

在 Google Cloud 控制台中,点击右上角工具栏中的 Cloud Shell 图标:

激活 Cloud Shell

或者,您也可以在 Google Cloud 控制台中按 g 键,然后按 s 键,或打开 Cloud Shell。

预配并连接到环境只需片刻时间。完成后,您应该会看到已连接的终端:

Google Cloud Shell 终端的屏幕截图,显示环境已连接

此虚拟机已加载您需要的所有开发工具。它提供了一个持久的 5 GB 主目录,并且在 Google Cloud 中运行,从而增强了网络性能和身份验证功能。您在此 Codelab 中的所有工作都可以在浏览器中完成。

3. 准备工作

启用 API

如需使用 Cloud SQL、Compute Engine、Service Networking 和 Gemini Enterprise Agent Platform,请在您的 Google Cloud 云项目中启用各自的 API。

在 Cloud Shell 终端中,确保项目 ID 已设置:

gcloud config get project

如果返回空字符串,请使用以下命令进行设置:

gcloud config set project [YOUR-PROJECT-ID]

设置 PROJECT_ID 环境变量:

PROJECT_ID=$(gcloud config get-value project)

启用所有必需的 API:

gcloud services enable sqladmin.googleapis.com \
                       compute.googleapis.com \
                       cloudresourcemanager.googleapis.com \
                       servicenetworking.googleapis.com \
                       aiplatform.googleapis.com

预期输出

student@cloudshell:~ (test-project-001-402417)$ gcloud config set project test-project-001-402417
Updated property [core/project].
student@cloudshell:~ (test-project-001-402417)$ PROJECT_ID=$(gcloud config get-value project)
Your active configuration is: [cloudshell-14650]
student@cloudshell:~ (test-project-001-402417)$ 
student@cloudshell:~ (test-project-001-402417)$ gcloud services enable sqladmin.googleapis.com \
                       compute.googleapis.com \
                       cloudresourcemanager.googleapis.com \
                       servicenetworking.googleapis.com \
                       aiplatform.googleapis.com
Operation "operations/acat.p2-4470404856-1f44ebd8-894e-4356-bea7-b84165a57442" finished successfully.

您可以在文档中了解每个已启用的 API。

4. 创建 Cloud SQL 实例

创建与 Gemini Enterprise Agent Platform 数据库集成的 Cloud SQL 实例。

创建数据库密码

为默认数据库用户定义密码。您可以自行定义密码,也可以使用随机函数生成密码:

export CLOUDSQL_PASSWORD=`openssl rand -hex 16`

显示生成的密码值:

echo $CLOUDSQL_PASSWORD

记下生成的密码,以便稍后使用。

创建 Cloud SQL for MySQL 实例

您可以使用多种方法创建 Cloud SQL 实例,包括 Google Cloud 控制台、Terraform 或 Google Cloud CLI (gcloud)。在此 Codelab 中,您将使用 gcloud。如需了解如何使用其他工具创建实例,请参阅创建实例文档。

创建实例时可以启用 cloudsql_vector 标志。向量支持适用于 MySQL 8.0 R20241208.01_00 或更高版本

在 Cloud Shell 会话中,执行以下命令:

gcloud sql instances create my-cloudsql-instance \
--database-version=MYSQL_8_4 \
--tier=db-custom-2-8192 \
--region=us-central1 \
--enable-google-ml-integration \
--edition=ENTERPRISE \
--root-password=$CLOUDSQL_PASSWORD

使用 gcloud sql connect 连接到实例。当系统提示时,输入密码:

gcloud sql connect my-cloudsql-instance --user=root

预期输出:

$gcloud sql connect my-cloudsql-instance --user=root
Allowlisting your IP for incoming connection for 5 minutes...done.                                                                                                                           
Connecting to database with SQL user [root].Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 71
Server version: 8.4.4-google (Google)

Copyright (c) 2000, 2025, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

按 Ctrl+D 或输入 exit 退出 mysql 会话:

exit

启用 Gemini Enterprise Agent Platform 集成

向 Cloud SQL 服务账号授予必要的 IAM 角色,以启用 Gemini Enterprise Agent Platform 集成。

检索 Cloud SQL 服务账号电子邮件地址,并将其导出为环境变量:

SERVICE_ACCOUNT_EMAIL=$(gcloud sql instances describe my-cloudsql-instance --format="value(serviceAccountEmailAddress)")
echo $SERVICE_ACCOUNT_EMAIL

将 roles/aiplatform.user 角色授予 Cloud SQL 服务账号:

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:$SERVICE_ACCOUNT_EMAIL" \
  --role="roles/aiplatform.user"

如需详细了解实例创建和配置,请参阅 Cloud SQL 文档(点击此处)。

5. 准备数据库

创建数据库并启用向量支持。

创建数据库

创建一个名为 quickstart_db 的数据库。 您可以使用数据库客户端(例如 mysql)、Google Cloud CLI 或 Cloud SQL Studio 创建数据库。在此步骤中,请使用 gcloud。

在 Cloud Shell 中,运行以下命令以创建数据库:

gcloud sql databases create quickstart_db --instance=my-cloudsql-instance

6. 加载数据

在数据库中创建表,并使用以 CSV 格式存储在公共 Cloud Storage 存储桶中的虚构 Cymbal Store 数据集文件加载数据。

Cloud Shell 将是您连接到数据库、创建所有对象和加载数据的主要环境。

将 Cloud Shell 公共 IP 添加到 Cloud SQL 实例的授权网络列表中。

在 Cloud Shell 中,执行以下命令:

gcloud sql instances patch my-cloudsql-instance --authorized-networks=$(curl ifconfig.me)

如果您的会话丢失、重置或您改用其他工具,请再次导出 CLOUDSQL_PASSWORD 变量:

export CLOUDSQL_PASSWORD=...your password defined for the instance...

创建所需的数据库对象。将 mysql 与 curl 搭配使用,以从公共来源下载并应用架构。

在 Cloud Shell 中,执行以下命令:

export INSTANCE_IP=$(gcloud sql instances describe my-cloudsql-instance --format="value(ipAddresses.ipAddress)")
curl -LJ https://raw.githubusercontent.com/GoogleCloudPlatform/devrel-demos/main/infrastructure/cymbal-store-embeddings/cymbal_mysql_schema.sql | mysql --host=$INSTANCE_IP --user=root --password=$CLOUDSQL_PASSWORD quickstart_db

命令细分。在上一步中,您已连接到数据库并运行 SQL 脚本来创建表、索引和序列。

接下来,运行 curl 和 mysql,使用 cymbal_products 数据填充数据库:

curl -LJ https://raw.githubusercontent.com/GoogleCloudPlatform/devrel-demos/main/infrastructure/cymbal-store-embeddings/cymbal_products.csv | mysql --enable-local-infile --host=$INSTANCE_IP --user=root --password=$CLOUDSQL_PASSWORD quickstart_db -e "LOAD DATA LOCAL INFILE '/dev/stdin'  INTO TABLE cymbal_products FIELDS TERMINATED BY ','  OPTIONALLY ENCLOSED BY '\"'  LINES TERMINATED BY '\n'  IGNORE 1 LINES;"

继续使用 cymbal_stores。

curl -LJ https://raw.githubusercontent.com/GoogleCloudPlatform/devrel-demos/main/infrastructure/cymbal-store-embeddings/cymbal_stores.csv | mysql --enable-local-infile --host=$INSTANCE_IP --user=root --password=$CLOUDSQL_PASSWORD quickstart_db -e "LOAD DATA LOCAL INFILE '/dev/stdin'  INTO TABLE cymbal_stores FIELDS TERMINATED BY ','  OPTIONALLY ENCLOSED BY '\"'  LINES TERMINATED BY '\n'  IGNORE 1 LINES;"

并使用 cymbal_inventory 完成,其中包含每个商店中每种产品的数量。

curl -LJ https://raw.githubusercontent.com/GoogleCloudPlatform/devrel-demos/main/infrastructure/cymbal-store-embeddings/cymbal_inventory.csv | mysql --enable-local-infile --host=$INSTANCE_IP --user=root --password=$CLOUDSQL_PASSWORD quickstart_db -e "LOAD DATA LOCAL INFILE '/dev/stdin'  INTO TABLE cymbal_inventory FIELDS TERMINATED BY ','  OPTIONALLY ENCLOSED BY '\"'  LINES TERMINATED BY '\n'  IGNORE 1 LINES;"

可选:如果您有自己的示例数据集,也可以改用 Google Cloud 控制台中的“导入”工具导入兼容的 CSV 文件。

7. 创建嵌入

使用 Gemini Enterprise Agent Platform 中的 text-embedding-005 模型为产品说明构建嵌入,并将其存储为向量数据。

如需存储向量数据,您必须在 Cloud SQL 实例中启用向量功能。

在 Cloud Shell 中执行以下命令:

gcloud sql instances patch my-cloudsql-instance \
--database-flags=cloudsql_vector=on

连接到数据库:

mysql --host=$INSTANCE_IP --user=root --password=$CLOUDSQL_PASSWORD quickstart_db

使用嵌入函数在 cymbal_products 表中创建新列 embedding。新列将包含基于 product_description 列中的文本生成的向量嵌入:

ALTER TABLE cymbal_products ADD COLUMN embedding vector(768) using varbinary;
UPDATE cymbal_products SET embedding = mysql.ml_embedding('text-embedding-005', product_description);

注意:生成 2,000 行的嵌入内容通常会在 5 分钟内完成。

退出 mysql 会话:

exit

8. 运行相似度搜索

通过比较为商品描述计算的向量嵌入与搜索查询的嵌入,运行相似度搜索。

您可以通过命令行或 Cloud SQL Studio 运行 SQL 查询。Cloud SQL Studio 提供了一种更便捷的方式来编辑和执行输出中包含多行的长 SQL 语句。

为 Cloud SQL Studio 创建 MySQL 用户

您需要一个可使用 Cloud SQL Studio 的新数据库用户。创建一个内置类型的用户 student,并使用与根用户相同的密码。

在 Cloud Shell 中,执行以下命令:

gcloud sql users create student  --instance=my-cloudsql-instance --password=$CLOUDSQL_PASSWORD --host=%

启动 Cloud SQL Studio

  1. 在 Google Cloud 控制台中,前往 Cloud SQL 实例,然后点击 my-cloudsql-instance。

Google Cloud 控制台中的 Cloud SQL 实例列表

  1. 在导航菜单中,点击 Cloud SQL Studio。

Cloud SQL Studio 菜单项

  1. 在身份验证对话框中,输入数据库名称和凭据:
    • 数据库:quickstart_db
    • 用户:student
    • 密码:
  2. 点击身份验证。

Cloud SQL Studio 身份验证对话框

  1. 点击未命名的查询标签页,打开 SQL 编辑器。

Cloud SQL Studio SQL 编辑器标签页

运行查询

运行查询,以检索与客户查询“哪些果树在这里长得好?”最相关的 5 种商品。

以下是您可以运行的查询,用于使用 cosine_distance 函数选择最适合我们请求的前 5 个商品:

SELECT mysql.ML_EMBEDDING('text-embedding-005','What kind of fruit trees grow well here?') into @query_vector;
SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        cosine_distance(cp.embedding ,@query_vector) as distance
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        distance ASC
LIMIT 5;

在 Cloud SQL Studio 中,输入查询,然后点击运行(或在 sql 会话中运行查询):

在 Cloud SQL Studio 中运行 SQL 查询

该查询会返回按余弦距离排序的匹配商品:

+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
| product_name    | description                                                                      | sale_price | zip_code | distance            |
+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
| Malus Domestica | Malus Domestica, the classic apple tree, brings beauty and delicious fruit to yo |     100.00 |    93230 | 0.37740096545831603 |
| Cerasus         | Cerasus: A beautiful cherry tree that brings delicious fruit and vibrant color t |      75.00 |    93230 |   0.405704177142419 |
| Persica         | Persica: Enjoy homegrown, delicious peaches with this beautiful peach tree. Reac |     150.00 |    93230 | 0.41031799106722877 |
| Meyer Lemon     | Grow your own juicy Meyer Lemons with this semi-dwarf tree, California's favorit |      34.00 |    93230 | 0.42823360959352186 |
| Acer            | Acer, the classic maple. Known for vibrant fall foliage in reds, oranges, and ye |     100.00 |    93230 | 0.42953897057301615 |
+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
5 rows in set (0.13 sec)

使用 cosine_distance 函数时,查询执行时间约为 0.13 秒。

运行相同的查询,但使用 approx_distance 函数进行 KNN 搜索。如果您没有为嵌入内容创建 ANN 索引,系统会在后台自动恢复为精确搜索:

SELECT mysql.ML_EMBEDDING('text-embedding-005','What kind of fruit trees grow well here?') into @query_vector;
SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        approx_distance(cp.embedding ,@query_vector, 'distance_measure=cosine') as distance
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        distance ASC
LIMIT 5;

以下是查询返回的商品列表。

+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
| product_name    | description                                                                      | sale_price | zip_code | distance            |
+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
| Malus Domestica | Malus Domestica, the classic apple tree, brings beauty and delicious fruit to yo |     100.00 |    93230 | 0.37740096545831603 |
| Cerasus         | Cerasus: A beautiful cherry tree that brings delicious fruit and vibrant color t |      75.00 |    93230 |   0.405704177142419 |
| Persica         | Persica: Enjoy homegrown, delicious peaches with this beautiful peach tree. Reac |     150.00 |    93230 | 0.41031799106722877 |
| Meyer Lemon     | Grow your own juicy Meyer Lemons with this semi-dwarf tree, California's favorit |      34.00 |    93230 | 0.42823360959352186 |
| Acer            | Acer, the classic maple. Known for vibrant fall foliage in reds, oranges, and ye |     100.00 |    93230 | 0.42953897057301615 |
+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
5 rows in set, 1 warning (0.12 sec)

查询执行仅耗时 0.12 秒。我们获得了与 KNN 精确 cosine_distance 函数相同的结果。

如需详细了解此函数,请参阅 Cloud SQL for MySQL 文档

9. 使用检索到的数据改进 LLM 回答

通过在提示中将查询结果作为接地背景信息传递给 Gemini Enterprise Agent Platform 基础语言模型,改进生成式 AI 对客户端应用的回答。

要实现这一目标,需要完成以下步骤:

  1. 根据 Cloud SQL 中的向量搜索结果生成 JSON 载荷。
  2. 在 Agent Platform Studio 中测试提示。
  3. 使用 google_ml 集成直接从 SQL 执行端到端提示。

以 JSON 格式生成输出

修改查询以将结果格式设置为 JSON 并返回一行:

SELECT mysql.ML_EMBEDDING('text-embedding-005','What kind of fruit trees grow well here?') into @query_vector;
WITH trees as (
SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        cp.uniq_id as product_id
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        (approx_distance(cp.embedding ,@query_vector, 'distance_measure=cosine')) ASC
LIMIT 1)
SELECT json_arrayagg(json_object('product_name',product_name,'description',description,'sale_price',sale_price,'zip_code',zip_code,'product_id',product_id)) FROM trees;

预期 JSON 输出:

[{"zip_code": 93230, "product_id": "23e41a71d63d8bbc9bdfa1d118cfddc5", "sale_price": 100.00, "description": "Malus Domestica, the classic apple tree, brings beauty and delicious fruit to yo", "product_name": "Malus Domestica"}]

在 Agent Platform Studio 中运行提示

在 Agent Platform Studio 中,将生成的 JSON 作为提示中的上下文提供给生成式模型。

  1. 在 Google Cloud 控制台中,打开 Agent Platform Studio。

Agent Platform Studio 导航

  1. 在 Agent Platform Studio 中输入以下提示:

在 Agent Platform Studio 中输入提示

You are a friendly advisor helping to find a product based on the customer's needs.
Based on the client request we have loaded a list of products closely related to search.
The list in JSON format with list of values like {"product_name":"name","description":"some description","sale_price":10,"zip_code": 10234, "produt_id": "02056727942aeb714dc9a2313654e1b0"}
Here is the list of products:
<JSON_OUTPUT>
The customer asked "What tree is growing the best here?"
You should give information about the product, price and some supplemental information.
Do not ask any additional questions and assume location based on the zip code provided in the list of products.

将 替换为查询返回的 JSON 响应:

You are a friendly advisor helping to find a product based on the customer's needs.
Based on the client request we have loaded a list of products closely related to search.
The list in JSON format with list of values like {"product_name":"name","description":"some description","sale_price":10,"zip_code": 10234, "produt_id": "02056727942aeb714dc9a2313654e1b0"}
Here is the list of products:
{"zip_code": 93230, "product_id": "23e41a71d63d8bbc9bdfa1d118cfddc5", "sale_price": 100.00, "description": "Malus Domestica, the classic apple tree, brings beauty and delicious fruit to yo", "product_name": "Malus Domestica"}
The customer asked "What tree is growing the best here?"
You should give information about the product, price and some supplemental information.
Do not ask any additional questions and assume location based on the zip code provided in the list of products.

Agent Platform Studio 中的提示

  1. 运行提示。

Agent Platform Studio 中的提示结果

答案包含价格、说明以及模型根据树木和位置信息从外部来源获取的补充信息。

在 SQL 中运行提示

您还可以将 Cloud SQL AI 与 Gemini Enterprise Agent Platform 集成,直接在 SQL 中获取生成式模型的回答。

首先,注册模型。

  1. 注册 gemini-3.5-flash 模型以生成回答(将 替换为您的项目 ID):
CALL
  mysql.ml_create_model_registration(
  'gemini-3.5-flash',
  'https://aiplatform.googleapis.com/v1/projects/<PROJECT_ID>/locations/global/publishers/google/models/gemini-3.5-flash:generateContent',
  'google',
  'GENERIC',
  NULL,
  'auth_type_cloudsql_service_agent_iam',
  NULL, NULL, NULL, NULL);

我们还可以将 Cloud SQL AI 与 Gemini Enterprise Agent Platform 集成,以便直接在数据库中使用 SQL 从生成式模型中获得类似回答。

现在,我们可以使用子查询中的生成结果(包含 JSON 结果),通过 SQL 将其作为提示的一部分提供给生成式 AI 文本模型。

在 mysql 或 Cloud SQL Studio 会话中,针对数据库运行查询

SELECT mysql.ML_EMBEDDING('text-embedding-005','What kind of fruit trees grow well here?') into @query_vector;
WITH trees AS (
SELECT
        cp.product_name,
        cp.product_description AS description,
        cp.sale_price,
        cs.zip_code,
        cp.uniq_id AS product_id
FROM
        cymbal_products cp
JOIN cymbal_inventory ci ON
        ci.uniq_id = cp.uniq_id
JOIN cymbal_stores cs ON
        cs.store_id = ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
         (approx_distance(cp.embedding ,@query_vector, 'distance_measure=cosine')) ASC
LIMIT 1),
prompt AS (
SELECT
       CONCAT( 'You are a friendly advisor helping to find a product based on the customer''s needs.
Based on the client request we have loaded a list of products closely related to search.
The list in JSON format with list of values like {"product_name":"name","product_description":"some description","sale_price":10}
Here is the list of products:', json_arrayagg(json_object('product_name',trees.product_name,'description',trees.description,'sale_price',trees.sale_price,'zip_code',trees.zip_code,'product_id',trees.product_id)) , 'The customer asked "What kind of fruit trees grow well here?"
You should give information about the product, price and some supplemental information') AS prompt_text
FROM
        trees),
response AS (
SELECT
       mysql.ML_PREDICT_ROW('gemini-3.5-flash',
        json_object('contents',
        json_object('role',
        'user',
        'parts',
        json_array(
        json_object('text',
        prompt_text))))) AS resp
FROM
        prompt)
SELECT
JSON_EXTRACT(resp, '$.candidates[0].content.parts[0].text')
FROM
        response;

以下是输出示例。您的输出可能会因模型版本和参数而异:

"Hello there! I'd be happy to help you find the perfect fruit tree for your space. \n\nBased on your area, a wonderful option we currently have in stock is the **Malus Domestica** (the classic Apple Tree)!\n\nHere are the key details:\n\n* **Product Name:** Malus Domestica (Classic Apple Tree)\n* **Price:** $100.00\n\n### Why it's a great choice:\n* **Beautiful Seasonal Foliage:** It features vibrant green leaves during the summer that turn into gorgeous shades of red, orange, and yellow in the autumn. \n* **Shade & Size:** It grows to approximately 30 feet tall, making it a strong, durable tree that offers excellent shade for your yard alongside delicious fresh fruit.\n* **Growing Conditions:** It thrives best in cool, moist climates with well-draining, loamy soil and is ideal for USDA Hardiness Zones 4–8.\n\n### Supplemental Care Tips:\n* **Planting Location:** Choose a spot that gets full sunlight (at least 6 hours a day) to ensure maximum fruit production.\n* **Soil:** Make sure the soil is rich and loamy with good drainage so the roots stay healthy.\n* **Cross-Pollination:** Apple trees often produce a higher yield when planted near another compatible apple tree variety, so if you have extra space, adding a companion tree in the future can boost your harvest!\n\nLet me know if you have any questions about planting or care, or if you'd like help adding this to your cart!"

输出以 Markdown 格式提供。

10. 创建最近邻索引

对于包含数百万个向量的大型数据集,向量搜索可能需要大量计算资源。为了提高查询性能,请在向量嵌入上创建索引。

创建 ScaNN 索引

我们将尝试使用 ScaNN 索引类型进行测试。

如需为嵌入列构建索引,您需要为嵌入列定义距离衡量标准。您可以在文档中详细了解这些参数。

CREATE VECTOR INDEX cymbal_products_embedding_idx ON cymbal_products(embedding) USING SCANN DISTANCE_MEASURE=COSINE;

比较回答

再次运行向量搜索查询,并查看结果:

SELECT mysql.ML_EMBEDDING('text-embedding-005','What kind of fruit trees grow well here?') into @query_vector;
SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        approx_distance(cp.embedding ,@query_vector, 'distance_measure=cosine') as distance
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        distance ASC
LIMIT 5;

预期输出:

+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
| product_name    | description                                                                      | sale_price | zip_code | distance            |
+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
| Malus Domestica | Malus Domestica, the classic apple tree, brings beauty and delicious fruit to yo |     100.00 |    93230 | 0.37740096545831603 |
| Cerasus         | Cerasus: A beautiful cherry tree that brings delicious fruit and vibrant color t |      75.00 |    93230 |   0.405704177142419 |
| Persica         | Persica: Enjoy homegrown, delicious peaches with this beautiful peach tree. Reac |     150.00 |    93230 | 0.41031799106722877 |
| Meyer Lemon     | Grow your own juicy Meyer Lemons with this semi-dwarf tree, California's favorit |      34.00 |    93230 | 0.42823360959352186 |
| Acer            | Acer, the classic maple. Known for vibrant fall foliage in reds, oranges, and ye |     100.00 |    93230 | 0.42953897057301615 |
+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
5 rows in set (0.08 sec)

性能提升幅度仅略有不同,但对于如此小的数据集,这是预期之内的。对于包含数百万个向量的大型数据集,这种差异会更加明显。

使用 EXPLAIN 命令检查执行计划:

SELECT mysql.ML_EMBEDDING('text-embedding-005','What kind of fruit trees grow well here?') into @query_vector;
EXPLAIN ANALYZE SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        approx_distance(cp.embedding ,@query_vector, 'distance_measure=cosine') as distance
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        distance ASC
LIMIT 5;

执行计划(摘录):

...
-> Nested loop inner join  (cost=443 rows=5) (actual time=1.14..1.18 rows=5 loops=1)
                                -> Vector index scan on cp  (cost=441 rows=5) (actual time=1.1..1.1 rows=5 loops=1)
                                -> Single-row index lookup on cp using PRIMARY (uniq_id=cp.uniq_id)  (cost=0.25 rows=1) (actual time=0.0152..0.0152 rows=1 loops=5)

...

它显示了对 cp 表(cymbal_products 表的别名)的向量索引扫描。

您可以尝试使用自己的数据或测试不同的搜索查询,了解 MySQL 中的语义搜索功能。

11. 清理环境

删除 Cloud SQL 实例

完成实验后销毁 Cloud SQL 实例

如果您已断开连接且之前的所有设置都已丢失,请在 Cloud Shell 中定义项目和环境变量:

export INSTANCE_NAME=my-cloudsql-instance
export PROJECT_ID=$(gcloud config get-value project)

删除实例:

gcloud sql instances delete $INSTANCE_NAME --project=$PROJECT_ID

预期的控制台输出:

student@cloudshell:~$ gcloud sql instances delete $INSTANCE_NAME --project=$PROJECT_ID
All of the instance data will be lost when the instance is deleted.

Do you want to continue (Y/n)?  y

Deleting Cloud SQL instance...done.                                                                                                                
Deleted [https://sandbox.googleapis.com/v1beta4/projects/test-project-001-402417/instances/my-cloudsql-instance].

12. 恭喜

恭喜您完成此 Codelab。

Google Cloud 学习路线

本实验是“利用 Google Cloud 构建可用于生产用途的 AI”学习路线的组成部分。

  • 探索完整课程,弥合从原型设计到生产落地的差距。
  • 使用 ##ProductionReadyAI 分享您的进度。

所学内容

  • 如何部署 Cloud SQL for MySQL 实例
  • 如何创建数据库并启用 Cloud SQL AI 集成
  • 如何将数据加载到数据库中
  • 如何使用 Cloud SQL Studio
  • 如何在 Cloud SQL 中使用 Vertex AI 嵌入模型
  • 如何使用 Agent Platform Studio
  • 如何使用 Gemini Enterprise Agent Platform 模型丰富结果
  • 如何使用向量索引提升性能

您可以尝试类似的 AlloyDB Codelab 或 Cloud SQL for Postgres Codelab

调查问卷

输出:

您打算如何使用本教程?

仅通读 阅读并完成练习