1. מבוא
ב-codelab הזה מוסבר איך לפרוס את AlloyDB עם אופרטורים של AI ואיך להשתמש בהם למשימות כמו חיפוש סמנטי, צירופים ודירוג תוצאות.
דרישות מוקדמות
- הבנה בסיסית של Google Cloud ושל המסוף
- מיומנויות בסיסיות בממשק שורת הפקודה וב-Cloud Shell
מה תלמדו
- איך פורסים אשכול AlloyDB ומופע ראשי
- איך מפעילים אופרטורים של AlloyDB AI
- איך משתמשים באופרטורים שונים של AlloyDB AI
- איך משתמשים בסידור מחדש באופרטורים של AlloyDB AI כדי לשפר את תוצאות הפלט
מה תצטרכו
- חשבון Google Cloud ופרויקט Google Cloud
- דפדפן אינטרנט כמו Chrome שתומך במסוף Google Cloud וב-Cloud Shell
2. הגדרה ודרישות
הגדרת פרויקט
- נכנסים למסוף Google Cloud. אם עדיין אין לכם חשבון Gmail או Google Workspace, אתם צריכים ליצור חשבון.
משתמשים בחשבון לשימוש אישי במקום בחשבון לצורכי עבודה או בחשבון בית ספרי.
- יוצרים פרויקט חדש או משתמשים בפרויקט קיים. כדי ליצור פרויקט חדש במסוף Google Cloud, לוחצים בכותרת על הלחצן 'בחירת פרויקט' שפותח חלון קופץ.

בחלון Select a project (בחירת פרויקט), לוחצים על הלחצן New Project (פרויקט חדש) כדי לפתוח תיבת דו-שיח לפרויקט החדש.

בתיבת הדו-שיח, מזינים את שם הפרויקט המועדף ובוחרים את המיקום.

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

- לוחצים על הלחצן כאן אפשר לגשת לזיכויים. תועברו לדף להגדרת פרופיל החיוב. אם מוצג לכם מסך הרשמה לתקופת ניסיון בחינם, לחצו על 'ביטול' והמשיכו לקשר את החיוב.

- לוחצים על 'אישור'. עכשיו אתם מחוברים לחשבון לחיוב ב-Google Cloud Platform לניסיון.

הגדרת חשבון לחיוב לשימוש אישי
אם הגדרתם חיוב באמצעות קרדיטים ל-Google Cloud, אתם יכולים לדלג על השלב הזה.
כדי להגדיר חשבון לחיוב לשימוש אישי, עוברים לכאן כדי להפעיל את החיוב ב-Cloud Console.
הערות:
- העלות של השלמת ה-Lab הזה במשאבי Cloud צריכה להיות פחות מ-3 דולר ארה"ב.
- כדי למנוע חיובים נוספים, אפשר למחוק את המשאבים לפי השלבים בסוף שיעור ה-Lab הזה.
- משתמשים חדשים זכאים לתקופת ניסיון בחינם בשווי 300$.
הפעלת Cloud Shell
אפשר להפעיל את Google Cloud מרחוק מהמחשב הנייד, אבל ב-codelab הזה תשתמשו ב-Google Cloud Shell, סביבת שורת פקודה שפועלת בענן.
ב-מסוף Google Cloud, לוחצים על סמל Cloud Shell בסרגל הכלים שבפינה הימנית העליונה:

אפשר גם ללחוץ על G ואז על S. אם אתם נמצאים במסוף Google Cloud, או אם אתם משתמשים בקישור הזה, רצף הפעולות הזה יפעיל את Cloud Shell.
יחלפו כמה רגעים עד שההקצאה והחיבור לסביבת העבודה יושלמו. בסיום התהליך, אמור להופיע משהו כזה:

