1. 簡介
在本程式碼研究室中,您將瞭解如何使用 MySQL 適用的 Cloud SQL AI 整合功能,透過嵌入執行語意搜尋,以及如何使用向量資料的索引提升效能。

事前準備
- 對 Google Cloud 和 Google Cloud 控制台有基本瞭解
- 熟悉指令列介面和 Cloud Shell 的基本操作
課程內容
- 如何部署 MySQL 適用的 Cloud SQL 執行個體
- 如何建立資料庫及啟用 Cloud SQL AI 整合
- 如何將資料載入資料庫
- 如何使用 Cloud SQL Studio
- 如何在 Cloud SQL 中使用 Vertex AI 嵌入模型
- 如何使用 Agent Platform Studio
- 如何使用 Gemini Enterprise Agent Platform 模型擴充結果
- 如何使用向量索引提升效能
軟硬體需求
- Google Cloud 帳戶和 Google Cloud 專案
- 網路瀏覽器,例如 Chrome
2. 設定和需求條件
專案設定
- 登入 Google Cloud 控制台。如果沒有 Gmail 或 Google Workspace 帳戶,請建立 Google 帳戶。
請改用個人帳戶,而非公司或學校帳戶。
- 建立新專案或重複使用現有專案。如要在 Google Cloud 控制台中建立新專案,請按一下工具列中的「選取專案」。

在「選取專案」視窗中,按下「新專案」按鈕,開啟新專案的對話方塊。

在對話方塊中輸入「專案名稱」,然後選取「位置」。

- 專案名稱是這個專案參與者的顯示名稱。Google API 不會使用專案名稱,且專案名稱隨時可以變更。
- 專案 ID 在所有 Google Cloud 專案中不得重複,且設定後即無法變更。Google Cloud 控制台會自動產生專屬 ID,但您可以自訂。如果不喜歡系統產生的 ID,可以產生另一個隨機 ID,或提供自己的 ID 並檢查是否可用。在大多數程式碼研究室中,您會參照專案 ID,通常是以
預留位置表示。 - 請注意,部分 API 會使用第三個值,也就是「專案編號」。如要進一步瞭解這三種值,請參閱「建立及管理專案」說明文件。
啟用計費功能
如要啟用計費功能,有兩種方法。你可以使用個人帳單帳戶,也可以按照下列步驟兌換抵免額。
兌換 Google Cloud 抵免額 (選填)
如要參加這場研討會,您需要有具備抵免額的帳單帳戶。請使用研討會主辦單位提供的抵免額,或這個程式碼研究室頂端橫幅中提供的抵免額,開始進行實驗。如果已連結帳單帳戶,可以略過這個步驟。
設定個人帳單帳戶
如果使用 Google Cloud 抵免額設定帳單,可以略過這個步驟。
如要設定個人帳單帳戶,請在 Google Cloud Billing 控制台中啟用帳單功能。
注意:
- 完成本實驗室的 Google Cloud 資源費用不到 $5 美元。
- 請按照本實驗室結尾的步驟刪除資源,避免產生額外費用。
- 新使用者可享有價值 $300 美元的免費試用期。
- 新使用者和現有使用者都可以使用 Cloud SQL 免費試用執行個體,開始使用 Cloud SQL
啟動 Cloud Shell
您可以透過電腦遠端操作 Google Cloud,但本程式碼實驗室會使用 Google Cloud Shell,這是雲端執行的指令列環境。
在 Google Cloud 控制台中,點選右上角工具列的 Cloud Shell 圖示:

或者,您也可以在 Google Cloud 控制台中依序按下 g 和 s 鍵,或開啟 Cloud Shell。
佈建並連線至環境的作業,應該很快就能完成。完成後,您應該會看到已連線的終端機:

這個虛擬機器已預先安裝所有必要的開發工具,並提供永久的 5 GB 主目錄,而且可在 Google Cloud 運作,提升網路效能並強化驗證功能。您可以在瀏覽器中完成本程式碼研究室的所有作業。
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
請記下產生的密碼,稍後會用到。
建立 MySQL 適用的 Cloud SQL 執行個體
您可以使用多種方法建立 Cloud SQL 執行個體,包括 Google Cloud 控制台、Terraform 或 Google Cloud CLI (gcloud)。在本程式碼研究室中,您將使用 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 整合功能
將必要的 IAM 角色授予 Cloud SQL 服務帳戶,以啟用 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"
如要進一步瞭解如何建立及設定執行個體,請參閱這篇文章。
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 bucket 中的虛構 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);
注意:通常 5 分鐘內即可完成 2,000 列的嵌入生成作業。
結束 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

- 按一下導覽選單中的「Cloud SQL Studio」。

- 在驗證對話方塊中,輸入資料庫名稱和憑證:
- 資料庫:
quickstart_db - 使用者:
student - 密碼:
- 資料庫:
- 按一下「Authenticate」(驗證)。

- 點選「未命名的查詢」分頁,開啟 SQL 編輯器。

執行查詢
執行查詢,找出與顧客查詢最相關的前 5 項產品:「這裡適合種植哪種果樹?」
使用 cosine_distance 執行查詢,進行 KNN (精確) 向量搜尋
以下是您可以執行的查詢,使用 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 工作階段中執行查詢):

查詢會傳回依餘弦距離排序的相符產品:
+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+ | 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 (精確) 向量搜尋的查詢
執行相同的查詢,但使用 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 函式相同的結果。
如要進一步瞭解這項功能,請參閱 MySQL 適用的 Cloud SQL 說明文件。
9. 使用檢索到的資料提升 LLM 回覆品質
將查詢結果做為提示中的基礎內容,傳遞至 Gemini Enterprise Agent Platform 基礎語言模型,藉此改善用戶端應用程式的生成式 AI 回覆。
為了達到這個目的:
- 從 Cloud SQL 的向量搜尋結果產生 JSON 酬載。
- 在 Agent Platform Studio 測試提示。
- 使用
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 做為提示的背景資訊提供給生成模型。
- 在 Google Cloud 控制台中,開啟 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.

- 然後輸入提示詞。

答案會包含價格、說明,以及模型根據樹木和地點資訊從外部來源取得的補充資訊。
在 SQL 中執行提示
您也可以使用 Cloud SQL AI 整合 Gemini Enterprise Agent Platform,直接在 SQL 中取得生成模型的相關回應。
首先,註冊模型。
- 註冊
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. 恭喜
恭喜您完成本程式碼研究室。
Google Cloud 學習路徑
這個實驗室屬於「Google Cloud 學習路徑:打造可用於正式環境的 AI」的一部分。
- 探索完整課程,從設計原型開始,一步步把專案投入正式環境。
- 使用主題標記
#ProductionReadyAI分享你的進度。
涵蓋內容
- 如何部署 MySQL 適用的 Cloud SQL 執行個體
- 如何建立資料庫及啟用 Cloud SQL AI 整合
- 如何將資料載入資料庫
- 如何使用 Cloud SQL Studio
- 如何在 Cloud SQL 中使用 Vertex AI 嵌入模型
- 如何使用 Agent Platform Studio
- 如何使用 Gemini Enterprise Agent Platform 模型擴充結果
- 如何使用向量索引提升效能
試試 AlloyDB 的類似程式碼實驗室,或 PostgreSQL 適用的 Cloud SQL 程式碼實驗室。
問卷調查
輸出內容: