โอเปอเรเตอร์ AI และการจัดอันดับใหม่ของ AlloyDB

โอเปอเรเตอร์ AI และการจัดอันดับใหม่ของ AlloyDB

เกี่ยวกับ Codelab นี้

subjectอัปเดตล่าสุดเมื่อ พ.ค. 23, 2025
account_circleเขียนโดย Gleb Otochkin

1 บทนำ

โค้ดแล็บนี้ให้คําแนะนําในการติดตั้งใช้งาน AlloyDB กับโอเปอเรเตอร์ AI และการใช้โอเปอเรเตอร์ดังกล่าวสําหรับงานต่างๆ เช่น การค้นหาเชิงความหมาย การรวม และการจัดอันดับผลลัพธ์

  • ความเข้าใจพื้นฐานเกี่ยวกับคอนโซล Google Cloud
  • ทักษะพื้นฐานในอินเทอร์เฟซบรรทัดคำสั่งและ Cloud Shell
  • วิธีติดตั้งใช้งาน AlloyDB for Postgres
  • วิธีเปิดใช้โอเปอเรเตอร์ AI ของ AlloyDB
  • วิธีใช้โอเปอเรเตอร์ AI ของ AlloyDB แบบต่างๆ
  • วิธีใช้โอเปอเรเตอร์ AI ของ AlloyDB ในเวิร์กโฟลว์ RAG

สิ่งที่ต้องมี

  • บัญชี Google Cloud และโปรเจ็กต์ Google Cloud
  • เว็บเบราว์เซอร์ เช่น Chrome ที่รองรับ Google Cloud Console และ Cloud Shell

2 การตั้งค่าและข้อกําหนด

การตั้งค่าสภาพแวดล้อมด้วยตนเอง

  1. ลงชื่อเข้าใช้ Google Cloud Console แล้วสร้างโปรเจ็กต์ใหม่หรือใช้โปรเจ็กต์ที่มีอยู่ซ้ำ หากยังไม่มีบัญชี Gmail หรือ Google Workspace คุณต้องสร้างบัญชี

fbef9caa1602edd0.png

a99b7ace416376c4.png

5e3ff691252acf41.png

  • ชื่อโปรเจ็กต์คือชื่อที่แสดงสำหรับผู้เข้าร่วมโปรเจ็กต์นี้ ซึ่งเป็นสตริงอักขระที่ Google APIs ไม่ได้ใช้ คุณจะอัปเดตได้ทุกเมื่อ
  • รหัสโปรเจ็กต์จะต้องไม่ซ้ำกันสำหรับโปรเจ็กต์ Google Cloud ทั้งหมดและจะเปลี่ยนแปลงไม่ได้ (เปลี่ยนแปลงไม่ได้หลังจากตั้งค่าแล้ว) คอนโซล Cloud จะสร้างสตริงที่ไม่ซ้ำกันโดยอัตโนมัติ ซึ่งปกติแล้วคุณไม่จำเป็นต้องสนใจว่าสตริงนั้นจะเป็นอะไร ในโค้ดแล็บส่วนใหญ่ คุณจะต้องอ้างอิงรหัสโปรเจ็กต์ (ปกติจะระบุเป็น PROJECT_ID) หากไม่ชอบรหัสที่สร้างขึ้น คุณอาจสร้างรหัสอื่นแบบสุ่มได้ หรือจะลองใช้อุปกรณ์ของคุณเองเพื่อดูว่าพร้อมใช้งานหรือไม่ก็ได้ คุณจะเปลี่ยนแปลงชื่อหลังจากขั้นตอนนี้ไม่ได้ และชื่อดังกล่าวจะคงอยู่ตลอดระยะเวลาของโปรเจ็กต์
  • โปรดทราบว่ามีค่าที่ 3 ซึ่งเป็นหมายเลขโปรเจ็กต์ที่ API บางรายการใช้ ดูข้อมูลเพิ่มเติมเกี่ยวกับค่าทั้ง 3 รายการนี้ได้ในเอกสารประกอบ
  1. ถัดไป คุณจะต้องเปิดใช้การเรียกเก็บเงินใน Cloud Console เพื่อใช้ทรัพยากร/API ของ Cloud การทำตามโค้ดแล็บนี้จะไม่เสียค่าใช้จ่ายมากนัก หากต้องการปิดทรัพยากรเพื่อหลีกเลี่ยงการเรียกเก็บเงินหลังจากบทแนะนำนี้ คุณสามารถลบทรัพยากรที่สร้างไว้หรือลบโปรเจ็กต์ได้ ผู้ใช้ Google Cloud รายใหม่มีสิทธิ์เข้าร่วมโปรแกรมช่วงทดลองใช้ฟรีมูลค่า$300 USD