המכונה הווירטואלית הזו כוללת את כל הכלים שדרושים למפתחים. יש בה ספריית בית בנפח מתמיד של 5GB והיא פועלת ב-Google Cloud, מה שמשפר מאוד את הביצועים והאימות ברשת. אפשר לבצע את כל העבודה ב-codelab הזה בדפדפן. לא צריך להתקין שום דבר.
3. לפני שמתחילים
הפעלת ה-API
כדי להשתמש ב-AlloyDB, ב-Compute Engine, ב-Networking services וב-Vertex AI, צריך להפעיל את ממשקי ה-API המתאימים בפרויקט Google Cloud.
במסוף Cloud Shell, מוודאים שמזהה הפרויקט מוגדר:
gcloud config set project [YOUR-PROJECT-ID]
מגדירים את משתנה הסביבה PROJECT_ID:
PROJECT_ID=$(gcloud config get-value project)
מפעילים את כל השירותים הנדרשים:
gcloud services enable alloydb.googleapis.com \
compute.googleapis.com \
cloudresourcemanager.googleapis.com \
servicenetworking.googleapis.com \
aiplatform.googleapis.com \
discoveryengine.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 alloydb.googleapis.com \
compute.googleapis.com \
cloudresourcemanager.googleapis.com \
servicenetworking.googleapis.com \
aiplatform.googleapis.com \
discoveryengine.googleapis.com
Operation "operations/acat.p2-4470404856-1f44ebd8-894e-4356-bea7-b84165a57442" finished successfully.
מבוא לממשקי ה-API
- AlloyDB API (
alloydb.googleapis.com) מאפשר לכם ליצור ולנהל אשכולות של AlloyDB ל-PostgreSQL, ולשנות את גודלם. הוא מספק שירות מנוהל של מסד נתונים שתואם ל-PostgreSQL ומיועד לעומסי עבודה כבדים בטרנזקציות ובניתוחים בארגונים. - Compute Engine API (
compute.googleapis.com) מאפשר לכם ליצור ולנהל מכונות וירטואליות (VM), דיסקים לאחסון מתמיד והגדרות רשת. היא מספקת את הבסיס של תשתית כשירות (IaaS) שנדרש להפעלת עומסי העבודה ולאירוח התשתית הבסיסית של שירותים מנוהלים רבים. - Cloud Resource Manager API (
cloudresourcemanager.googleapis.com) מאפשר לכם לנהל באופן פרוגרמטי את המטא-נתונים וההגדרות של הפרויקט שלכם ב-Google Cloud. היא מאפשרת לכם לארגן משאבים, לטפל במדיניות של ניהול זהויות והרשאות גישה (IAM) ולאמת הרשאות בהיררכיית הפרויקט. - Service Networking API (
servicenetworking.googleapis.com) מאפשר לכם להגדיר אוטומטית קישוריות פרטית בין רשת Virtual Private Cloud (VPC) לבין שירותים מנוהלים של Google. היא נדרשת במיוחד כדי ליצור גישה לכתובות IP פרטיות לשירותים כמו AlloyDB, כדי שהם יוכלו לתקשר בצורה מאובטחת עם המשאבים האחרים שלכם. - Vertex AI API (
aiplatform.googleapis.com) מאפשר לאפליקציות שלכם ליצור מודלים של למידת מכונה, לפרוס אותם ולבצע להם התאמה לעומס (scaling). הוא מספק ממשק מאוחד לכל שירותי ה-AI של Google Cloud, כולל גישה למודלים של AI גנרטיבי (כמו Gemini) ואימון מודלים בהתאמה אישית.
4. פריסת AlloyDB
יצירת אשכול AlloyDB ומופע ראשי. אפשר לפרוס אותו באמצעות סקריפט מוכן שיפרוס את כל המשאבים הנדרשים, או לבצע את הפריסה שלב אחר שלב בעצמכם.
פריסת AlloyDB באמצעות סקריפט אוטומטי
בגישה הזו נעשה שימוש בסקריפט אוטומטי כדי לפרוס את אשכול AlloyDB, והסקריפט מספק את המידע הנדרש כדי להתחיל לעבוד עם המשאבים שנפרסו.
ב-Cloud Shell, מריצים את הפקודה terminate כדי לשכפל את סקריפט הפריסה.
REPO_NAME="codelabs"
REPO_URL="https://github.com/GoogleCloudPlatform/$REPO_NAME"
SOURCE_DIR="alloydb-ai-operators"
git clone --no-checkout --filter=blob:none --depth=1 $REPO_URL
cd $REPO_NAME
git sparse-checkout set $SOURCE_DIR
git checkout
cd $SOURCE_DIR
מריצים את סקריפט הפריסה.
./deploy_alloydb.sh
הסקריפט יפעל במשך זמן מה – בדרך כלל כ-5 עד 7 דקות. לאחר מכן, המערכת תספק מידע על אשכול AlloyDB שנפרס. חשוב לדעת שהסיסמה תהיה שונה – כדאי לרשום את הסיסמה איפשהו לשימוש עתידי.
... <redacted> ... Creating primary instance: alloydb-aip-01-pr (8 vCPUs for TRIAL cluster) Operation ID: operation-1765988049916-646282264938a-bddce198-9f248715 Creating instance...done. ---------------------------------------- Deployment Process Completed Cluster: alloydb-aip-01 (TRIAL) Instance: alloydb-aip-01-pr Region: us-central1 Initial Password: JBBoDTgixzYwYpkF (if new cluster) ----------------------------------------
אפשר לראות אותו גם במסוף האינטרנט.

