תחילת העבודה עם Vector Embeddings ב-Cloud SQL ל-MySQL

תחילת העבודה עם Vector Embeddings ב-Cloud SQL ל-MySQL

מידע על Codelab זה

subjectהעדכון האחרון: אפר׳ 22, 2025
account_circleנכתב על ידי Gleb Otochkin

1.‏ מבוא

בשיעור ה-Codelab הזה תלמדו איך להשתמש ב-Cloud SQL לשילוב של MySQL עם Vertex AI, על ידי שילוב של חיפוש וקטורים עם הטמעות (embeddings) של Vertex AI.

30b7c4dcdd8bb68f.png

  • הבנה בסיסית של Google Cloud, מסוף
  • מיומנויות בסיסיות בממשק שורת הפקודה וב-Cloud Shell
  • איך לפרוס מכונה של Cloud SQL ל-MySQL
  • איך יוצרים מסד נתונים ומפעילים את השילוב של Cloud SQL עם AI
  • איך טוענים נתונים למסד הנתונים
  • איך משתמשים במודל הטמעה של Vertex AI ב-Cloud SQL
  • איך להעשיר את התוצאה באמצעות מודל גנרטיבי של Vertex AI
  • איך לשפר את הביצועים באמצעות אינדקס וקטור

מה צריך להכין

  • חשבון Google Cloud ופרויקט ב-Google Cloud
  • דפדפן אינטרנט כמו Chrome שתומך במסוף Google Cloud וב-Cloud Shell

2.‏ הגדרה ודרישות

הגדרת סביבה בקצב אישי

  1. נכנסים למסוף Google Cloud ויוצרים פרויקט חדש או משתמשים מחדש בפרויקט קיים. אם עדיין אין לכם חשבון Gmail או חשבון Google Workspace, עליכם ליצור חשבון.

fbef9caa1602edd0.png

a99b7ace416376c4.png

5e3ff691252acf41.png

  • שם הפרויקט הוא השם המוצג של המשתתפים בפרויקט. זוהי מחרוזת תווים שלא משמשת את Google APIs. תמיד אפשר לעדכן אותו.
  • מזהה הפרויקט הוא ייחודי לכל הפרויקטים ב-Google Cloud ואי אפשר לשנות אותו אחרי שמגדירים אותו. מסוף Cloud יוצר מחרוזת ייחודית באופן אוטומטי. בדרך כלל לא משנה מה המחרוזת הזו. ברוב ה-codelabs תצטרכו להפנות למזהה הפרויקט (בדרך כלל מזהים אותו בתור PROJECT_ID). אם המזהה שנוצר לא מוצא חן בעיניכם, תוכלו ליצור מזהה אקראי אחר. לחלופין, אפשר לנסות כתובת משלכם ולבדוק אם היא זמינה. לא ניתן לשנות אותו אחרי השלב הזה, והוא יישאר למשך כל פרק הזמן של הפרויקט.
  • לידיעתך, יש ערך שלישי, מספר פרויקט, שמשתמשים בו בחלק מממשקי ה-API. מידע נוסף על כל שלושת הערכים האלה זמין במסמכי התיעוד.
  1. בשלב הבא, כדי להשתמש במשאבים או ב-API של Cloud, תצטרכו להפעיל את החיוב במסוף Cloud. השלמת הקודלאב הזה לא תעלה הרבה, אם בכלל. כדי להשבית את המשאבים ולמנוע חיובים אחרי סיום המדריך, אפשר למחוק את המשאבים שיצרתם או למחוק את הפרויקט. משתמשים חדשים ב-Google Cloud זכאים להשתתף בתוכנית תקופת ניסיון בחינם בסך 300$.

הפעלת Cloud Shell

אפשר להפעיל את Google Cloud מרחוק מהמחשב הנייד, אבל בסדנת הקוד הזו נשתמש ב-Google Cloud Shell, סביבת שורת פקודה שפועלת ב-Cloud.

במסוף Google Cloud, לוחצים על סמל Cloud Shell בסרגל הכלים שבפינה הימנית העליונה:

55efc1aaa7a4d3ad.png

ההקצאה והחיבור לסביבת העבודה אמורים להימשך רק כמה רגעים. בסיום, אמור להופיע משהו כזה:

7ffe5cbb04455448.png

המכונה הווירטואלית הזו כוללת את כל הכלים הדרושים למפתחים. יש בה ספריית בית בנפח מתמיד של 5GB והיא פועלת ב-Google Cloud, משפרת מאוד את ביצועי הרשת ואת האימות. אתם יכולים לבצע את כל העבודה בקודלאב הזה בדפדפן. אין צורך להתקין שום דבר.

3.‏ לפני שמתחילים

הפעלת ה-API

ב-Cloud Shell, מוודאים שמזהה הפרויקט מוגדר:

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 ל-MySQL

אפשר להפעיל את הדגל 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

מעניקים לחשבון השירות של 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 .כדי לעשות זאת, יש לנו אפשרויות שונות, כמו לקוחות מסדי נתונים בשורת הפקודה, כמו mysql ל-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 תהיה הסביבה העיקרית שלנו להתחברות למסד נתונים, ליצירת כל האובייקטים ולטעינה של הנתונים.