เริ่ม Cloud Shell

แม้ว่า Google Cloud จะทำงานจากระยะไกลจากแล็ปท็อปได้ แต่ในโค้ดแล็บนี้ คุณจะใช้ Google Cloud Shell ซึ่งเป็นสภาพแวดล้อมบรรทัดคำสั่งที่ทำงานในระบบคลาวด์

จากคอนโซล Google Cloud ให้คลิกไอคอน Cloud Shell ในแถบเครื่องมือด้านขวาบน

55efc1aaa7a4d3ad.png

การจัดสรรและเชื่อมต่อกับสภาพแวดล้อมจะใช้เวลาเพียงไม่กี่นาที เมื่อดำเนินการเสร็จแล้ว คุณควรเห็นข้อมูลดังต่อไปนี้

7ffe5cbb04455448.png

เครื่องเสมือนนี้โหลดเครื่องมือการพัฒนาทั้งหมดที่คุณต้องการ ซึ่งจะมีไดเรกทอรีหลักขนาด 5 GB ถาวรและทำงานบน 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 alloydb.googleapis.com \
                       compute
.googleapis.com \
                       cloudresourcemanager
.googleapis.com \
                       servicenetworking
.googleapis.com \
                       aiplatform
.googleapis.com \
                       discoveryengine
.googleapis.com \
                       secretmanager
.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
Operation "operations/acat.p2-4470404856-1f44ebd8-894e-4356-bea7-b84165a57442" finished successfully.

4 ติดตั้งใช้งาน AlloyDB

สร้างคลัสเตอร์ AlloyDB และอินสแตนซ์หลัก ขั้นตอนต่อไปนี้อธิบายวิธีสร้างคลัสเตอร์และอินสแตนซ์ 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

ผลลัพธ์ที่คาดหวังในคอนโซล

student@cloudshell:~ (test-project-402417)$ echo $PGPASSWORD
bbefbfde7601985b0dee5723

สร้างคลัสเตอร์ช่วงทดลองใช้ฟรี

หากไม่เคยใช้ 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 อื่นโดยใช้เครื่องหมาย "+" ที่ด้านบน

4ca978f5142bb6ce.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"

ผลลัพธ์ที่คาดหวังในคอนโซล

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 แทนได้ หากต้องการเรียกใช้คําสั่ง คุณต้องเปิดอินเทอร์เฟซเว็บคอนโซลสําหรับคลัสเตอร์ AlloyDB โดยคลิกอินสแตนซ์หลัก

ef4bfbcf0ed2ef3a.png

จากนั้นคลิก AlloyDB Studio ทางด้านซ้าย

5c155cbcd7d43a1.png

เลือกฐานข้อมูล postgres, ผู้ใช้ postgres แล้วป้อนรหัสผ่านที่บันทึกไว้เมื่อเราสร้างคลัสเตอร์ จากนั้นคลิกปุ่ม "ตรวจสอบสิทธิ์"

432613065cac864f.png

ซึ่งจะเปิดอินเทอร์เฟซ AlloyDB Studio หากต้องการเรียกใช้คําสั่งในฐานข้อมูล ให้คลิกแท็บ "Editor 1" ทางด้านขวา

b36c28f8165119ca.png

ซึ่งจะเปิดอินเทอร์เฟซที่คุณสามารถเรียกใช้คําสั่ง SQL

cf43aa20f292797e.png

สร้างฐานข้อมูล

เริ่มต้นใช้งานฐานข้อมูลอย่างรวดเร็ว

ในเครื่องมือแก้ไข AlloyDB Studio ให้เรียกใช้คําสั่งต่อไปนี้

สร้างฐานข้อมูล

CREATE DATABASE quickstart_db

ผลลัพธ์ที่คาดหวัง

Statement executed successfully

เชื่อมต่อกับ quickstart_db

เชื่อมต่อกับสตูดิโออีกครั้งโดยใช้ปุ่มเพื่อเปลี่ยนผู้ใช้/ฐานข้อมูล

e826ad973eb23a74.png

เลือกฐานข้อมูล quickstart_db ใหม่จากรายการแบบเลื่อนลง และใช้ผู้ใช้และรหัสผ่านเดิม

1ca70c59b5aea8c1.png

ซึ่งจะเปิดการเชื่อมต่อใหม่ที่คุณสามารถใช้กับออบเจ็กต์จากฐานข้อมูล quickstart_db

ยืนยันส่วนขยาย google_ml

