本教學課程說明如何使用 Google Cloud 控制台,在 AlloyDB for PostgreSQL 中設定及執行向量搜尋。這些範例僅供示範,目的是展示向量搜尋功能。
如要瞭解如何使用含篩選條件的向量搜尋功能,縮小相似度搜尋範圍,請參閱「AlloyDB for PostgreSQL 中的含篩選條件向量搜尋」。
如要瞭解如何使用 Vertex AI 嵌入執行向量搜尋,請參閱「開始透過 AlloyDB AI 使用向量嵌入」。
目標
- 建立 AlloyDB 叢集和主要執行個體。
- 連線至資料庫並安裝必要擴充功能。
- 建立
product
和product inventory
資料表。 - 將資料插入
product
和product inventory
資料表,並執行基本向量搜尋。 - 在產品資料表上建立 ScaNN 索引。
- 執行簡單的向量搜尋。
- 使用篩選器和聯結執行複雜的向量搜尋。
費用
在本文件中,您會使用 Google Cloud的下列計費元件:
如要根據預測用量估算費用,請使用 Pricing Calculator。
完成本文所述工作後,您可以刪除已建立的資源,避免繼續計費。詳情請參閱清除所用資源一節。
事前準備
啟用計費功能和必要的 API
前往 Google Cloud 控制台的「Clusters」(叢集) 頁面。
啟用建立及連線至 PostgreSQL 適用的 AlloyDB 時所需的 Cloud API。
- 在「確認專案」步驟中,按一下「下一步」,確認要變更的專案名稱。
在「啟用 API」步驟中,按一下「啟用」,啟用下列項目:
- AlloyDB API
- Compute Engine API
- Service Networking API
- Vertex AI API
建立 AlloyDB 叢集和主要執行個體
前往 Google Cloud 控制台的「Clusters」(叢集) 頁面。
按一下 [Create cluster] (建立叢集)。
在「叢集 ID」中輸入
my-cluster
。輸入密碼。請記下這組密碼,因為本教學課程會用到。
選取區域,例如
us-central1 (Iowa)
。選取預設網路。
如果您有私人存取連線,請繼續下一個步驟。如果沒有,請按一下「設定連線」,然後按照下列步驟操作:
- 在「Allocate an IP range」(分配 IP 範圍) 中,按一下「Use an automatically allocated IP range」(使用系統自動分配的 IP 範圍)。
- 依序點選「繼續」和「建立連線」。
在「可用區可用性」中選取「單一可用區」。
選取
2 vCPU,16 GB
機型。在「連線能力」部分,選取「啟用公開 IP」。
按一下「Create cluster」(建立叢集)。AlloyDB 可能需要幾分鐘才能建立叢集,並顯示在主要叢集的「總覽」頁面上。
在「叢集中的執行個體」中,展開「連線」窗格。請記下「連線 URI」,因為本教學課程會用到。
連線 URI 的格式為
projects/<var>PROJECT_ID</var>/locations/<var>REGION_ID</var>/clusters/my-cluster/instances/my-cluster-primary
。
將 Vertex AI 使用者權限授予 AlloyDB 服務代理
如要讓 AlloyDB 使用 Vertex AI 文字嵌入模型,您必須為叢集和執行個體所在專案的 AlloyDB 服務代理新增 Vertex AI 使用者權限。
如要進一步瞭解如何新增權限,請參閱將 Vertex AI 使用者權限授予 AlloyDB 服務代理程式。
使用網路瀏覽器連線至資料庫
前往 Google Cloud 控制台的「Clusters」(叢集) 頁面。
在「資源名稱」欄中,按一下叢集名稱
my-cluster
。在導覽窗格中,按一下「AlloyDB Studio」。
在「Sign in to AlloyDB Studio」(登入 AlloyDB Studio) 頁面,按照下列步驟操作:
- 選取
postgres
資料庫。 - 選取
postgres
使用者。 - 輸入您在「建立叢集及其主要執行個體」中建立的密碼。
- 按一下「驗證」。「Explorer」窗格會顯示
postgres
資料庫中的物件清單。
- 選取
點選「+ New SQL editor tab」(+ 新的 SQL 編輯器分頁) 或「+ New tab」(+ 新分頁),開啟新分頁。
安裝必要擴充功能
執行下列查詢,安裝 vector
和 alloydb_scann
擴充功能:
CREATE EXTENSION IF NOT EXISTS vector;
CREATE EXTENSION IF NOT EXISTS alloydb_scann;
插入產品和產品目錄資料,並執行基本向量搜尋
執行下列陳述式,建立可執行下列作業的
product
資料表:- 儲存產品基本資訊。
- 包含
embedding
向量資料欄,可計算及儲存每項產品的產品說明嵌入向量。
CREATE TABLE product ( id INT PRIMARY KEY, name VARCHAR(255) NOT NULL, description TEXT, category VARCHAR(255), color VARCHAR(255), embedding vector(768) GENERATED ALWAYS AS (embedding('text-embedding-005', description)) STORED );
如有需要,您可以使用記錄檔探索工具查看記錄檔及排解錯誤。
執行下列查詢,建立
product_inventory
資料表,儲存可用商品目錄和相應價格的相關資訊。本教學課程會使用product_inventory
和product
資料表執行複雜的向量搜尋查詢。CREATE TABLE product_inventory ( id INT PRIMARY KEY, product_id INT REFERENCES product(id), inventory INT, price DECIMAL(10,2) );
執行下列查詢,將產品資料插入
product
資料表:INSERT INTO product (id, name, description,category, color) VALUES (1, 'Stuffed Elephant', 'Soft plush elephant with floppy ears.', 'Plush Toys', 'Gray'), (2, 'Remote Control Airplane', 'Easy-to-fly remote control airplane.', 'Vehicles', 'Red'), (3, 'Wooden Train Set', 'Classic wooden train set with tracks and trains.', 'Vehicles', 'Multicolor'), (4, 'Kids Tool Set', 'Toy tool set with realistic tools.', 'Pretend Play', 'Multicolor'), (5, 'Play Food Set', 'Set of realistic play food items.', 'Pretend Play', 'Multicolor'), (6, 'Magnetic Tiles', 'Set of colorful magnetic tiles for building.', 'Construction Toys', 'Multicolor'), (7, 'Kids Microscope', 'Microscope for kids with different magnification levels.', 'Educational Toys', 'White'), (8, 'Telescope for Kids', 'Telescope designed for kids to explore the night sky.', 'Educational Toys', 'Blue'), (9, 'Coding Robot', 'Robot that teaches kids basic coding concepts.', 'Educational Toys', 'White'), (10, 'Kids Camera', 'Durable camera for kids to take pictures and videos.', 'Electronics', 'Pink'), (11, 'Walkie Talkies', 'Set of walkie talkies for kids to communicate.', 'Electronics', 'Blue'), (12, 'Karaoke Machine', 'Karaoke machine with built-in microphone and speaker.', 'Electronics', 'Black'), (13, 'Kids Drum Set', 'Drum set designed for kids with adjustable height.', 'Musical Instruments', 'Blue'), (14, 'Kids Guitar', 'Acoustic guitar for kids with nylon strings.', 'Musical Instruments', 'Brown'), (15, 'Kids Keyboard', 'Electronic keyboard with different instrument sounds.', 'Musical Instruments', 'Black'), (16, 'Art Easel', 'Double-sided art easel with chalkboard and whiteboard.', 'Arts & Crafts', 'White'), (17, 'Finger Paints', 'Set of non-toxic finger paints for kids.', 'Arts & Crafts', 'Multicolor'), (18, 'Modeling Clay', 'Set of colorful modeling clay.', 'Arts & Crafts', 'Multicolor'), (19, 'Watercolor Paint Set', 'Watercolor paint set with brushes and palette.', 'Arts & Crafts', 'Multicolor'), (20, 'Beading Kit', 'Kit for making bracelets and necklaces with beads.', 'Arts & Crafts', 'Multicolor'), (21, '3D Puzzle', '3D puzzle of a famous landmark.', 'Puzzles', 'Multicolor'), (22, 'Race Car Track Set', 'Race car track set with cars and accessories.', 'Vehicles', 'Multicolor'), (23, 'RC Monster Truck', 'Remote control monster truck with oversized tires.', 'Vehicles', 'Green'), (24, 'Train Track Expansion Set', 'Expansion set for wooden train tracks.', 'Vehicles', 'Multicolor');
選用:執行下列查詢,確認資料已插入
product
資料表:SELECT * FROM product;
執行下列查詢,將庫存資料插入
product_inventory
資料表:INSERT INTO product_inventory (id, product_id, inventory, price) VALUES (1, 1, 9, 13.09), (2, 2, 40, 79.82), (3, 3, 34, 52.49), (4, 4, 9, 12.03), (5, 5, 36, 71.29), (6, 6, 10, 51.49), (7, 7, 7, 37.35), (8, 8, 6, 10.87), (9, 9, 7, 42.47), (10, 10, 3, 24.35), (11, 11, 4, 10.20), (12, 12, 47, 74.57), (13, 13, 5, 28.54), (14, 14, 11, 25.58), (15, 15, 21, 69.84), (16, 16, 6, 47.73), (17, 17, 26, 81.00), (18, 18, 11, 91.60), (19, 19, 8, 78.53), (20, 20, 43, 84.33), (21, 21, 46, 90.01), (22, 22, 6, 49.82), (23, 23, 37, 50.20), (24, 24, 27, 99.27);
執行下列向量搜尋查詢,嘗試找出與「
music
」一詞相似的產品。這表示即使產品說明中未明確提及「music
」一字,結果仍會顯示與查詢相關的產品:SELECT * FROM product ORDER BY embedding <=> embedding('text-embedding-005', 'music')::vector LIMIT 3;
查詢結果如下:
執行基本向量搜尋時,不必建立索引,系統會使用 K 近鄰搜尋 (KNN),提供有效率的召回率。大規模使用 KNN 可能會影響效能。為提升查詢效能,建議您使用 ScaNN 索引進行近似最近鄰 (ANN) 搜尋,這項索引可提供高召回率和低延遲。
如果沒有建立索引,AlloyDB 預設會使用精確的最鄰近搜尋 (KNN)。
如要進一步瞭解如何大規模使用 ScaNN,請參閱「開始透過 AlloyDB AI 使用向量嵌入」。
在產品資料表上建立 ScaNN 索引
執行下列查詢,在 product
資料表上建立 product_index
ScaNN 索引:
CREATE INDEX product_index ON product
USING scann (embedding cosine)
WITH (num_leaves=5);
num_leaves
參數表示樹狀結構索引用來建構索引的葉節點數量。如要進一步瞭解如何調整這個參數,請參閱「調整向量查詢效能」。
執行向量搜尋
執行下列向量搜尋查詢,嘗試找出與自然語言查詢 music
相似的產品。即使產品說明中未包含「music
」一詞,結果仍會顯示與查詢相關的產品:
SET LOCAL scann.num_leaves_to_search = 2;
SELECT * FROM product
ORDER BY embedding <=> embedding('text-embedding-005', 'music')::vector
LIMIT 3;
查詢結果如下:
scann.num_leaves_to_search
查詢參數可控制相似度搜尋期間搜尋的分葉節點數量。num_leaves
和 scann.num_leaves_to_search
參數值有助於在效能和喚回率之間取得平衡。
執行使用篩選器和聯結的向量搜尋
即使使用 ScaNN 索引,您也能有效率地執行經過篩選的向量搜尋查詢。執行下列複雜的向量搜尋查詢,即使有篩選條件,也會傳回符合查詢條件的相關結果:
SET LOCAL scann.num_leaves_to_search = 2;
SELECT * FROM product p
JOIN product_inventory pi ON p.id = pi.product_id
WHERE pi.price < 80.00
ORDER BY embedding <=> embedding('text-embedding-005', 'music')::vector
LIMIT 3;
加快篩選後的向量搜尋速度
搭配高選擇性述詞篩選 (例如在資料庫中使用 LIKE
),即可使用直欄引擎提升向量相似度搜尋 (尤其是 K 近鄰 (KNN) 搜尋) 的效能。在本節中,您會使用 vector
擴充功能和 AlloyDB google_columnar_engine
擴充功能。
直欄式引擎內建掃描大型資料集和套用篩選器 (例如 LIKE
述詞) 的效率,加上向量支援功能可預先篩選資料列,因此效能有所提升。這項功能可減少後續 KNN 向量距離計算所需的資料子集數量,並有助於最佳化涉及標準篩選和向量搜尋的複雜分析查詢。
如要比較啟用直欄引擎前後,以述詞篩選的 KNN 向量搜尋執行時間,請按照下列步驟操作:LIKE
啟用
vector
擴充功能,支援向量資料類型和作業。執行下列陳述式,建立含有 ID、文字說明和 512 維度向量嵌入資料欄的範例資料表 (項目)。CREATE EXTENSION IF NOT EXISTS vector; CREATE TABLE items ( id SERIAL PRIMARY KEY, description TEXT, embedding VECTOR(512) );
執行下列陳述式,將 100 萬個資料列插入範例
items
資料表,以填入資料。-- Simplified example of inserting matching (~0.1%) and non-matching data INSERT INTO items (description, embedding) SELECT CASE WHEN g % 1000 = 0 THEN 'product_' || md5(random()::text) || '_common' -- ~0.1% match ELSE 'generic_item_' || g || '_' || md5(random()::text) -- ~99.9% don't match END, random_vector(512) -- Assumes random_vector function exists FROM generate_series(1, 999999) g;
評估向量相似度搜尋的基準成效,但不使用資料欄引擎。
SELECT id, description, embedding <-> '[...]' AS distance FROM items WHERE description LIKE '%product_%_common%' ORDER BY embedding <-> '[...]' LIMIT 100;
在 Google Cloud CLI 中執行下列指令,啟用資料欄引擎和向量支援。如要使用 gcloud CLI,請安裝及初始化 gcloud CLI。
gcloud beta alloydb instances update INSTANCE_ID \ --cluster=CLUSTER_ID \ --region=REGION_ID \ --project=PROJECT_ID \ --database-flags=google_columnar_engine.enabled=on,google_columnar_engine.enable_vector_support=on
將
items
表格新增至直欄引擎:SELECT google_columnar_engine_add('items');
使用資料欄引擎評估向量相似度搜尋的效能。您會重新執行先前用於評估基準成效的查詢。
SELECT id, description, embedding <-> '[...]' AS distance FROM items WHERE description LIKE '%product_%_common%' ORDER BY embedding <-> '[...]' LIMIT 100;
如要檢查查詢是否使用直欄引擎執行,請執行下列指令:
explain (analyze) SELECT id, description, embedding <-> '[...]' AS distance FROM items WHERE description LIKE '%product_%_common%' ORDER BY embedding <-> '[...]' LIMIT 100;
清除所用資源
前往 Google Cloud 控制台的「Clusters」(叢集) 頁面。
在「資源名稱」資料欄中,按一下叢集名稱
my-cluster
。按一下 delete「刪除叢集」。
在「Delete cluster my-cluster」(刪除叢集 my-cluster) 中輸入
my-cluster
,確認要刪除叢集。點選「刪除」。
如果您在建立叢集時建立了私人連線,請前往 Google Cloud 控制台的「網路」頁面,然後按一下「刪除虛擬私有雲網路」。