عوامل تشغيل الذكاء الاصطناعي في AlloyDB وإعادة الترتيب

1. مقدمة

تقدّم لك تجربة البرمجة هذه دليلاً حول نشر AlloyDB مع مشغّلي الذكاء الاصطناعي واستخدامهم في مهام مثل البحث الدلالي وعمليات الربط وترتيب النتائج.

المتطلبات الأساسية

  • فهم أساسي لـ Google Cloud وGoogle Cloud Console
  • مهارات أساسية في واجهة سطر الأوامر وCloud Shell

ما ستتعلمه

المتطلبات

  • حساب Google Cloud ومشروع Google Cloud
  • متصفّح ويب، مثل Chrome، متوافق مع "وحدة تحكّم Google Cloud" وCloud Shell

2. الإعداد والمتطلبات

إعداد المشروع

  1. سجِّل الدخول إلى Google Cloud Console. إذا لم يكن لديك حساب على Gmail أو Google Workspace، عليك إنشاء حساب.

استخدام حساب شخصي بدلاً من حساب عمل أو حساب تديره مؤسسة تعليمية

  1. أنشئ مشروعًا جديدًا أو أعِد استخدام مشروع حالي. لإنشاء مشروع جديد في Google Cloud Console، انقر على الزر "اختيار مشروع" في العنوان، ما سيؤدي إلى فتح نافذة منبثقة.

295004821bab6a87.png

في نافذة "اختيار مشروع"، انقر على الزر "مشروع جديد" الذي سيفتح مربع حوار للمشروع الجديد.

37d264871000675d.png

في مربّع الحوار، أدخِل اسم المشروع المفضّل لديك واختَر الموقع الجغرافي.

96d86d3d5655cdbe.png

  • اسم المشروع هو الاسم المعروض للمشاركين في هذا المشروع. لا تستخدم واجهات برمجة تطبيقات Google اسم المشروع، ويمكن تغييره في أي وقت.
  • معرّف المشروع هو معرّف فريد في جميع مشاريع Google Cloud ولا يمكن تغييره (لا يمكن تغييره بعد ضبطه). تنشئ وحدة تحكّم Google Cloud تلقائيًا معرّفًا فريدًا، ولكن يمكنك تخصيصه. إذا لم يعجبك المعرّف الذي تم إنشاؤه، يمكنك إنشاء معرّف عشوائي آخر أو تقديم معرّفك الخاص للتحقّق من توفّره. في معظم دروس البرمجة، عليك الرجوع إلى رقم تعريف مشروعك، والذي يتم تحديده عادةً باستخدام العنصر النائب PROJECT_ID.
  • للعلم، هناك قيمة ثالثة، وهي رقم المشروع، تستخدمها بعض واجهات برمجة التطبيقات. يمكنك الاطّلاع على مزيد من المعلومات حول هذه القيم الثلاث في المستندات.

تفعيل الفوترة

لتفعيل الفوترة، لديك خياران. يمكنك استخدام حساب الفوترة الشخصي أو تحصيل قيمة الرصيد باتّباع الخطوات التالية.

تحصيل قيمة رصيد Google Cloud بقيمة 5 دولار أمريكي (اختياري)

لإجراء ورشة العمل هذه، تحتاج إلى حساب فوترة يتضمّن بعض الرصيد. إذا كنت تخطّط لاستخدام الفوترة الخاصة بك، يمكنك تخطّي هذه الخطوة.

  1. انقر على هذا الرابط وسجِّل الدخول باستخدام حساب Google شخصي.
  2. سيظهر لك ما يلي:

f54628965f465486.png

  1. انقر على الزر انقر هنا للوصول إلى أرصدتك. ستنتقل إلى صفحة لإعداد ملف الفوترة. إذا ظهرت لك شاشة الاشتراك في تجربة مجانية، انقر على "إلغاء" وواصِل ربط الفوترة.

20e88842cf2a732e.png

  1. انقر على "تأكيد". لقد تم ربط حسابك الآن بحساب فوترة تجريبي في Google Cloud Platform.

cdc87f1c57777951.png

إعداد حساب فوترة شخصي

إذا أعددت الفوترة باستخدام أرصدة Google Cloud، يمكنك تخطّي هذه الخطوة.

لإعداد حساب فوترة شخصي، انتقِل إلى هنا لتفعيل الفوترة في Cloud Console.

ملاحظات:

  • يجب أن تبلغ تكلفة إكمال هذا المختبر أقل من 3 دولارات أمريكية من موارد السحابة الإلكترونية.
  • يمكنك اتّباع الخطوات في نهاية هذا المختبر لحذف الموارد وتجنُّب المزيد من الرسوم.
  • يكون المستخدمون الجدد مؤهّلين للاستفادة من الفترة التجريبية المجانية بقيمة 300 دولار أمريكي.

