1. 简介
在此 Codelab 中,您将学习如何将向量搜索与 Vertex AI 嵌入结合使用,以便使用 Cloud SQL for PostgreSQL AI 集成。
前提条件
- 对 Google Cloud 控制台有基本的了解
- 具备命令行界面和 Cloud Shell 方面的基本技能
学习内容
- 如何部署 Cloud SQL for PostgreSQL 实例
- 如何创建数据库并启用 Cloud SQL AI 集成
- 如何将数据加载到数据库
- 如何在 Cloud SQL 中使用 Vertex AI 嵌入模型
- 如何使用 Vertex AI 生成式模型丰富结果
- 如何使用向量索引提升性能
所需条件
- Google Cloud 账号和 Google Cloud 项目
- 支持 Google Cloud 控制台和 Cloud Shell 的网络浏览器,例如 Chrome
2. 设置和要求
自定进度的环境设置
- 登录 Google Cloud 控制台,然后创建一个新项目或重复使用现有项目。如果您还没有 Gmail 或 Google Workspace 账号,则必须创建一个。
- 项目名称是此项目参与者的显示名称。它是 Google API 尚未使用的字符串。您可以随时对其进行更新。
- 项目 ID 在所有 Google Cloud 项目中是唯一的,并且是不可变的(一经设置便无法更改)。Cloud 控制台会自动生成一个唯一字符串;通常情况下,您无需关注该字符串。在大多数 Codelab 中,您都需要引用项目 ID(通常用
PROJECT_ID
标识)。如果您不喜欢生成的 ID,可以再随机生成一个 ID。或者,您也可以尝试自己的项目 ID,看看是否可用。完成此步骤后便无法更改该 ID,并且此 ID 在项目期间会一直保留。 - 此外,还有第三个值,即部分 API 使用的项目编号,供您参考。如需详细了解所有这三个值,请参阅文档。
- 接下来,您需要在 Cloud 控制台中启用结算功能,以便使用 Cloud 资源/API。运行此 Codelab 应该不会产生太多的费用(如果有的话)。若要关闭资源以避免产生超出本教程范围的结算费用,您可以删除自己创建的资源或删除项目。Google Cloud 新用户符合参与 300 美元免费试用计划的条件。
启动 Cloud Shell
虽然可以通过笔记本电脑对 Google Cloud 进行远程操作,但在此 Codelab 中,您将使用 Google Cloud Shell,这是一个在云端运行的命令行环境。
在 Google Cloud 控制台 中,点击右上角工具栏中的 Cloud Shell 图标:
预配和连接到环境应该只需要片刻时间。完成后,您应该会看到如下内容:
这个虚拟机已加载了您需要的所有开发工具。它提供了一个持久的 5 GB 主目录,并且在 Google Cloud 中运行,大大增强了网络性能和身份验证功能。您在此 Codelab 中的所有工作都可以在浏览器中完成。您无需安装任何程序。
3. 准备工作
启用 API
输出:
在 Cloud Shell 中,确保项目 ID 已设置:
gcloud config set project [YOUR-PROJECT-ID]
设置环境变量 PROJECT_ID:
PROJECT_ID=$(gcloud config get-value project)
启用所有必要的服务:
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.
4. 创建 Cloud SQL 实例
创建 Cloud SQL 实例,并实现数据库与 Vertex AI 的集成。
创建数据库密码
为默认数据库用户定义密码。您可以自行定义密码,也可以使用随机函数生成密码:
export CLOUDSQL_PASSWORD=`openssl rand -hex 12`
记下为密码生成的值:
echo $CLOUDSQL_PASSWORD
创建 Cloud SQL for PostgreSQL 实例
在 Cloud Shell 会话中,执行以下命令:
gcloud sql instances create my-cloudsql-instance \
--database-version=POSTGRES_16 \
--tier=db-custom-1-3840 \
--region=us-central1 \
--edition=ENTERPRISE \
--enable-google-ml-integration \
--database-flags cloudsql.enable_google_ml_integration=on
创建实例后,我们需要为实例中的默认用户设置密码,并验证能否使用该密码进行连接。
gcloud sql users set-password postgres \
--instance=my-cloudsql-instance \
--password=$CLOUDSQL_PASSWORD
运行该命令,并在准备好连接时在提示中输入密码。
gcloud sql connect my-cloudsql-instance --user=postgres
启用“Vertex AI 集成”
向内部 Cloud SQL 服务账号授予必要的权限,以便使用 Vertex AI 集成。
查找 Cloud SQL 内部服务账号的电子邮件地址,并将其导出为变量。
SERVICE_ACCOUNT_EMAIL=$(gcloud sql instances describe my-cloudsql-instance --format="value(serviceAccountEmailAddress)")
echo $SERVICE_ACCOUNT_EMAIL
向 Cloud SQL 服务账号授予对 Vertex AI 的访问权限:
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:$SERVICE_ACCOUNT_EMAIL" \
--role="roles/aiplatform.user"
如需详细了解如何创建和配置实例,请点击此处参阅 Cloud SQL 文档。
5. 准备数据库
现在,我们需要创建一个数据库并启用矢量支持。
创建数据库
创建一个名为 quickstart_db 的数据库。为此,我们提供了不同的选项,例如命令行数据库客户端(例如适用于 PostgreSQL 的 psql)、SDK 或 Cloud SQL Studio。我们将使用 SDK (gcloud) 创建数据库并连接到实例。
在 Cloud Shell 中,执行命令以创建数据库
gcloud sql databases create quickstart_db --instance=my-cloudsql-instance
启用扩展程序
为了能够使用 Vertex AI 和矢量,我们需要在创建的数据库中启用两个扩展程序。
在 Cloud Shell 中,执行命令以连接到创建的数据库(您需要提供密码)
gcloud sql connect my-cloudsql-instance --database quickstart_db --user=postgres
然后,成功连接后,您需要在 SQL 会话中运行以下两个命令:
CREATE EXTENSION IF NOT EXISTS google_ml_integration CASCADE;
CREATE EXTENSION IF NOT EXISTS vector CASCADE;
退出 SQL 会话:
exit;
6. 加载数据
现在,我们需要在数据库中创建对象并加载数据。我们将使用虚构的 Cymbal 商店数据。数据以 CSV 格式提供在公共 Google Storage 存储分区中。
首先,我们需要在数据库中创建所有必需的对象。为此,我们将使用已经熟悉的 gcloud sql connect 和 gcloud storage 命令下载架构对象并将其导入数据库。
在 Cloud Shell 中,执行以下命令并提供创建实例时记下的密码:
gcloud storage cat gs://cloud-training/gcc/gcc-tech-004/cymbal_demo_schema.sql |gcloud sql connect my-cloudsql-instance --database quickstart_db --user=postgres
我们在上一个命令中具体做了什么?我们连接到数据库,并执行了下载的 SQL 代码,该代码创建了表、索引和序列。
下一步是加载数据,为此,我们需要从 Google Cloud Storage 下载 CSV 文件。
gcloud storage cp gs://cloud-training/gcc/gcc-tech-004/cymbal_products.csv .
gcloud storage cp gs://cloud-training/gcc/gcc-tech-004/cymbal_inventory.csv .
gcloud storage cp gs://cloud-training/gcc/gcc-tech-004/cymbal_stores.csv .
然后,我们需要连接到数据库。
gcloud sql connect my-cloudsql-instance --database quickstart_db --user=postgres
并从 CSV 文件导入数据。
\copy cymbal_products from 'cymbal_products.csv' csv header
\copy cymbal_inventory from 'cymbal_inventory.csv' csv header
\copy cymbal_stores from 'cymbal_stores.csv' csv header
退出 SQL 会话:
exit;
如果您有自己的数据,并且您的 CSV 文件与 Cloud 控制台中提供的 Cloud SQL 导入工具兼容,则可以使用该工具,而不是使用命令行方法。
7. 创建嵌入
下一步是使用 Google Vertex AI 中的 textembedding-004 模型为产品说明构建嵌入,并将其存储为矢量数据。
连接到数据库:
gcloud sql connect my-cloudsql-instance --database quickstart_db --user=postgres
并使用嵌入函数在 cymbal_products 表中创建一个虚拟列“embedding”。
ALTER TABLE cymbal_products ADD COLUMN embedding vector(768) GENERATED ALWAYS AS (embedding('text-embedding-004',product_description)) STORED;
这可能需要一些时间,但对于 900-1000 行,不应超过 5 分钟,通常会更快。
8. 运行相似性搜索
现在,我们可以根据为说明计算的向量值和为请求获取的向量值,使用相似度搜索来运行搜索。
您可以使用 gcloud sql connect 从同一命令行界面执行 SQL 查询,也可以通过 Cloud SQL Studio 执行。最好在 Cloud SQL Studio 中管理任何多行和复杂查询。
启动 Cloud SQL Studio
在控制台中,点击我们之前创建的 Cloud SQL 实例。
在右侧面板上打开该窗口后,我们可以看到 Cloud SQL Studio。点击该图标。
系统随即会打开一个对话框,您可以在其中提供数据库名称和凭据:
- 数据库:quickstart_db
- 用户:postgres
- 密码:您记下的主数据库用户的密码
然后点击“AUTHENTICATE”(身份验证)按钮。
系统随即会打开下一个窗口,您可以在其中点击右侧的“Editor”(编辑器)标签页以打开 SQL 编辑器。
现在,我们可以运行查询了。
运行查询
运行查询,获取与客户请求最相关的可用产品列表。我们将向 Vertex AI 传递一个请求来获取矢量值,该请求类似于“这里适合种植什么样的果树?”
您可以运行以下查询,选择最符合我们请求的前 10 项内容:
SELECT
cp.product_name,
left(cp.product_description,80) as description,
cp.sale_price,
cs.zip_code,
(cp.embedding <=> embedding('text-embedding-004','What kind of fruit trees grow well here?')::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 10;
将查询复制并粘贴到 Cloud SQL Studio 编辑器,然后点击“运行”按钮,或将其粘贴到连接到 quickstart_db 数据库的命令行会话中。
下面列出了与查询匹配的所选商品。
product_name | description | sale_price | zip_code | distance -------------------------+----------------------------------------------------------------------------------+------------+----------+--------------------- Cherry Tree | This is a beautiful cherry tree that will produce delicious cherries. It is an d | 75.00 | 93230 | 0.43922018972266397 Meyer Lemon Tree | Meyer Lemon trees are California's favorite lemon tree! Grow your own lemons by | 34 | 93230 | 0.4685112926118228 Toyon | This is a beautiful toyon tree that can grow to be over 20 feet tall. It is an e | 10.00 | 93230 | 0.4835677149651668 California Lilac | This is a beautiful lilac tree that can grow to be over 10 feet tall. It is an d | 5.00 | 93230 | 0.4947204525907498 California Peppertree | This is a beautiful peppertree that can grow to be over 30 feet tall. It is an e | 25.00 | 93230 | 0.5054166905547247 California Black Walnut | This is a beautiful walnut tree that can grow to be over 80 feet tall. It is a d | 100.00 | 93230 | 0.5084219510932597 California Sycamore | This is a beautiful sycamore tree that can grow to be over 100 feet tall. It is | 300.00 | 93230 | 0.5140519790508755 Coast Live Oak | This is a beautiful oak tree that can grow to be over 100 feet tall. It is an ev | 500.00 | 93230 | 0.5143126438081371 Fremont Cottonwood | This is a beautiful cottonwood tree that can grow to be over 100 feet tall. It i | 200.00 | 93230 | 0.5174774727252058 Madrone | This is a beautiful madrona tree that can grow to be over 80 feet tall. It is an | 50.00 | 93230 | 0.5227400803389093 (10 rows)
9. 使用检索到的数据改进 LLM 回答
我们可以使用已执行查询的结果改进对客户端应用的 Gen AI LLM 响应,并使用提供的查询结果作为 Vertex AI 生成式基础语言模型的提示的一部分来准备有意义的输出。
为此,我们需要使用向量搜索的结果生成 JSON,然后将生成的 JSON 用作 Vertex AI 中 LLM 模型的提示,以生成有意义的输出。在第一步中,我们生成 JSON,然后在 Vertex AI Studio 中对其进行测试,最后将其纳入到可在应用中使用的 SQL 语句中。
以 JSON 格式生成输出
修改查询以以 JSON 格式生成输出,并仅返回一行以传递给 Vertex AI
Cloud SQL for PostgreSQL
以下是查询示例:
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
(cp.embedding <=> embedding('text-embedding-004','What kind of fruit trees grow well here?')::vector) ASC
LIMIT 1)
SELECT json_agg(trees) FROM trees;
以下是输出中的预期 JSON:
[{"product_name":"Cherry Tree","description":"This is a beautiful cherry tree that will produce delicious cherries. It is an d","sale_price":75.00,"zip_code":93230,"product_id":"d536e9e823296a2eba198e52dd23e712"}]
在 Vertex AI Studio 中运行提示
我们可以使用生成的 JSON 将其作为 Vertex AI Studio 中生成式 AI 文本模型的提示的一部分提供
在 Cloud 控制台中打开 Vertex AI Studio Chat。
系统可能会要求您启用其他 API,但您可以忽略该请求。我们无需任何其他 API 即可完成本实验。
以下是我们要使用的提示:
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:
[place your JSON here]
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: [{"product_name":"Cherry Tree","description":"This is a beautiful cherry tree that will produce delicious cherries. It is an d","sale_price":75.00,"zip_code":93230,"product_id":"d536e9e823296a2eba198e52dd23e712"}] 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 值和 gemini-2.0-flash 模型运行提示的结果:
下面是本例中模型给出的回答。请注意,由于模型和参数会随时间而变化,因此您的回答可能会有所不同:
“好的,根据可用产品列表,我们最适合您所在地区的树种是樱桃树。
价格为 75.00 美元。
虽然我不知道您确切邮政编码 (93230) 所在地的具体生长条件,但众所周知,樱桃树通常在气候温和且排水良好的土壤中茁壮成长。它们通常需要经历一段时间的冬季寒冷才能结果,请记住这一点。不过,在条件适合的情况下,它们可以成为花园的绝佳补充,既能提供美景,又能提供美味的樱桃。”
在 PSQL 中运行提示
我们还可以使用 Cloud SQL AI 与 Vertex AI 的集成,直接在数据库中使用 SQL 从生成式模型获取类似回答。不过,如需使用 gemini-2.0-flash-exp 模型,我们需要先将其注册。
在 Cloud SQL for PostgreSQL 中运行
将扩展程序升级到 1.4.2 或更高版本(如果当前版本较低)。如前所示,使用 gcloud sql connect 连接到 quickstart_db 数据库(或使用 Cloud SQL Studio),然后执行以下命令:
SELECT extversion from pg_extension where extname='google_ml_integration';
如果返回的值小于 1.4.2,请执行以下操作:
ALTER EXTENSION google_ml_integration UPDATE TO '1.4.2';
然后,我们需要将 google_ml_integration.enable_model_support 数据库标志设为“开启”。为此,您可以使用 Web 控制台界面或运行以下 gcloud 命令。
gcloud sql instances patch my-cloudsql-instance \
--database-flags google_ml_integration.enable_model_support=on,cloudsql.enable_google_ml_integration=on
该命令大约需要 1-3 分钟才能在后台执行完毕。然后,您可以在 psql 会话中验证新标志,或使用 Cloud SQL Studio 连接到 quickstart_db 数据库。
show google_ml_integration.enable_model_support;
psql 会话的预期输出为“on”:
quickstart_db => show google_ml_integration.enable_model_support; google_ml_integration.enable_model_support -------------------------------------------- on (1 row)
然后,我们需要注册两个模型。第一个是已使用的 text-embedding-004 模型。由于我们启用了模型注册功能,因此需要对其进行注册。
如需注册模型,请在 psql 或 Cloud SQL Studio 中运行以下代码:
CALL
google_ml.create_model(
model_id => 'text-embedding-004',
model_provider => 'google',
model_qualified_name => 'text-embedding-004',
model_type => 'text_embedding',
model_auth_type => 'cloudsql_service_agent_iam',
model_in_transform_fn => 'google_ml.vertexai_text_embedding_input_transform',
model_out_transform_fn => 'google_ml.vertexai_text_embedding_output_transform');
我们需要注册的下一个模型是 gemini-2.0-flash-001,它将用于生成人性化的输出。
CALL
google_ml.create_model(
model_id => 'gemini-2.0-flash-001',
model_request_url => 'https://us-central1-aiplatform.googleapis.com/v1/projects/$PROJECT_ID/locations/us-central1/publishers/google/models/gemini-2.0-flash-001:streamGenerateContent',
model_provider => 'google',
model_auth_type => 'cloudsql_service_agent_iam');
您可以随时从 google_ml.model_info_view 中选择信息,以验证已注册模型的列表。
select model_id,model_type from google_ml.model_info_view;
以下是示例输出
quickstart_db=> select model_id,model_type from google_ml.model_info_view; model_id | model_type --------------------------------------+---------------- textembedding-gecko | text_embedding textembedding-gecko@001 | text_embedding gemini-1.5-pro:streamGenerateContent | generic gemini-1.5-pro:generateContent | generic gemini-1.0-pro:generateContent | generic text-embedding-004 | text_embedding gemini-2.0-flash-001 | generic
现在,我们可以使用子查询 JSON 中生成的内容,通过 SQL 将其作为生成式 AI 文本模型提示的一部分提供给模型。
在数据库的 psql 或 Cloud SQL Studio 会话中运行查询
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
(cp.embedding <=> google_ml.embedding('text-embedding-004',
'What kind of fruit trees grow well here?')::vector) ASC
LIMIT 1),
prompt AS (
SELECT
'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_agg(trees) || '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
json_array_elements(google_ml.predict_row( model_id =>'gemini-2.0-flash-001',
request_body => json_build_object('contents',
json_build_object('role',
'user',
'parts',
json_build_object('text',
prompt_text)))))->'candidates'->0->'content'->'parts'->0->'text' AS resp
FROM
prompt)
SELECT
string_agg(resp::text,
' ')
FROM
response;
预期输出如下所示。您的输出可能会因模型版本和参数而异:
"That" "'s a great question! Based on your location (assuming you're" " in zip code 93230), I have a suggestion for a" " fruit tree that should thrive.\n\nWe have the **Cherry Tree** available.\n\n**Product Name:** Cherry Tree\n\n**Description:** This is a beautiful cherry" " tree that will produce delicious cherries. It's a deciduous tree (meaning it loses its leaves in the fall) growing to about 15 feet tall." " The leaves are dark green in summer, turning a beautiful red in the fall. Cherry trees are known for their beauty, shade, and privacy.\n\n**Sale Price:** $75.00\n\n**Important Considerations for Growing" " Cherry Trees:**\n\n* **Climate:** Cherry trees prefer a cool, moist climate, and 93230 falls within a suitable range (USDA zones 4-9). However, it's always a good idea to" " check the specific microclimate of your property (sun exposure, drainage etc.).\n* **Soil:** They do best in sandy soil. If your soil is different, you may need to amend it to improve drainage.\n* **Pollination:** Many cherry varieties require a second, compatible cherry tree for proper pollination" ". Check the specific pollination needs of this variety before purchase if you want a significant cherry yield.\n\nThis cherry tree is a beautiful addition to any yard and will provide you with delicious cherries if you can meet its needs. Would you like to know more about its pollination requirements, or perhaps see if we have any other" " fruit trees suitable for your area?\n" ""
10. 创建最近邻索引
我们的数据集非常小,响应时间主要取决于与 AI 模型的互动。但是,如果您有数百万个向量,向量搜索可能会占用我们响应时间的很大一部分,并给系统带来较高负载。为了改进这一点,我们可以在向量上构建索引。
创建 HNSW 索引
我们将尝试在测试中使用 HNSW 索引类型。HNSW 代表分层可导航小世界,表示多层图索引。
如需为嵌入列构建索引,我们需要定义嵌入列、距离函数以及可选的参数(例如 m 或 ef_constructions)。您可以在文档中详细了解这些参数。
CREATE INDEX cymbal_products_embeddings_hnsw ON cymbal_products
USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
预期输出:
quickstart_db=> CREATE INDEX cymbal_products_embeddings_hnsw ON cymbal_products USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64); CREATE INDEX quickstart_db=>
比较回答
现在,我们可以在 EXPLAIN 模式下运行矢量搜索查询,并验证是否已使用索引。
EXPLAIN (analyze)
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
(cp.embedding <=> embedding('text-embedding-004','What kind of fruit trees grow well here?')::vector) ASC
LIMIT 1)
SELECT json_agg(trees) FROM trees;
预期输出:
Aggregate (cost=779.12..779.13 rows=1 width=32) (actual time=1.066..1.069 rows=1 loops=1) -> Subquery Scan on trees (cost=769.05..779.12 rows=1 width=142) (actual time=1.038..1.041 rows=1 loops=1) -> Limit (cost=769.05..779.11 rows=1 width=158) (actual time=1.022..1.024 rows=1 loops=1) -> Nested Loop (cost=769.05..9339.69 rows=852 width=158) (actual time=1.020..1.021 rows=1 loops=1) -> Nested Loop (cost=768.77..9316.48 rows=852 width=945) (actual time=0.858..0.859 rows=1 loops=1) -> Index Scan using cymbal_products_embeddings_hnsw on cymbal_products cp (cost=768.34..2572.47 rows=941 width=941) (actual time=0.532..0.539 rows=3 loops=1) Order By: (embedding <=> '[0.008864171,0.03693164,-0.024245683,... <redacted> ...,0.017593635,-0.040275685,-0.03914233,-0.018452475,0.00826032,-0.07372604 ]'::vector) -> Index Scan using product_inventory_pkey on cymbal_inventory ci (cost=0.42..7.17 rows=1 width=37) (actual time=0.104..0.104 rows=0 loops=3) Index Cond: ((store_id = 1583) AND (uniq_id = (cp.uniq_id)::text)) Filter: (inventory > 0) Rows Removed by Filter: 1 -> Materialize (cost=0.28..8.31 rows=1 width=8) (actual time=0.133..0.134 rows=1 loops=1) -> Index Scan using product_stores_pkey on cymbal_stores cs (cost=0.28..8.30 rows=1 width=8) (actual time=0.129..0.129 rows=1 loops=1) Index Cond: (store_id = 1583) Planning Time: 112.398 ms Execution Time: 1.221 ms
从输出中,我们可以清楚地看到该查询使用的是“使用 cymbal_products_embeddings_hnsw 的索引扫描”。
如果我们不使用 explain 运行查询,则会得到以下结果:
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
(cp.embedding <=> embedding('text-embedding-004','What kind of fruit trees grow well here?')::vector) ASC
LIMIT 1)
SELECT json_agg(trees) FROM trees;
预期输出:
[{"product_name":"Cherry Tree","description":"This is a beautiful cherry tree that will produce delicious cherries. It is an d","sale_price":75.00,"zip_code":93230,"product_id":"d536e9e823296a2eba198e52dd23e712"}]
我们可以看到,结果相同,并返回了在未使用索引的搜索中排名第一的樱桃树。结果可能会因参数和索引类型而略有不同。在测试期间,使用编入索引的查询返回结果所需时间为 131.301 毫秒,而未使用任何索引时则需要 167.631 毫秒,但我们处理的数据集非常小,如果数据量更大,差异会更明显。
您可以尝试适用于向量的不同索引,并参阅文档,了解更多包含 LangChain 集成的实验和示例。
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。
所学内容
- 如何部署 Cloud SQL for PostgreSQL 实例
- 如何创建数据库并启用 Cloud SQL AI 集成
- 如何将数据加载到数据库
- 如何在 Cloud SQL 中使用 Vertex AI 嵌入模型
- 如何使用 Vertex AI 生成式模型丰富结果
- 如何使用向量索引提升性能
尝试使用 ScaNN 索引(而非 HNSW)运行类似的 AlloyDB Codelab
13. 调查问卷
输出如下: