開始使用 MySQL 適用的 Cloud SQL 中的向量嵌入

開始使用 MySQL 適用的 Cloud SQL 中的向量嵌入

程式碼研究室簡介

subject上次更新時間:4月 22, 2025
account_circle作者:Gleb Otochkin

1. 簡介

在本程式碼研究室中,您將瞭解如何結合向量搜尋與 Vertex AI 嵌入功能,使用 Cloud SQL for MySQL Vertex AI 整合。

30b7c4dcdd8bb68f.png

  • 具備 Google Cloud 控制台的基本知識
  • 指令列介面和 Cloud Shell 的基本技能
  • 如何部署 MySQL 適用的 Cloud SQL 執行個體
  • 如何建立資料庫並啟用 Cloud SQL AI 整合
  • 如何將資料載入資料庫
  • 如何在 Cloud SQL 中使用 Vertex AI 嵌入模型
  • 如何使用 Vertex AI 生成式模型豐富結果
  • 如何使用向量索引提升效能

軟硬體需求

  • Google Cloud 帳戶和 Google Cloud 專案
  • 支援 Google Cloud 控制台和 Cloud Shell 的網路瀏覽器,例如 Chrome

2. 設定和需求

自助式環境設定

  1. 登入 Google Cloud 控制台,然後建立新專案或重複使用現有專案。如果您還沒有 Gmail 或 Google Workspace 帳戶,請務必建立帳戶

fbef9caa1602edd0.png

a99b7ace416376c4.png

5e3ff691252acf41.png

  • 「Project name」是這個專案參與者的顯示名稱。這是 Google API 不會使用的字元字串。您隨時可以更新。
  • 專案 ID 在所有 Google Cloud 專案中都是不重複的值,且無法變更 (設定後即無法變更)。Cloud 控制台會自動產生唯一字串,您通常不需要特別留意。在大多數程式碼研究室中,您都需要參照專案 ID (通常會標示為 PROJECT_ID)。如果您不喜歡產生的 ID,可以產生另一個隨機 ID。或者,您也可以自行嘗試,看看是否可用。在這個步驟後就無法變更,且會在專案期間維持不變。
  • 提醒您,有些 API 會使用第三個值「專案編號」。如要進一步瞭解這三個值,請參閱說明文件
  1. 接下來,您需要在 Cloud 控制台中啟用帳單功能,才能使用 Cloud 資源/API。執行這個程式碼研究室不會產生太多費用,甚至可能完全不會產生費用。如要關閉資源,避免在本教學課程結束後繼續產生費用,您可以刪除建立的資源或專案。Google Cloud 新使用者可享有 $300 美元的免費試用期

啟動 Cloud Shell

雖然 Google Cloud 可透過筆記型電腦遠端操作,但在本程式碼研究室中,您將使用 Google Cloud Shell,這是在雲端運作的指令列環境。

Google Cloud 控制台中,按一下右上方工具列的 Cloud Shell 圖示:

55efc1aaa7a4d3ad.png

佈建並連線至環境的作業需要一些時間才能完成。完成後,畫面應如下所示:

7ffe5cbb04455448.png

這個虛擬機器會載入您需要的所有開發工具。提供永久的 5 GB 主目錄,而且在 Google Cloud 中運作,可大幅提升網路效能和驗證功能。您可以在瀏覽器中完成本程式碼研究室的所有工作。您不需要安裝任何東西。

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

建立 MySQL 適用的 Cloud SQL 執行個體

您可以在建立執行個體時啟用 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

我們可以透過 Cloud Shell 確認連線執行狀況

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>

啟用 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

將 Vertex AI 存取權授予 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 for mySQL、SDK 或 Cloud SQL Studio)。我們將使用 SDK (gcloud) 建立資料庫。

在 Cloud Shell 中執行指令建立資料庫

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

6. 載入資料

接下來,我們需要在資料庫中建立物件並載入資料。我們將使用虛構的 Cymbal 商店資料。資料可使用 SQL (結構定義) 和 CSV (資料) 格式提供。

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 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 程式碼,建立資料表、索引和序列。

接下來,我們要載入 cymbal_products 資料。我們使用相同的 curlmysql 公用程式。

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;"

如果您有自己的範例資料,且 CSV 檔案與 Cloud 控制台提供的 Cloud SQL 匯入工具相容,可以使用該工具,而非本文介紹的方法。

7. 建立嵌入

接下來,我們將使用 Google Vertex AI 的 textembedding-005 模型,為產品說明建立嵌入資料,並將這些資料儲存在資料表 cymbal_products 的新欄位中。

如要儲存向量資料,我們需要在 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

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

產生 2000 列的向量嵌入資料通常需要 5 分鐘內,但有時可能需要稍微久一點,但通常會更快完成。

8. 執行相似度搜尋

我們現在可以使用相似度搜尋功能,根據為說明計算的向量值,以及使用相同嵌入模型為要求產生的向量值,執行搜尋作業。

您可以透過相同的指令列介面執行 SQL 查詢,也可以改用 Cloud SQL Studio 執行。任何多列和複雜查詢都建議在 Cloud SQL Studio 中管理。

建立使用者