ตรวจสอบเวอร์ชันของส่วนขยาย google_ml ว่าเท่ากับ 1.4.4 ขึ้นไปเพื่อให้ใช้เครื่องมือค้นหา AI ได้

ใน AlloyDB Studio ขณะที่เชื่อมต่อกับ quickstart_db ให้ดำเนินการดังนี้

SELECT extversion FROM pg_extension WHERE extname = 'google_ml_integration';

ผลลัพธ์ที่คาดหวัง

1.4.4

หากเวอร์ชันต่ำกว่าที่กำหนด ให้อัปเดตส่วนขยาย

ใน 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.4.4

6 ข้อมูลตัวอย่าง

ตอนนี้เราต้องสร้างออบเจ็กต์ในฐานข้อมูลและโหลดข้อมูล เราจะใช้ชุดข้อมูลภาพยนตร์สมมติที่มี 2-3 แถว

คัดลอกคำสั่งต่อไปนี้ไปยังเครื่องมือแก้ไข 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%';

ไม่พบผลลัพธ์ใดๆ แต่เรามั่นใจว่ามีภาพยนตร์อย่างน้อย 1 เรื่องซึ่งจัดอยู่ในหมวดหมู่นั้น เราลองใช้วิธีการค้นหาข้อความแบบเต็มได้

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

เรากำลังแสดงภาพยนตร์ "Interstellar" ตามความหมายเชิงอรรถศาสตร์ของคำขอ แม้ว่าจะไม่มีคำว่า "อวกาศ" ทั้งในชื่อหรือคำอธิบายก็ตาม และคุณก็สังเกตเห็นว่าเราไม่ได้สร้างอะไรล่วงหน้าและอาศัยฟังก์ชันในตัวแบบอัตโนมัติเท่านั้น

8 ใช้ JOIN กับโอเปอเรเตอร์ IF

จะเกิดอะไรขึ้นหากเราต้องการเชื่อมต่อ 2 ตารางโดยใช้การกรองเชิงความหมายที่ทำงานด้วยระบบ 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';

และเราได้รับรีวิว 2 รายการที่ตรงกับคำขอของเราตามชื่อภาพยนตร์ที่กล่าวถึงในชื่อ และเรายังลดความซับซ้อนของคำขอได้อีกด้วย โดยทำดังนี้

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 สำหรับรีวิวยอดนิยม

10 ปรับปรุงการค้นหาเชิงความหมายโดยใช้การจัดอันดับ

เรารวมการค้นหาเชิงความหมายเข้ากับการจัดอันดับเพื่อให้ได้ผลลัพธ์ที่แม่นยำยิ่งขึ้นได้

ลงทะเบียนรูปแบบการจัดอันดับใหม่

เปิดแท็บ Cloud Shell อื่นโดยใช้เครื่องหมาย "+" ที่ด้านบน

4ca978f5142bb6ce.png

ในแท็บ Cloud Shell ใหม่ ให้ดำเนินการต่อไปนี้

export PROJECT_ID=$(gcloud config get-value project)
gcloud iam service-accounts create aip-reranking
gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:aip-reranking@$PROJECT_ID.iam.gserviceaccount.com" \
  --role="roles/discoveryengine.viewer"
gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:aip-reranking@$PROJECT_ID.iam.gserviceaccount.com" \
  --role="roles/aiplatform.user"
gcloud iam service-accounts add-iam-policy-binding aip-reranking@$PROJECT_ID.iam.gserviceaccount.com \
    --member="user:$(gcloud auth list --filter=status:ACTIVE --format="value(account)")" --role="roles/iam.serviceAccountTokenCreator"
gcloud iam service-accounts add-iam-policy-binding aip-reranking@$PROJECT_ID.iam.gserviceaccount.com \
    --member="user:$(gcloud auth list --filter=status:ACTIVE --format="value(account)")" --role="roles/iam.serviceAccountUser"

สร้างโทเค็นการเข้าถึงและเพิ่มเป็นข้อมูลลับที่มีชื่อ "rerank-secret" โดยทำดังนี้

echo -n $(gcloud auth print-access-token \
  --impersonate-service-account="aip-reranking@$PROJECT_ID.iam.gserviceaccount.com" \
  --lifetime=3600) | gcloud secrets create rerank-secret \
    --replication-policy="automatic" \
    --data-file=-
gcloud secrets add-iam-policy-binding 'rerank-secret' \
      --member="serviceAccount:service-$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")@gcp-sa-alloydb.iam.gserviceaccount.com" \
      --role="roles/secretmanager.secretAccessor"