פריסת AlloyDB שלב אחר שלב באמצעות Google Cloud SDK
בקטע הבא מוסבר איך ליצור אשכול ומופע של AlloyDB באמצעות Google Cloud SDK. אם כבר פרסתם אותו באמצעות הסקריפט בשלב הקודם, אפשר לדלג על השלב הזה ולעבור ישירות אל 'הכנת מסד הנתונים'.
אם אתם מעדיפים להשתמש במסוף עם ממשק משתמש גרפי באינטרנט, תוכלו לפעול לפי ההוראות שמפורטות כאן.
לפני שיוצרים אשכול AlloyDB, צריך להגדיר טווח של כתובות IP פרטיות שיהיה זמין ב-VPC לשימוש במכונת AlloyDB העתידית. אם אין לנו את זה, אנחנו צריכים ליצור אותו, להקצות אותו לשימוש בשירותים פנימיים של Google, ואז נוכל ליצור את האשכול ואת המופע.
יצירת טווח כתובות IP פרטיות
אנחנו צריכים להגדיר גישה לשירות פרטי ב-VPC שלנו בשביל AlloyDB. ההנחה כאן היא שיש לנו רשת VPC 'ברירת מחדל' בפרויקט, והיא תשמש לכל הפעולות.
יוצרים את טווח כתובות ה-IP הפרטיות:
gcloud compute addresses create psa-range \
--global \
--purpose=VPC_PEERING \
--prefix-length=24 \
--description="VPC private service access" \
--network=default
יצירת חיבור פרטי באמצעות טווח כתובות ה-IP שהוקצה:
gcloud services vpc-peerings connect \
--service=servicenetworking.googleapis.com \
--ranges=psa-range \
--network=default
הפלט הצפוי במסוף:
student@cloudshell:~ (test-project-402417)$ gcloud compute addresses create psa-range \
--global \
--purpose=VPC_PEERING \
--prefix-length=24 \
--description="VPC private service access" \
--network=default
Created [https://www.googleapis.com/compute/v1/projects/test-project-402417/global/addresses/psa-range].
student@cloudshell:~ (test-project-402417)$ gcloud services vpc-peerings connect \
--service=servicenetworking.googleapis.com \
--ranges=psa-range \
--network=default
Operation "operations/pssn.p24-4470404856-595e209f-19b7-4669-8a71-cbd45de8ba66" finished successfully.
student@cloudshell:~ (test-project-402417)$
יצירת אשכול AlloyDB
בקטע הזה אנחנו יוצרים אשכול AlloyDB באזור us-central1.
מגדירים סיסמה למשתמש postgres. אתם יכולים להגדיר סיסמה משלכם או להשתמש בפונקציה אקראית כדי ליצור סיסמה
export PGPASSWORD=`openssl rand -hex 12`
הפלט הצפוי במסוף:
student@cloudshell:~ (test-project-402417)$ export PGPASSWORD=`openssl rand -hex 12`
חשוב לשמור את הסיסמה של PostgreSQL לשימוש עתידי.
echo $PGPASSWORD
תצטרכו את הסיסמה הזו בעתיד כדי להתחבר למופע כמשתמש postgres. מומלץ לרשום את הסיסמה או להעתיק אותה למקום כלשהו כדי שתוכלו להשתמש בה בהמשך.
הפלט הצפוי במסוף:
student@cloudshell:~ (test-project-402417)$ echo $PGPASSWORD bbefbfde7601985b0dee5723 (Note: Yours will be different!)
יצירת אשכול לתקופת ניסיון בחינם
אם עדיין לא השתמשתם ב-AlloyDB, אתם יכולים ליצור אשכול לתקופת ניסיון בחינם:
מגדירים את האזור ואת שם אשכול AlloyDB. אנחנו נשתמש באזור us-central1 וב-alloydb-aip-01 כשם האשכול:
export REGION=us-central1
export ADBCLUSTER=alloydb-aip-01
מריצים את הפקודה ליצירת האשכול:
gcloud alloydb clusters create $ADBCLUSTER \
--password=$PGPASSWORD \
--network=default \
--region=$REGION \
--subscription-type=TRIAL
הפלט הצפוי במסוף:
export REGION=us-central1
export ADBCLUSTER=alloydb-aip-01
gcloud alloydb clusters create $ADBCLUSTER \
--password=$PGPASSWORD \
--network=default \
--region=$REGION \
--subscription-type=TRIAL
Operation ID: operation-1697655441138-6080235852277-9e7f04f5-2012fce4
Creating cluster...done.
יוצרים מכונת AlloyDB ראשית לאשכול באותו סשן של Cloud Shell. אם החיבור ינותק, תצטרכו להגדיר מחדש את משתני הסביבה של שם האזור ושם האשכול.
gcloud alloydb instances create $ADBCLUSTER-pr \
--instance-type=PRIMARY \
--cpu-count=8 \
--region=$REGION \
--cluster=$ADBCLUSTER
הפלט הצפוי במסוף:
student@cloudshell:~ (test-project-402417)$ gcloud alloydb instances create $ADBCLUSTER-pr \
--instance-type=PRIMARY \
--cpu-count=8 \
--region=$REGION \
--availability-type ZONAL \
--cluster=$ADBCLUSTER
Operation ID: operation-1697659203545-6080315c6e8ee-391805db-25852721
Creating instance...done.
יצירת אשכול AlloyDB Standard
אם זה לא אשכול ה-AlloyDB הראשון שלכם בפרויקט, ממשיכים ליצירה של אשכול רגיל. אם כבר יצרתם אשכול בתקופת ניסיון בחינם בשלב הקודם, אפשר לדלג על השלב הזה.
מגדירים את האזור ואת שם אשכול AlloyDB. אנחנו נשתמש באזור us-central1 וב-alloydb-aip-01 כשם האשכול:
export REGION=us-central1
export ADBCLUSTER=alloydb-aip-01
מריצים את הפקודה ליצירת האשכול:
gcloud alloydb clusters create $ADBCLUSTER \
--password=$PGPASSWORD \
--network=default \
--region=$REGION
הפלט הצפוי במסוף:
export REGION=us-central1
export ADBCLUSTER=alloydb-aip-01
gcloud alloydb clusters create $ADBCLUSTER \
--password=$PGPASSWORD \
--network=default \
--region=$REGION
Operation ID: operation-1697655441138-6080235852277-9e7f04f5-2012fce4
Creating cluster...done.
יוצרים מכונת AlloyDB ראשית לאשכול באותו סשן של Cloud Shell. אם החיבור ינותק, תצטרכו להגדיר מחדש את משתני הסביבה של שם האזור ושם האשכול.
gcloud alloydb instances create $ADBCLUSTER-pr \
--instance-type=PRIMARY \
--cpu-count=2 \
--region=$REGION \
--cluster=$ADBCLUSTER
הפלט הצפוי במסוף:
student@cloudshell:~ (test-project-402417)$ gcloud alloydb instances create $ADBCLUSTER-pr \
--instance-type=PRIMARY \
--cpu-count=2 \
--region=$REGION \
--availability-type ZONAL \
--cluster=$ADBCLUSTER
Operation ID: operation-1697659203545-6080315c6e8ee-391805db-25852721
Creating instance...done.
5. הכנת מסד הנתונים
צריך ליצור מסד נתונים, להפעיל את השילוב עם Vertex AI, ליצור אובייקטים של מסד נתונים ולייבא את הנתונים.
מתן ההרשאות הנדרשות ל-AlloyDB
מוסיפים הרשאות Vertex AI לסוכן השירות של AlloyDB.
פותחים כרטיסייה נוספת ב-Cloud Shell באמצעות הסימן '+' בחלק העליון.

בכרטיסייה החדשה של Cloud Shell, מריצים את הפקודה:
PROJECT_ID=$(gcloud config get-value project)
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:service-$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")@gcp-sa-alloydb.iam.gserviceaccount.com" \
--role="roles/aiplatform.user"
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:service-$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")@gcp-sa-alloydb.iam.gserviceaccount.com" \
--role="roles/discoveryengine.viewer"
הפלט הצפוי במסוף:
student@cloudshell:~ (test-project-001-402417)$ PROJECT_ID=$(gcloud config get-value project) Your active configuration is: [cloudshell-11039] student@cloudshell:~ (test-project-001-402417)$ gcloud projects add-iam-policy-binding $PROJECT_ID \ --member="serviceAccount:service-$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")@gcp-sa-alloydb.iam.gserviceaccount.com" \ --role="roles/aiplatform.user" Updated IAM policy for project [test-project-001-402417]. bindings: - members: - serviceAccount:service-4470404856@gcp-sa-alloydb.iam.gserviceaccount.com role: roles/aiplatform.user - members: ... etag: BwYIEbe_Z3U= version: 1
סוגרים את הכרטיסייה באמצעות הפקודה exit:
exit
התחברות ל-AlloyDB Studio
בפרקים הבאים אפשר להריץ את כל פקודות ה-SQL שדורשות חיבור למסד הנתונים ב-AlloyDB Studio. T
עוברים אל הדף Clusters ב-AlloyDB ל-Postgres.
פותחים את ממשק מסוף האינטרנט של אשכול AlloyDB על ידי לחיצה על המופע הראשי.