بدء Cloud Shell

على الرغم من إمكانية تشغيل Google Cloud عن بُعد من الكمبيوتر المحمول، ستستخدم في هذا الدرس التطبيقي حول الترميز Google Cloud Shell، وهي بيئة سطر أوامر تعمل في السحابة الإلكترونية.

من Google Cloud Console، انقر على رمز Cloud Shell في شريط الأدوات أعلى يسار الصفحة:

تفعيل Cloud Shell

يمكنك بدلاً من ذلك الضغط على G ثم S. سيؤدي هذا التسلسل إلى تفعيل Cloud Shell إذا كنت تستخدم Google Cloud Console أو هذا الرابط.

لن يستغرق توفير البيئة والاتصال بها سوى بضع لحظات. عند الانتهاء، من المفترض أن يظهر لك ما يلي:

لقطة شاشة لواجهة سطر الأوامر في Google Cloud Shell توضّح أنّه تم ربط البيئة

يتم تحميل هذه الآلة الافتراضية مزوّدة بكل أدوات التطوير التي ستحتاج إليها. توفّر هذه الخدمة دليلًا منزليًا ثابتًا بسعة 5 غيغابايت، وتعمل على Google Cloud، ما يؤدي إلى تحسين أداء الشبكة والمصادقة بشكل كبير. يمكن إكمال جميع المهام في هذا الدرس العملي ضمن المتصفّح. لست بحاجة إلى تثبيت أي تطبيق.

3- قبل البدء

تفعيل واجهة برمجة التطبيقات

لاستخدام AlloyDB وCompute Engine وخدمات الشبكات وVertex AI، عليك تفعيل واجهات برمجة التطبيقات الخاصة بها في مشروعك على 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.

لمحة عن واجهات برمجة التطبيقات

  • تتيح لك AlloyDB API (alloydb.googleapis.com) إنشاء مجموعات AlloyDB for PostgreSQL وإدارتها وتوسيع نطاقها. توفّر هذه الخدمة قاعدة بيانات مُدارة بالكامل ومتوافقة مع PostgreSQL، وهي مصمَّمة لتلبية متطلبات مهام العمل التحليلية والمعاملات على مستوى المؤسسة.
  • تتيح لك Compute Engine API (compute.googleapis.com) إنشاء الأجهزة الافتراضية والأقراص الثابتة وإعدادات الشبكة وإدارتها. توفّر هذه المنطقة الأساس اللازم لنموذج "البنية التحتية كخدمة" (IaaS) من أجل تشغيل أحجام العمل واستضافة البنية التحتية الأساسية للعديد من الخدمات المُدارة.
  • تتيح لك Cloud Resource Manager API (cloudresourcemanager.googleapis.com) إدارة البيانات الوصفية وإعدادات مشروعك على Google Cloud آليًا. تتيح لك هذه الخدمة تنظيم الموارد والتعامل مع سياسات "إدارة الهوية والوصول" (IAM) والتحقّق من صحة الأذونات في جميع مستويات بنية المشروع.
  • تتيح لك Service Networking API (servicenetworking.googleapis.com) إمكانية برمجة عملية إعداد الاتصال الخاص بين شبكة السحابة الافتراضية الخاصة (VPC) وخدمات Google المُدارة. وهي مطلوبة تحديدًا لإتاحة الوصول إلى عناوين IP الخاصة لخدمات مثل AlloyDB، ما يتيح لها التواصل بأمان مع مواردك الأخرى.
  • تتيح Vertex AI API (aiplatform.googleapis.com) لتطبيقاتك إنشاء نماذج تعلُّم الآلة ونشرها وتوسيع نطاقها. توفّر هذه المنصة واجهة موحّدة لجميع خدمات الذكاء الاصطناعي من Google Cloud، بما في ذلك إمكانية الوصول إلى نماذج الذكاء الاصطناعي التوليدي (مثل Gemini) وتدريب النماذج المخصّصة.

4. نشر AlloyDB

أنشئ مجموعة AlloyDB ومثيلًا أساسيًا. يمكنك إما نشرها باستخدام نص برمجي مُعدّ مسبقًا سينشر جميع الموارد اللازمة، أو يمكنك تنفيذ ذلك خطوة بخطوة بنفسك.

نشر AlloyDB باستخدام نص برمجي آلي

يستخدم هذا الأسلوب نصًا برمجيًا مبرمَجًا لنشر مجموعة AlloyDB وتوفير المعلومات اللازمة لبدء العمل مع الموارد التي تم نشرها.

في Cloud Shell، أوقِف أمر التنفيذ لنسخ النص البرمجي الخاص بالنشر.

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