我們需要一個可使用 Cloud SQL Studio 的新使用者。我們將建立內建類型的使用者學生,並使用與超級使用者相同的密碼。

在 Cloud Shell 中執行:

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

啟動 Cloud SQL Studio

在控制台中,按一下我們先前建立的 Cloud SQL 執行個體。

667b658dbf98eb0b.png

在右側面板中開啟後,我們可以看到 Cloud SQL Studio。按一下該按鈕。

a879e8ac914a8ce9.png

系統會開啟對話方塊,要求您提供資料庫名稱和憑證:

  • 資料庫:quickstart_db
  • 使用者:student
  • 密碼:您為使用者記下的密碼

然後按一下「驗證」按鈕。

36e6036847333d18.png

系統會開啟下一個視窗,請點選右側的「Editor」分頁,開啟 SQL 編輯器。

d803b7b6a798094f.png

我們現在可以執行查詢了。

執行查詢

執行查詢,取得與客戶要求最相關的可用產品清單。我們要傳送給 Vertex AI 以取得向量值的要求,聽起來就像「這裡適合種植哪種果樹?」

以下是可以執行的查詢,可使用 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 編輯器,然後按下「RUN」按鈕,或將查詢貼到連線至 quickstart_db 資料庫的指令列工作階段。

dffc70835901cf03.png

以下是符合查詢的產品清單。

+-----------------+----------------------------------------------------------------------------------+------------+----------+---------------------+
| 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 秒。我們得到的結果與 cosine_distance 函式相同。

9. 使用擷取的資料改善 LLM 回覆

我們可以使用執行查詢的結果,改善向用戶端應用程式傳送的生成式 AI 大型語言模型回覆,並使用提供的查詢結果,做為向 Vertex AI 生成式基礎語言模型提示的一部分,準備有意義的輸出內容。

為此,我們需要使用向量搜尋結果產生 JSON,然後在 Vertex AI 中使用產生的 JSON 和 LLM 模型提示,建立有意義的輸出內容。在第一步中,我們會產生 JSON,然後在 Vertex AI Studio 中進行測試,最後將 JSON 納入可在應用程式中使用的 SQL 陳述式。

以 JSON 格式產生輸出內容

修改查詢,以 JSON 格式產生輸出內容,並只傳回一列資料,以便傳遞至 Vertex AI

以下是使用 ANN 搜尋的查詢範例:

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"}]

在 Vertex AI Studio 中執行提示

我們可以使用產生的 JSON,在 Vertex AI Studio 中將其做為生成式 AI 文字模型提示的一部分

在雲端控制台中開啟 Vertex AI Studio 提示。

411ffb9d164ac140.png

系統可能會要求您啟用其他 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:
{"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.

以下是使用 JSON 值和 gemini-2.0-flash 模型執行提示的結果:

9839af512686130d.png

在本例中,我們使用語意搜尋結果和所提及郵遞區碼中可用的最佳相符產品,從模型中取得以下答案。

在 PSQL 中執行提示

我們也可以使用 Cloud SQL AI 與 Vertex AI 的整合功能,直接在資料庫中使用 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('publishers/google/models/gemini-2.0-flash-001:generateContent',
        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;

以下是輸出內容範例。輸出結果可能因模型版本和參數而異:

"Okay, I see you're looking for fruit trees that grow well in your area. Based on the available product, the **Malus Domestica** (Apple Tree) is a great option to consider!\n\n* **Product:** Malus Domestica (Apple Tree)\n* **Description:** This classic apple tree grows to about 30 feet tall and provides beautiful seasonal color with green leaves in summer and fiery colors in the fall. It's known for its strength and provides good shade. Most importantly, it produces delicious apples!\n* **Price:** \\$100.00\n* **Growing Zones:** This particular apple tree is well-suited for USDA zones 4-8. Since your zip code is 93230, you are likely in USDA zone 9a or 9b. While this specific tree is rated for zones 4-8, with proper care and variety selection, apple trees can still thrive in slightly warmer climates. You may need to provide extra care during heat waves.\n\n**Recommendation:** I would recommend investigating varieties of Malus Domestica suited to slightly warmer climates or contacting a local nursery/arborist to verify if it is a good fit for your local climate conditions.\n"

輸出內容會以 Markdown 格式提供。

10. 建立最近鄰居索引

我們的資料集相對較小,回應時間主要取決於與 AI 模型的互動情形。但如果您有數百萬個向量,向量搜尋可能會占據大量回應時間,並對系統造成高負載。為了改善這個問題,我們可以建立向量索引。

建立 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. 恭喜

恭喜您完成程式碼研究室!

涵蓋內容

  • 如何部署 MySQL 適用的 Cloud SQL 執行個體
  • 如何建立資料庫並啟用 Cloud SQL AI 整合
  • 如何將資料載入資料庫
  • 如何在 Cloud SQL 中使用 Vertex AI 嵌入模型
  • 如何使用 Vertex AI 生成式模型豐富結果
  • 如何使用向量索引提升效能

試試類似的 AlloyDB 程式碼研究室PostgreSQL 適用的 Cloud SQL 程式碼研究室

13. 問卷調查

輸出:

您要如何使用這個教學課程?