ในตัวอย่าง ข้อมูลลับจะใช้งานได้ 1 ชั่วโมง หลังจากนั้นควรอัปเดตโดยการสร้างเวอร์ชันใหม่ เช่น

echo -n $(gcloud auth print-access-token \
--impersonate-service-account="aip-reranking@$PROJECT_ID.iam.gserviceaccount.com" \
 
--lifetime=3600) | gcloud secrets versions add rerank-secret \
   
--data-file=-

ตอนนี้เราต้องเปลี่ยนไปใช้ AlloyDB Studio และสร้างข้อมูลลับเพื่อเข้าถึงโมเดลการจัดอันดับใหม่

ในคอนโซล AlloyDB Studio ให้ดำเนินการต่อไปนี้หลังจากเปลี่ยน $PROJECT_ID ตามโปรเจ็กต์

CALL
  google_ml
.create_sm_secret(
    secret_id
=> 'rerank-secret',
    secret_path
=> 'projects/PROJECT_ID/secrets/rerank-secret/versions/latest');

และลงทะเบียนโมเดลในเซสชัน Studio เดียวกันหลังจากเปลี่ยน PROJECT_ID ตามโปรเจ็กต์ของคุณ

CALL
google_ml.create_model(
  model_id => 'semantic-ranker-512-002',
  model_type => 'reranking',
  model_provider => 'custom',
  model_request_url =>
    'https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/rankingConfigs/default_ranking_config:rank',
  model_qualified_name => 'semantic-ranker-512@002',
  model_auth_type => 'secret_manager',
  model_auth_id => 'rerank-secret',
  model_in_transform_fn => 'google_ml.vertexai_reranking_input_transform',
  model_out_transform_fn => 'google_ml.vertexai_reranking_output_transform');

ใช้รูปแบบการจัดอันดับใหม่

ตอนนี้เราสามารถใช้รูปแบบการจัดอันดับใหม่ในข้อความค้นหาเพื่อปรับปรุงผลการค้นหาเชิงความหมายให้เฉพาะเจาะจงมากขึ้นและเลือกตัวเลือกที่ดีที่สุดได้แล้ว

มาค้นหาภาพยนตร์แอ็กชันและจัดอันดับโดยใช้เงื่อนไข "คอมพิวเตอร์และอนาคต"

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-512-002',
        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.0145
 
Mad Max: Fury Road                            | In a post-apocalyptic wasteland, a woman rebels against a tyrannical ruler in se |  0.002
 
Avengers: Endgame                             | After the devastating events of Avengers: Infinity War, the universe is in ruins | 0.0018
 
Blade Runner 2049                             | Young Blade Runner K's discovery of a long-buried secret leads him to track down | 0.0004
 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 |  1e-05
 
The Dark Knight                               | When the menace known as the Joker wreaks havoc and chaos on the people of Gotha |  1e-05
 
Inception                                     | A thief who steals information by entering people's dreams.                      |  1e-05
 Gladiator                                     | A former Roman General sets out to exact vengeance against the corrupt emperor w |  1e-05
(8 rows)

ลองใช้กับเงื่อนไขต่างๆ และดูว่าการจัดอันดับส่งผลต่อลําดับเอาต์พุตอย่างไร

11 ล้างสภาพแวดล้อม

ทำลายอินสแตนซ์และคลัสเตอร์ AlloyDB เมื่อใช้ห้องทดลองเสร็จแล้ว

ลบคลัสเตอร์ AlloyDB และอินสแตนซ์ทั้งหมด

ระบบจะทำลายคลัสเตอร์ด้วยตัวเลือก "บังคับ" ซึ่งจะลบอินสแตนซ์ทั้งหมดของคลัสเตอร์ด้วย

ในเชลล์ระบบคลาวด์ ให้กําหนดตัวแปรโปรเจ็กต์และสภาพแวดล้อมหากคุณถูกตัดการเชื่อมต่อและการตั้งค่าก่อนหน้านี้ทั้งหมดหายไป

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 จนเสร็จสมบูรณ์

สิ่งที่เราได้พูดถึง

  • วิธีติดตั้งใช้งาน AlloyDB for Postgres
  • วิธีเปิดใช้โอเปอเรเตอร์ AI ของ AlloyDB
  • วิธีใช้โอเปอเรเตอร์ AI ของ AlloyDB แบบต่างๆ
  • วิธีใช้โอเปอเรเตอร์ AI ของ AlloyDB ในเวิร์กโฟลว์ RAG

13 แบบสำรวจ

เอาต์พุต:

คุณจะใช้บทแนะนำนี้อย่างไร