קודם כול, צריך להוסיף את כתובת ה-IP הציבורית של Cloud Shell לרשימת הרשתות המורשות של המכונה של 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. אנחנו משתמשים באותם כלי curl ו-mysql.

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 SQL שזמין במסוף Cloud, תוכלו להשתמש בו במקום בגישה המוצגת.

7.‏ יצירת הטמעות

השלב הבא הוא ליצור הטמעות (embeddings) של תיאורי המוצרים באמצעות המודל textembedding-005 מ-Google Vertex AI, ולאחסן אותן בעמודה החדשה בטבלה 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 באמצעות פונקציית ההטמעה.

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 דקות, אבל לפעמים התהליך נמשך קצת יותר זמן, ולרוב הוא מסתיים הרבה יותר מהר.

8.‏ הפעלת חיפוש הדמיון

עכשיו אנחנו יכולים להריץ את החיפוש באמצעות חיפוש דמיון שמבוסס על ערכי וקטורים שמחושבים לתיאורים ועל ערך הווקטור שאנחנו יוצרים לבקשה שלנו באמצעות אותו מודל הטמעה.

אפשר להריץ את שאילתת ה-SQL מאותו ממשק שורת הפקודה, או לחלופין מ-Cloud SQL Studio. עדיף לנהל שאילתות מורכבות עם כמה שורות ב-Cloud SQL Studio.

יצירת משתמש

אנחנו צריכים משתמש חדש שיכול להשתמש ב-Cloud SQL Studio. אנחנו הולכים ליצור משתמש מובנה מסוג תלמיד עם אותה סיסמה שבה השתמשנו למשתמש root.

ב-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

החלון הבא ייפתח, ועליך ללחוץ על הכרטיסייה 'עריכה' בצד שמאל כדי לפתוח את עורך ה-SQL.

d803b7b6a798094f.png

עכשיו אנחנו מוכנים להריץ את השאילתות שלנו.

הרצת שאילתה

מריצים שאילתה כדי לקבל רשימה של מוצרים זמינים שקשורים בצורה הכי הדוקה לבקשה של הלקוח. הבקשה שנעביר ל-Vertex AI כדי לקבל את ערך הווקטור תישמע בערך כך: "What kind of fruit trees grow well here?‎"

זו השאילתה שאפשר להריץ כדי לבחור את 5 הפריטים הראשונים הכי מתאימים לבקשה שלנו באמצעות הפונקציה cosine_distance:

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, לוחצים על 'הפעלה' או מדביקים אותה בסשן של שורת הפקודה שמתחבר למסד הנתונים 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)

ביצוע השאילתה נמשך 0.13 שניות באמצעות הפונקציה cosine_distance.

עכשיו מריצים את אותה שאילתה, אבל באמצעות חיפוש KNN באמצעות הפונקציה approx_distance. אם אין לנו אינדקס 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 באמצעות נתונים שאוחזרו

אנחנו יכולים לשפר את התגובה של LLM ל-Gen AI לאפליקציית לקוח באמצעות התוצאה של השאילתה שבוצעה, ולהכין פלט בעל משמעות באמצעות תוצאות השאילתה שסופקו כחלק מההנחיה ל-Vertex AI generative foundation language model.

כדי לעשות זאת, אנחנו צריכים ליצור קובץ JSON עם התוצאות שלנו מחיפוש הווקטור, ואז להשתמש בקובץ ה-JSON שנוצר כתוספת להנחיה של מודל LLM ב-Vertex AI כדי ליצור פלט בעל משמעות. בשלב הראשון יוצרים את קובץ ה-JSON, לאחר מכן בודקים אותו ב-Vertex AI Studio ובשלב האחרון משלבים אותו בהצהרת 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 שנוצר כדי לספק אותו כחלק מההנחיה למודל טקסט של AI גנרטיבי ב-Vertex AI Studio

פותחים את ההנחיה של Vertex AI Studio במסוף Cloud.

411ffb9d164ac140.png

יכול להיות שתתבקשו להפעיל ממשקי API נוספים, אבל אתם יכולים להתעלם מהבקשה. אין צורך ב-API נוסף כדי להשלים את שיעור ה-Lab.

זו ההנחיה שבה נשתמש:

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.

כך זה נראה כשמחליפים את placeholder ה-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 ישירות במסד הנתונים.

עכשיו אפשר להשתמש ב-generated בשאילתת משנה עם תוצאות JSON כדי לספק אותו כחלק מההנחיה למודל טקסט של AI גנרטיבי באמצעות SQL.

מריצים את השאילתה בסשן של 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.‏ מזל טוב

כל הכבוד על השלמת ה-Codelab.

מה עסקנו בו

  • איך לפרוס מכונה של Cloud SQL ל-MySQL
  • איך יוצרים מסד נתונים ומפעילים את השילוב של Cloud SQL עם AI
  • איך טוענים נתונים למסד הנתונים
  • איך משתמשים במודל הטמעה של Vertex AI ב-Cloud SQL
  • איך להעשיר את התוצאה באמצעות מודל גנרטיבי של Vertex AI
  • איך לשפר את הביצועים באמצעות אינדקס וקטור

כדאי לנסות codelab דומה ל-AlloyDB או codelab ל-Cloud SQL ל-Postgres

13.‏ סקר

פלט:

איך תוכלו להשתמש במדריך הזה?