אחר כך לוחצים על AlloyDB Studio בצד ימין:

בוחרים את מסד הנתונים של postgres, את המשתמש postgres ומזינים את הסיסמה שרשמתם כשיצרתם את האשכול. לאחר מכן לוחצים על הלחצן 'אימות'.
אם הסיסמה לא עובדת או ששכחתם לרשום אותה, אתם יכולים לשנות אותה. במסמכי התיעוד מוסבר איך עושים את זה.

ממשק AlloyDB Studio ייפתח. כדי להריץ את הפקודות במסד הנתונים, לוחצים על הכרטיסייה 'שאילתה ללא שם' בצד שמאל.

ייפתח ממשק שבו אפשר להריץ פקודות SQL

יצירת מסד נתונים
מדריך מהיר ליצירת מסד נתונים.
בעורך של AlloyDB Studio, מריצים את הפקודה הבאה.
יצירת מסד נתונים:
CREATE DATABASE quickstart_db
הפלט אמור להיראות כך:
Statement executed successfully
התחברות ל-quickstart_db
מתחברים מחדש ל-Studio באמצעות הלחצן להחלפת משתמש או מסד נתונים.

מהרשימה הנפתחת בוחרים את מסד הנתונים החדש quickstart_db ומשתמשים באותו משתמש ובאותה סיסמה כמו קודם.