ويمكنك أيضًا الاطّلاع عليه في وحدة التحكّم على الويب.

4271eb55bcc9ec84.png

نشر 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 باستخدام علامة "+" في أعلى الصفحة.

abc505ac4d41f24e.png

في علامة تبويب 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

انتقِل إلى صفحة المجموعات في AlloyDB for Postgres.

افتح واجهة وحدة تحكّم الويب لمجموعة AlloyDB من خلال النقر على الآلة الافتراضية الأساسية.

1d7298e7096e7313.png

بعد ذلك، انقر على AlloyDB Studio في يمين الصفحة:

a33131c72ad29478.png

اختَر قاعدة بيانات postgres ومستخدم postgres وأدخِل كلمة المرور التي دوّنتها عند إنشاء المجموعة. بعد ذلك، انقر على الزر "المصادقة".

إذا لم تنجح كلمة المرور أو نسيت تدوينها، يمكنك تغييرها. راجِع المستندات لمعرفة كيفية إجراء ذلك.

2fcb84f70448118c.png

سيؤدي ذلك إلى فتح واجهة AlloyDB Studio. لتنفيذ الأوامر في قاعدة البيانات، انقر على علامة التبويب "استعلام بدون عنوان" على يسار الصفحة.

a127047c343731ff.png

يتم فتح واجهة يمكنك من خلالها تنفيذ أوامر SQL

9d312d5053c1296c.png

إنشاء قاعدة بيانات

إنشاء قاعدة بيانات باستخدام التشغيل السريع

في "محرّر AlloyDB Studio"، نفِّذ الأمر التالي.

إنشاء قاعدة بيانات:

CREATE DATABASE quickstart_db

الناتج المتوقّع:

Statement executed successfully

الاتصال بقاعدة بيانات quickstart_db

أعِد الاتصال بالاستوديو باستخدام الزرّ لتبديل المستخدم أو قاعدة البيانات.

5ac657387f7b6ec3.png

اختَر قاعدة البيانات الجديدة quickstart_db من القائمة المنسدلة واستخدِم اسم المستخدم وكلمة المرور نفسها كما كان من قبل.

309e09003db414c3.png

سيتم فتح اتصال جديد يمكنك من خلاله العمل مع عناصر من قاعدة بيانات quickstart_db.

التحقّق من صحة إضافة google_ml

تحقَّق من إصدار إضافة 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

علينا أيضًا تفعيل ميزات محرّك طلبات البحث المستند إلى الذكاء الاصطناعي في قاعدة البيانات. يمكن إجراء ذلك إما عن طريق تعديل علامة المثيل لجميع قواعد البيانات على المثيل أو عن طريق تفعيلها لقاعدة البيانات فقط. نفِّذ الأمر التالي في AlloyDB Studio لتفعيله لقاعدة بيانات quickstart_db.

ALTER DATABASE quickstart_db SET google_ml_integration.enable_ai_query_engine = 'on';

6. عيّنات البيانات

الآن، علينا إنشاء عناصر في قاعدة البيانات وتحميل البيانات. سنستخدم مجموعة بيانات أفلام وهمية تتضمّن بضعة صفوف.

انسخ العبارات التالية إلى "محرّر AlloyDB Studio" وانقر على الزر "تنفيذ".

-- 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 Console، يمكنك استخدامها بدلاً من الطريقة المعروضة.

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.

يمكننا الآن محاولة استخدام الفلترة الدلالية المستندة إلى الذكاء الاصطناعي مع الدالة google_ml.if. سيستخدم الذكاء الاصطناعي في الخلفية لإجراء فلترة دلالية استنادًا إلى طلبنا باللغة الطبيعية.

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

ماذا لو أردنا ربط جدولَين باستخدام الفلترة الدلالية المستندة إلى الذكاء الاصطناعي؟ على سبيل المثال، يمكننا محاولة مطابقة مراجعات المستخدمين مع الأفلام استنادًا إلى مراجعات المستخدمين إذا تم ذكر الفيلم في المراجعة.

تشغيلها في علامة تبويب جديدة في 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. تم تفعيل واجهة برمجة التطبيقات والدور في الخطوات الأولى من مختبرنا. تعثر الدالة 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. تنظيف البيئة

تدمير مثيلات 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. تهانينا

تهانينا على إكمال تجربة البرمجة.

المسار التعليمي في Google Cloud

هذا المختبر هو جزء من مسار "الذكاء الاصطناعي الجاهز للإنتاج" التعليمي على Google Cloud.

المواضيع التي تناولناها

13. استطلاع

إخراج:

كيف ستستخدم هذا البرنامج التعليمي؟

قراءة المحتوى فقط قراءة المحتوى وإكمال التمارين