ייפתח חיבור חדש שבו תוכלו לעבוד עם אובייקטים ממסד הנתונים quickstart_db.
אימות התוסף google_ml
כדי להשתמש במנוע השאילתות מבוסס ה-AI, צריך לוודא שגרסת התוסף google_ml היא 1.5.2 ואילך.
ב-AlloyDB Studio, בזמן שאתם מחוברים ל-quickstart_db, מריצים את הפקודה:
SELECT extversion FROM pg_extension WHERE extname = 'google_ml_integration';
הפלט אמור להיראות כך:
1.5.2
אם הגרסה נמוכה מהגרסה הנדרשת, צריך לעדכן את התוסף.
ב-AlloyDB Studio, בזמן שאתם מחוברים ל-quickstart_db, מריצים את הפקודה:
CALL google_ml.upgrade_to_preview_version();
הפלט אמור להיראות כך:
Statement executed successfully
אחרי שההפעלה מסתיימת, בודקים שוב את הגרסה.
ב-AlloyDB Studio, בזמן שאתם מחוברים ל-quickstart_db, מריצים את הפקודה:
SELECT extversion FROM pg_extension WHERE extname = 'google_ml_integration';
הפלט אמור להיראות כך:
1.5.2
אנחנו גם צריכים להפעיל את התכונות של מנוע השאילתות מבוסס ה-AI במסד הנתונים שלנו. אפשר לעשות את זה על ידי עדכון של דגל המופע לכל מסדי הנתונים במופע, או על ידי הפעלה רק עבור מסד הנתונים שלנו. מריצים את הפקודה הבאה ב-AlloyDB Studio כדי להפעיל את התכונה במסד הנתונים quickstart_db.
ALTER DATABASE quickstart_db SET google_ml_integration.enable_ai_query_engine = 'on';
6. נתונים לדוגמה
עכשיו צריך ליצור אובייקטים במסד הנתונים ולטעון נתונים. נשתמש במערך נתונים פיקטיבי של סרטים עם כמה שורות.
מעתיקים את ההצהרות הבאות לעורך של AlloyDB Studio ולוחצים על הלחצן Run (הפעלה).
-- Drop tables if they exist to prevent errors on re-running the script
DROP TABLE IF EXISTS movie_reviews;
DROP TABLE IF EXISTS movies;
-- Create the 'movies' table
-- This table stores information about each movie.
CREATE TABLE movies (
id BIGINT PRIMARY KEY, -- Unique identifier for the movie
title TEXT NOT NULL, -- Title of the movie
description TEXT, -- A brief description or synopsis of the movie
genres TEXT, -- Comma-separated list of genres (e.g., "Action, Adventure, Sci-Fi")
actors TEXT -- Comma-separated list of main actors
);
-- Create the 'movie_reviews' table
-- This table stores reviews for the movies.
CREATE TABLE movie_reviews (
review_id BIGINT PRIMARY KEY, -- Unique identifier for the review
movie_id BIGINT NOT NULL, -- Foreign key referencing the movie being reviewed
reviewer_name TEXT, -- Name of the person who wrote the review
rating INT CHECK (rating >= 1 AND rating <= 5), -- Rating from 1 to 5 stars
review_text TEXT, -- The content of the review
review_date DATE DEFAULT CURRENT_DATE, -- Date when the review was submitted
FOREIGN KEY (movie_id) REFERENCES movies(id) ON DELETE CASCADE -- Ensures referential integrity; if a movie is deleted, its reviews are also deleted.
);
-- Insert sample data into the 'movies' table (20 rows)
INSERT INTO movies (id, title, description, genres, actors) VALUES
(1, 'Inception', 'A thief who steals information by entering people''s dreams.', 'Sci-Fi, Thriller, Action', 'Leonardo DiCaprio, Joseph Gordon-Levitt, Elliot Page'),
(2, 'The Matrix', 'A computer hacker learns about the true nature of his reality.', 'Sci-Fi, Action', 'Keanu Reeves, Laurence Fishburne, Carrie-Anne Moss'),
(3, 'Interstellar', 'A team of explorers journey through a cosmic passage beyond our world in an attempt to ensure humanity''s survival.', 'Sci-Fi, Drama, Adventure', 'Matthew McConaughey, Anne Hathaway, Jessica Chastain'), -- Updated description
(4, 'The Dark Knight', 'When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, Batman must accept one of the greatest psychological and physical tests of his ability to fight injustice.', 'Action, Crime, Drama', 'Christian Bale, Heath Ledger, Aaron Eckhart'),
(5, 'Pulp Fiction', 'The lives of two mob hitmen, a boxer, a gangster and his wife, and a pair of diner bandits intertwine in four tales of violence and redemption.', 'Crime, Drama', 'John Travolta, Uma Thurman, Samuel L. Jackson'),
(6, 'Forrest Gump', 'The presidencies of Kennedy and Johnson, the Vietnam War, the Watergate scandal and other historical events unfold from the perspective of an Alabama man with an IQ of 75.', 'Drama, Romance', 'Tom Hanks, Robin Wright, Gary Sinise'),
(7, 'The Shawshank Redemption', 'Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.', 'Drama', 'Tim Robbins, Morgan Freeman, Bob Gunton'),
(8, 'Gladiator', 'A former Roman General sets out to exact vengeance against the corrupt emperor who murdered his family and sent him into slavery.', 'Action, Adventure, Drama', 'Russell Crowe, Joaquin Phoenix, Connie Nielsen'),
(9, 'Fight Club', 'An insomniac office worker looking for a way to change his life crosses paths with a devil-may-care soap maker and they form an underground fight club that evolves into something much, much more.', 'Drama', 'Brad Pitt, Edward Norton, Meat Loaf'),
(10, 'The Lord of the Rings: The Return of the King', 'Gandalf and Aragorn lead the World of Men against Sauron''s army to draw his gaze from Frodo and Sam as they approach Mount Doom with the One Ring.', 'Action, Adventure, Drama', 'Elijah Wood, Viggo Mortensen, Ian McKellen'),
(11, 'Spirited Away', 'During her family''s move to the suburbs, a sullen 10-year-old girl wanders into a world ruled by gods, witches, and spirits, and where humans are changed into beasts.', 'Animation, Adventure, Family', 'Daveigh Chase, Suzanne Pleshette, Miyu Irino'),
(12, 'Parasite', 'Greed and class discrimination threaten the newly formed symbiotic relationship between the wealthy Park family and the destitute Kim clan.', 'Comedy, Drama, Thriller', 'Song Kang-ho, Lee Sun-kyun, Cho Yeo-jeong'),
(13, 'The Godfather', 'The aging patriarch of an organized crime dynasty transfers control of his clandestine empire to his reluctant son.', 'Crime, Drama', 'Marlon Brando, Al Pacino, James Caan'),
(14, 'Avengers: Endgame', 'After the devastating events of Avengers: Infinity War, the universe is in ruins. With the help of remaining allies, the Avengers assemble once more in order to reverse Thanos'' actions and restore balance to the universe.', 'Action, Adventure, Drama', 'Robert Downey Jr., Chris Evans, Mark Ruffalo'),
(15, 'Joker', 'In Gotham City, mentally troubled comedian Arthur Fleck is disregarded and mistreated by society. He then embarks on a downward spiral of revolution and bloody crime.', 'Crime, Drama, Thriller', 'Joaquin Phoenix, Robert De Niro, Zazie Beetz'),
(16, 'Mad Max: Fury Road', 'In a post-apocalyptic wasteland, a woman rebels against a tyrannical ruler in search for her homeland with the help of a group of female prisoners, a psychotic worshiper, and a drifter named Max.', 'Action, Adventure, Sci-Fi', 'Tom Hardy, Charlize Theron, Nicholas Hoult'),
(17, 'Coco', 'Aspiring musician Miguel, confronted with his family''s ancestral ban on music, enters the Land of the Dead to find his great-great-grandfather, a legendary singer.', 'Animation, Adventure, Family', 'Anthony Gonzalez, Gael García Bernal, Benjamin Bratt'),
(18, 'Whiplash', 'A promising young drummer enrolls at a cut-throat music conservatory where his dreams of greatness are mentored by an instructor who will stop at nothing to realize a student''s potential.', 'Drama, Music', 'Miles Teller, J.K. Simmons, Paul Reiser'),
(19, 'The Grand Budapest Hotel', 'The adventures of Gustave H, a legendary concierge at a famous hotel from the fictional Republic of Zubrowka between the first and second World Wars, and Zero Moustafa, the lobby boy who becomes his most trusted friend.', 'Adventure, Comedy, Drama', 'Ralph Fiennes, F. Murray Abraham, Mathieu Amalric'),
(20, 'Blade Runner 2049', 'Young Blade Runner K''s discovery of a long-buried secret leads him to track down former Blade Runner Rick Deckard, who''s been missing for thirty years.', 'Action, Drama, Mystery', 'Ryan Gosling, Harrison Ford, Ana de Armas');
-- Insert sample data into the 'movie_reviews' table (30 rows)
-- Reviews are linked to movies via movie_id. Includes a mix of positive and negative reviews.
-- Movie title is prepended to the review text.
INSERT INTO movie_reviews (review_id, movie_id, reviewer_name, rating, review_text) VALUES
(1, 1, 'Alice Wonderland', 5, 'Inception: Absolutely mind-bending! A masterpiece of sci-fi.'),
(2, 1, 'Bob The Critic', 2, 'Inception: Too confusing and pretentious. Didn''t enjoy it.'),
(3, 2, 'Charlie Reviewer', 5, 'The Matrix: Revolutionary visuals and a compelling story.'),
(4, 3, 'Diana Prince', 5, 'Interstellar: Visually stunning and emotionally powerful. A must-see.'),
(5, 3, 'Edward Nigma', 4, 'Interstellar: Long, but worth it for the spectacle and ideas.'),
(6, 4, 'Fiona Glenanne', 5, 'The Dark Knight: Heath Ledger''s Joker is iconic. Dark and thrilling.'),
(7, 5, 'George Costanza', 5, 'Pulp Fiction: Quirky, violent, and endlessly quotable.'),
(8, 5, 'Hannah Montana', 1, 'Pulp Fiction: Way too violent and the timeline was confusing. Hated it.'),
(9, 6, 'Ian Malcolm', 4, 'Forrest Gump: A heartwarming story with a great performance by Hanks.'),
(10, 7, 'Jane Doe', 5, 'The Shawshank Redemption: An uplifting story of hope and friendship. Perfect.'),
(11, 7, 'John Smith', 5, 'The Shawshank Redemption: Morgan Freeman is amazing. Truly a classic.'),
(12, 8, 'Kyle Broflovski', 2, 'Gladiator: Generic plot and boring action scenes. Overrated.'),
(13, 9, 'Laura Palmer', 5, 'Fight Club: Provocative and thought-provoking. Norton and Pitt are fantastic.'),
(14, 10, 'Michael Scott', 5, 'The Lord of the Rings: The Return of the King: A fitting and epic conclusion to a legendary trilogy.'),
(15, 11, 'Nancy Drew', 5, 'Spirited Away: Beautiful animation and a magical story for all ages.'),
(16, 12, 'Oscar Martinez', 5, 'Parasite: A brilliant satire with unexpected twists. Loved it!'),
(17, 12, 'Pam Beesly', 4, 'Parasite: Very intense, but incredibly well-directed and acted.'),
(18, 13, 'Quentin Coldwater', 5, 'The Godfather: A cinematic masterpiece. Brando is unforgettable.'),
(19, 14, 'Rachel Green', 3, 'Avengers: Endgame: It was okay, but felt bloated and had too many characters.'),
(20, 14, 'Steve Rogers', 5, 'Avengers: Endgame: The culmination of a decade of storytelling. Perfect ending.'),
(21, 15, 'Tony Stark', 4, 'Joker: A dark and disturbing character study. Phoenix is mesmerizing.'),
(22, 16, 'Uma Thurman', 5, 'Mad Max: Fury Road: Non-stop action and incredible practical effects. What a ride!'),
(23, 17, 'Victor Frankenstein', 5, 'Coco: A heartwarming and visually stunning celebration of family and culture.'),
(24, 18, 'Walter White', 5, 'Whiplash: Intense and gripping. J.K. Simmons is terrifyingly good.'),
(25, 19, 'Xena Warrior', 2, 'The Grand Budapest Hotel: Too quirky for its own good. Style over substance.'),
(26, 20, 'Ygritte Snow', 5, 'Blade Runner 2049: A worthy sequel that expands on the original in meaningful ways. Visually breathtaking.'),
(27, 1, 'Zack Morris', 4, 'Inception: Kept me on the edge of my seat. Very clever.'),
(28, 4, 'Buffy Summers', 5, 'The Dark Knight: The best superhero movie ever made. Ledger is a legend.'),
(29, 8, 'Clark Kent', 3, 'Gladiator: Decent action, but the story felt predictable and dragged a bit.'),
(30, 15, 'Diana Troy', 3, 'Joker: Hard to watch at times, but a powerful performance. Felt it was a bit one-note though.');
אם יש לכם נתונים לדוגמה משלכם וקובצי ה-CSV שלכם תואמים לכלי הייבוא של Cloud SQL שזמין במסוף Cloud, אתם יכולים להשתמש בהם במקום בגישה שמוצגת כאן.
7. שימוש באופרטור IF
קודם ננסה את החיפוש הרגיל באמצעות גישות סטנדרטיות של PostgreSQL.
אם ננסה לחפש סרט על הרפתקאות בחלל, נוכל לנסות את השאילתה הבאה
SELECT title,description AS movies_about_space
FROM movies
WHERE description like '%space%' OR title like '%space%';
לא נמצאו תוצאות. אבל אני בטוח שיש לנו לפחות סרט אחד שמתאים לקטגוריה הזו. אפשר לנסות להשתמש בגישה של חיפוש טקסט מלא.
SELECT title,description
FROM movies
WHERE to_tsvector('english', description) @@ to_tsquery('english', 'space');
יכול להיות שלא נקבל תוצאות בכלל. לכן, אנחנו צריכים לדעת כמה מילות מפתח או ביטויים כדי להשתמש בטכניקות 'קלאסיות' של חיפוש ב-PostgreSQL.
עכשיו אפשר לנסות להשתמש בסינון סמנטי מבוסס-AI באמצעות הפונקציה google_ml.if. הכלי ישתמש ב-AI מאחורי הקלעים כדי לבצע סינון סמנטי על סמך הבקשה בשפה טבעית.
SELECT title,description AS movies_about_space
FROM movies
WHERE
google_ml.if(
prompt => 'Here are descriptions of movies, can you return the ones about space adventures: '||description);
אנחנו מקבלים את הסרט "בין כוכבים" על סמך המשמעות הסמנטית של הבקשה, גם אם המונח "חלל" לא מופיע בשם או בתיאור. כפי ששמת לב, לא בנינו מראש שום דבר והסתמכנו באופן בלעדי על פונקציות אוטומטיות מובנות.
8. שימוש באופרטור JOIN עם האופרטור IF
מה קורה אם רוצים לצרף שתי טבלאות באמצעות סינון סמנטי מבוסס-AI? לדוגמה, אנחנו יכולים לנסות להתאים ביקורות משתמשים לסרטים על סמך ביקורות המשתמשים, אם הסרט הוזכר בביקורת.
מריצים בכרטיסייה חדשה של עורך AlloyDB Studio:
SELECT title, rating, movie_reviews
FROM movies
JOIN
movie_reviews ON
google_ml.if(
prompt => 'Does the following reviews talk about a movie mentioned? The review: ' || review_text||' and the movie title is: '||title)
AND
title='Interstellar';
קיבלנו שתי ביקורות שתואמות לבקשה שלנו על סמך שם הסרט שמוזכר בכותרת. אפשר לפשט עוד יותר את הבקשה:
SELECT title, rating, movie_reviews
FROM movies
JOIN
movie_reviews ON
google_ml.if(
prompt => 'Do we have the movie in the review?: ' || review_text||' and the movie title is: '||title)
AND
title='Interstellar';
9. הצגת תוצאות על סמך התוכן
בטבלה movie_reviews יש דירוגים לסרטים, אבל אם רוצים להטמיע דירוג משלכם, אפשר להשתמש בפונקציה google_ml.rank. אנחנו יכולים לתת ציון לביקורות על סמך תנאים שמוגדרים בשפה טבעית, ולקבל למשל את 5 הביקורות המובילות על הסרטים ולהציג את הדירוג המקורי לצורך השוואה.
SELECT rating,review_text AS top_five
FROM movie_reviews
ORDER BY google_ml.rank('Score of 7 to 10 if the review says the movie was really good, 3 to 6 if the review says it''s alright is and 1 to 2 if the review says it was not worth of time. Review: ' || review_text) DESC
LIMIT 5;
אם רוצים להציג את הדירוג החדש לצד הדירוג המקורי, אפשר להוסיף אותו לרשימת העמודות.
SELECT rating,
google_ml.rank('Score of 7 to 10 if the review says the movie was really good, 3 to 6 if the review says it''s alright is and 1 to 2 if the review says it was not worth of time. Review: ' || review_text) AS ml_rank,
review_text AS top_five
FROM movie_reviews
ORDER BY ml_rank DESC
LIMIT 5;
אלה 5 הביקורות המובילות.
rating | ml_rank | top_five
--------+---------+-----------------------------------------------------------------------
5 | 9 | The Dark Knight: Heath Ledger's Joker is iconic. Dark and thrilling.
5 | 9 | The Matrix: Revolutionary visuals and a compelling story.
5 | 9 | Interstellar: Visually stunning and emotionally powerful. A must-see.
5 | 9 | Inception: Absolutely mind-bending! A masterpiece of sci-fi.
5 | 9 | Pulp Fiction: Quirky, violent, and endlessly quotable.
(5 rows)
5 rows in set (0.13 sec)
הדירוג שנבחר היה 9 מתוך 10 לביקורות המובילות.
מידע נוסף על אופרטורים של AlloyDB AI זמין בתיעוד.
10. שיפור החיפוש הסמנטי באמצעות דירוג
אנחנו יכולים לשלב את החיפוש הסמנטי שלנו עם דירוג כדי לקבל תוצאות מדויקות יותר.
גישה למודל לדירוג מחדש
כדי להשתמש במודלים של דירוג, צריך להפעיל את Discovery Engine API ולהעניק את התפקיד discoveryengine.viewer לחשבון השירות של AlloyDB. ה-API והתפקיד הופעלו בשלבים הראשונים של שיעור ה-Lab. הפונקציה ai.rank מוצאת ומשתמשת אוטומטית במודל העדכני ביותר של דירוג מחדש ב-Vertex AI.
שימוש במודל לדירוג מחדש בשאילתות
עכשיו אנחנו יכולים להשתמש במודל לדירוג מחדש בשאילתות, כדי לשפר את תוצאות החיפוש הסמנטי, להפוך אותן לספציפיות יותר ולבחור את האפשרויות הטובות ביותר.
בוא נחפש סרטי פעולה ונמיין אותם לפי התנאים 'מחשבים ועתיד'.
WITH
action_movies AS (
SELECT
title,
description,
ROW_NUMBER() OVER (ORDER BY title, description) AS ref_number
FROM
movies
WHERE
google_ml.if(
prompt => 'The following movies are action movies. The movie title: ' || title || ' and the description is: ' || description
)
),
ranked_documents_array AS (
SELECT
ARRAY_AGG(description ORDER BY ref_number) AS docs
FROM
action_movies
),
reranked_results AS (
SELECT
r.index,
r.score
FROM
ranked_documents_array,
ai.rank(
model_id => 'semantic-ranker-default',
search_string => 'Computers and future',
documents => ranked_documents_array.docs
) AS r
)
SELECT
am.title,
left(am.description,80) as description,
rr.score
FROM
action_movies am
JOIN
reranked_results rr ON am.ref_number = rr.index
ORDER BY
rr.score DESC;
התוצאות יכללו רשימה של סרטי אקשן, ואני מקווה שסרטים על העתיד ועל מחשבים יופיעו בראש הרשימה.
title | description | score
-----------------------------------------------+----------------------------------------------------------------------------------+--------
The Matrix | A computer hacker learns about the true nature of his reality. | 0.1197
Inception | A thief who steals information by entering people's dreams. | 0.0646
Blade Runner 2049 | Young Blade Runner K's discovery of a long-buried secret leads him to track down | 0.022
Mad Max: Fury Road | In a post-apocalyptic wasteland, a woman rebels against a tyrannical ruler in se | 0.0206
Gladiator | A former Roman General sets out to exact vengeance against the corrupt emperor w | 0.0189
Avengers: Endgame | After the devastating events of Avengers: Infinity War, the universe is in ruins | 0.0175
Fight Club | An insomniac office worker looking for a way to change his life crosses paths wi | 0.0162
The Dark Knight | When the menace known as the Joker wreaks havoc and chaos on the people of Gotha | 0.0095
The Lord of the Rings: The Return of the King | Gandalf and Aragorn lead the World of Men against Sauron's army to draw his gaze | 0.0056
(9 rows)
נסו להשתמש בתנאים שונים כדי לראות איך הדירוג משפיע על סדר הפלט.
מידע נוסף על האפשרויות ועל דירוג מחדש זמין במאמרי העזרה.
11. ניקוי הסביבה
בסיום שיעור ה-Lab, משמידים את המופעים ואת האשכול של AlloyDB.
מחיקת אשכול AlloyDB וכל המופעים
אם השתמשתם בגרסת הניסיון של AlloyDB. אל תמחקו את אשכול הניסיון אם אתם מתכננים לבדוק מעבדות ומשאבים אחרים באמצעות אשכול הניסיון. לא תוכלו ליצור אשכול ניסיון נוסף באותו פרויקט.
האפשרות force משמידה את האשכול וגם מוחקת את כל המופעים ששייכים לאשכול.
ב-Cloud Shell, מגדירים את משתני הפרויקט והסביבה אם התנתקתם וכל ההגדרות הקודמות אבדו:
gcloud config set project <your project id>
export REGION=us-central1
export ADBCLUSTER=alloydb-aip-01
export PROJECT_ID=$(gcloud config get-value project)
מחיקת האשכול:
gcloud alloydb clusters delete $ADBCLUSTER --region=$REGION --force
הפלט הצפוי במסוף:
student@cloudshell:~ (test-project-001-402417)$ gcloud alloydb clusters delete $ADBCLUSTER --region=$REGION --force All of the cluster data will be lost when the cluster is deleted. Do you want to continue (Y/n)? Y Operation ID: operation-1697820178429-6082890a0b570-4a72f7e4-4c5df36f Deleting cluster...done.
מחיקת גיבויים של AlloyDB
מחיקת כל הגיבויים של AlloyDB לאשכול:
for i in $(gcloud alloydb backups list --filter="CLUSTER_NAME: projects/$PROJECT_ID/locations/$REGION/clusters/$ADBCLUSTER" --format="value(name)" --sort-by=~createTime) ; do gcloud alloydb backups delete $(basename $i) --region $REGION --quiet; done
הפלט הצפוי במסוף:
student@cloudshell:~ (test-project-001-402417)$ for i in $(gcloud alloydb backups list --filter="CLUSTER_NAME: projects/$PROJECT_ID/locations/$REGION/clusters/$ADBCLUSTER" --format="value(name)" --sort-by=~createTime) ; do gcloud alloydb backups delete $(basename $i) --region $REGION --quiet; done Operation ID: operation-1697826266108-60829fb7b5258-7f99dc0b-99f3c35f Deleting backup...done.
12. מזל טוב
כל הכבוד, סיימתם את ה-Codelab.
תוכנית הלימודים של Google Cloud
שיעור ה-Lab הזה הוא חלק מתוכנית הלימודים בנושא AI מוכן לייצור באמצעות Google Cloud.
- כדי לגשר על הפער בין אב-טיפוס לבין מוצר מוכן, מומלץ לעיין בתוכנית הלימודים המלאה.
- שתפו את ההתקדמות שלכם באמצעות ההאשטאג
#ProductionReadyAI.
מה נכלל
- איך פורסים אשכול AlloyDB ומופע ראשי
- איך מפעילים אופרטורים של AlloyDB AI
- איך משתמשים באופרטורים שונים של AlloyDB AI
- איך משתמשים בסידור מחדש באופרטורים של AlloyDB AI כדי לשפר את תוצאות הפלט
13. סקר
פלט: