Cloud SQL for PostgreSQL でベクトル エンベディングを使ってみる

1. はじめに

この Codelab では、ベクトル検索と Gemini Enterprise Agent Platform エンベディングを組み合わせて Cloud SQL for PostgreSQL AI 統合を使用する方法を学びます。

Cloud SQL と Gemini Enterprise Agent Platform の統合を示すアーキテクチャ図

前提条件

  • Google Cloud と Google Cloud コンソールの基本的な知識
  • コマンドライン インターフェースと Cloud Shell の基本的な使用経験

演習内容

  • Cloud SQL for PostgreSQL インスタンスをデプロイする
  • データベースを作成して Cloud SQL AI 統合を有効にする
  • データベースにデータを読み込む
  • Cloud SQL Studio を使用する
  • Cloud SQL で Gemini Enterprise Agent Platform を使用してエンベディングを生成する
  • Agent Platform Studio を使用する
  • Gemini Enterprise Agent Platform 生成モデルを使用してクエリ結果を拡充する
  • HNSW ベクトル インデックスを使用してクエリのパフォーマンスを向上させる

必要なもの

  • Google Cloud アカウントと Google Cloud プロジェクト
  • ウェブブラウザ(Chrome など)

2. 設定と要件

プロジェクトの設定

  1. Google Cloud コンソールにログインします。Google アカウント(Gmail または Google Workspace)をまだお持ちでない場合は、Google アカウントを作成する必要があります。

仕事用または学校用のアカウントではなく、個人用のアカウントを使用します。

  1. 新しいプロジェクトを作成するか、既存のプロジェクトを再利用します。Google Cloud コンソールで新しいプロジェクトを作成するには、ツールバーの [プロジェクトを選択] をクリックします。

Google Cloud コンソールのプロジェクト選択ダイアログ

[プロジェクトを選択] ダイアログで、[新しいプロジェクト] をクリックします。

37d264871000675d.png

ダイアログで、プロジェクト名を入力し、ロケーションを選択します。

96d86d3d5655cdbe.png

  • プロジェクト名は、このプロジェクトの参加者に表示される名称です。プロジェクト名は Google API では使用されず、いつでも変更できます。
  • プロジェクト ID は、すべての Google Cloud プロジェクトにおいて一意でなければならず、不変です(設定後は変更できません)。Google Cloud コンソールでは、一意の ID が自動的に生成されますが、カスタマイズすることもできます。生成された ID が気に入らない場合は、別のランダムな ID を生成するか、独自の ID を指定してその ID が使用可能かどうかを確認できます。ほとんどの Codelab では、プロジェクト ID を参照します。通常、プロジェクト ID は プレースホルダで識別されます。
  • 3 つ目の値として、一部の API が使用するプロジェクト番号があります。これら 3 つの値について詳しくは、プロジェクトの作成と管理に関するドキュメントをご覧ください。

課金を有効にする

個人用の請求先アカウントを設定する

Google Cloud クレジットを使用して課金を設定した場合は、この手順をスキップできます。

個人用請求先アカウントを設定するには、Google Cloud Billing コンソールで課金を有効にします。

注:

  • このラボを完了するために必要な Google Cloud リソースの費用は $5 USD 未満です。
  • このラボの最後の手順に沿ってリソースを削除し、追加料金が発生しないようにします。
  • 新規ユーザーは、300 米ドル分の無料トライアルをご利用いただけます。

Cloud Shell の起動

Google Cloud はパソコンからリモートで操作できますが、この Codelab では Google Cloud Shell(Cloud 上で動作するコマンドライン環境)を使用します。

Google Cloud コンソールのツールバーで、[Cloud Shell をアクティブにする] をクリックします。

Cloud Shell をアクティブにする

または、Google Cloud コンソール内で g キー、s キーの順に押すか、Cloud Shell を開きます。

環境のプロビジョニングと接続にはそれほど時間はかかりません。完了すると、接続されたターミナルが表示されます。

環境が接続されていることを示す Google Cloud Shell ターミナルのスクリーンショット

この仮想マシンには、必要な開発ツールがすべて用意されています。永続的なホーム ディレクトリが 5 GB 用意されており、Google Cloud で稼働します。そのため、ネットワークのパフォーマンスと認証機能が向上しています。この Codelab での作業はすべて、ブラウザ内から実行できます。

3. API を有効にする

Cloud SQL、Compute Engine、Service Networking、Gemini Enterprise Agent Platform を使用するには、Google Cloud プロジェクトでそれぞれの API を有効にします。

Cloud Shell ターミナルで、プロジェクト ID が設定されていることを確認します。

gcloud config set project <PROJECT_ID>

PROJECT_ID 環境変数を設定します。

PROJECT_ID=$(gcloud config get-value project)

必要なサービスをすべて有効にします。

gcloud services enable sqladmin.googleapis.com \
                       compute.googleapis.com \
                       cloudresourcemanager.googleapis.com \
                       servicenetworking.googleapis.com \
                       aiplatform.googleapis.com

予想される出力:

student@cloudshell:~ (test-project-001-402417)$ gcloud config set project test-project-001-402417
Updated property [core/project].
student@cloudshell:~ (test-project-001-402417)$ PROJECT_ID=$(gcloud config get-value project)
Your active configuration is: [cloudshell-14650]
student@cloudshell:~ (test-project-001-402417)$ 
student@cloudshell:~ (test-project-001-402417)$ gcloud services enable sqladmin.googleapis.com \
                       compute.googleapis.com \
                       cloudresourcemanager.googleapis.com \
                       servicenetworking.googleapis.com \
                       aiplatform.googleapis.com
Operation "operations/acat.p2-4470404856-1f44ebd8-894e-4356-bea7-b84165a57442" finished successfully.

有効になっている各 API については、ドキュメントをご覧ください。

4. Cloud SQL インスタンスを作成する

Gemini Enterprise Agent Platform データベース統合を使用して Cloud SQL インスタンスを作成します。

データベース パスワードを作成する

デフォルトのデータベース ユーザーのパスワードを定義します。独自のパスワードを定義することも、ランダム関数を使用してパスワードを生成することもできます。

export CLOUDSQL_PASSWORD=$(openssl rand -hex 16)

生成されたパスワード値を表示します。

echo $CLOUDSQL_PASSWORD

後で使用できるように、生成されたパスワードをメモしておきます。

Cloud SQL for PostgreSQL インスタンスを作成する

Cloud SQL インスタンスは、Google Cloud コンソール、Terraform、Google Cloud CLI(gcloud)など、いくつかの方法で作成できます。この Codelab では、gcloud を使用します。他のツールを使用してインスタンスを作成する方法については、インスタンスの作成のドキュメントをご覧ください。

Cloud Shell で次のコマンドを実行してインスタンスを作成します。

gcloud sql instances create my-cloudsql-instance \
--database-version=POSTGRES_18 \
--tier=db-custom-1-3840 \
--region=us-central1 \
--edition=ENTERPRISE \
--enable-google-ml-integration \
--database-flags cloudsql.enable_google_ml_integration=on

インスタンスを作成したら、デフォルト ユーザー(postgres)のパスワードを設定し、接続できることを確認します。

gcloud sql users set-password postgres \
    --instance=my-cloudsql-instance \
    --password=$CLOUDSQL_PASSWORD

gcloud sql connect を使用してインスタンスに接続します。プロンプトが表示されたら、パスワードを入力します。

gcloud sql connect my-cloudsql-instance --user=postgres

Ctrl+D キーを押すか、exit と入力して psql セッションを終了します。

exit

Gemini Enterprise Agent Platform の統合を有効にする

Gemini Enterprise Agent Platform の統合を有効にするために、必要な IAM ロールを Cloud SQL サービス アカウントに付与します。

Cloud SQL サービス アカウントのメールアドレスを取得し、環境変数としてエクスポートします。

SERVICE_ACCOUNT_EMAIL=$(gcloud sql instances describe my-cloudsql-instance --format="value(serviceAccountEmailAddress)")
echo $SERVICE_ACCOUNT_EMAIL

Cloud SQL サービス アカウントに roles/aiplatform.user ロールを付与します。

PROJECT_ID=$(gcloud config get-value project)
gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:$SERVICE_ACCOUNT_EMAIL" \
  --role="roles/aiplatform.user"

インスタンスの作成と構成の詳細については、Cloud SQL と Gemini Enterprise Agent Platform を統合するをご覧ください。

5. データベースを準備する

データベースを作成し、ベクトル サポートを有効にします。

データベースの作成

quickstart_db という名前のデータベースを作成します。 データベースは、データベース クライアント(psql など)、Google Cloud CLI、または Cloud SQL Studio を使用して作成できます。このステップでは、gcloud を使用します。

Cloud Shell で次のコマンドを実行して、データベースを作成します。

gcloud sql databases create quickstart_db --instance=my-cloudsql-instance

拡張機能を有効にする

Gemini Enterprise Agent Platform とベクトルを使用するには、quickstart_db データベースで google_ml_integration と vector の 2 つの拡張機能を有効にします。

Cloud Shell で、データベースに接続します。

gcloud sql connect my-cloudsql-instance --database quickstart_db --user=postgres

プロンプトが表示されたら、データベースのパスワードを入力します。

SQL セッションで、次のコマンドを実行します。

CREATE EXTENSION IF NOT EXISTS google_ml_integration CASCADE;
CREATE EXTENSION IF NOT EXISTS vector CASCADE;

SQL セッションを終了します。

exit;

6. データを読み込む

データベースにテーブルを作成し、CSV 形式で Cloud Storage の公開バケットに保存されている架空の Cymbal Store データセット ファイルを使用してデータを読み込みます。

まず、必要なスキーマ オブジェクトを作成します。gcloud sql connect と gcloud storage を実行して、スキーマをダウンロードしてインポートします。

Cloud Shell で次のコマンドを実行します(プロンプトが表示されたら、インスタンス用に作成したパスワードを入力します)。

gcloud storage cat gs://cloud-training/gcc/gcc-tech-004/cymbal_demo_schema.sql | gcloud sql connect my-cloudsql-instance --database quickstart_db --user=postgres

このコマンドは、データベースに接続し、ダウンロードした SQL コードを実行してテーブル、インデックス、シーケンスを作成します。

次に、Cloud Storage から CSV データファイルをダウンロードします。

gcloud storage cp gs://cloud-training/gcc/gcc-tech-004/cymbal_products.csv .
gcloud storage cp gs://cloud-training/gcc/gcc-tech-004/cymbal_inventory.csv .
gcloud storage cp gs://cloud-training/gcc/gcc-tech-004/cymbal_stores.csv .

データベースに接続します。

gcloud sql connect my-cloudsql-instance --database quickstart_db --user=postgres

CSV ファイルからデータをインポートします。

\copy cymbal_products from 'cymbal_products.csv' csv header
\copy cymbal_inventory from 'cymbal_inventory.csv' csv header
\copy cymbal_stores from 'cymbal_stores.csv' csv header

独自のデータを使用し、CSV ファイルが Google Cloud コンソールの Cloud SQL インポート ツールと互換性がある場合は、コマンドラインの代わりにコンソールを使用できます。

7. エンベディングを作成する

Gemini Enterprise Agent Platform の text-embedding-005 モデルを使用して商品紹介のエンベディングを構築し、ベクトルデータとして保存します。

セッションが切断された場合は、データベースに接続します。

gcloud sql connect my-cloudsql-instance --database quickstart_db --user=postgres

embedding 関数を使用して、cymbal_products テーブルに embedding という名前の生成された列を作成します。このコマンドは、テーブル内のすべての行の product_description 列から生成されたベクトル エンベディングを保持する保存された生成列を作成します。モデルは最初のパラメータとして指定され、ソーステキスト列は 2 番目のパラメータとして指定されます。

ALTER TABLE cymbal_products ADD COLUMN embedding vector(768) GENERATED ALWAYS AS (google_ml.embedding('text-embedding-005', product_description)) STORED;

900 ~ 1, 000 行の場合、このプロセスには通常 1 ~ 5 分かかります。

テーブルに新しい行を挿入するか、既存の行の product_description を更新すると、embedding 列が自動的に更新されます。

8. 類似性検索を実行する

商品紹介用に計算されたベクトル エンベディングと検索クエリのエンベディングを比較して、類似性検索を実行します。

SQL クエリは、gcloud sql connect を使用してコマンドラインから実行するか、Cloud SQL Studio から実行できます。Cloud SQL Studio を使用すると、出力に複数の行を含む長い SQL ステートメントをより簡単に編集して実行できます。

Cloud SQL Studio を起動する

  1. Google Cloud コンソールで Cloud SQL インスタンスに移動し、my-cloudsql-instance をクリックします。

Google Cloud コンソールの Cloud SQL インスタンスのリスト

  1. ナビゲーション メニューで [Cloud SQL Studio] をクリックします。

Cloud SQL Studio メニュー項目

  1. 認証ダイアログで、データベース名と認証情報を入力します。
    • データベース: quickstart_db
    • ユーザー: postgres
    • パスワード:
  2. [認証] をクリックします。

Cloud SQL Studio の認証ダイアログ

  1. [エディタ] タブをクリックして SQL エディタを開きます。

Cloud SQL Studio の SQL エディタタブ

クエリを実行

お客様のクエリ「この地域でよく育つ果樹は何ですか?」に最も関連性の高い上位 10 個の商品を取得するクエリを実行します。

SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        (cp.embedding <=> embedding('text-embedding-005','What kind of fruit trees grow well here?')::vector) as distance
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        distance ASC
LIMIT 10;

Cloud SQL Studio でクエリを入力し、[実行] をクリックします(または、psql セッションでクエリを実行します)。

Cloud SQL Studio で SQL クエリを実行する

クエリは、コサイン距離で並べ替えられた一致する商品を返します。

product_name       |                                   description                                    | sale_price | zip_code |      distance       
-------------------------+----------------------------------------------------------------------------------+------------+----------+---------------------
 Cherry Tree             | This is a beautiful cherry tree that will produce delicious cherries. It is an d |      75.00 |    93230 | 0.43922018972266397
 Meyer Lemon Tree        | Meyer Lemon trees are California's favorite lemon tree! Grow your own lemons by  |         34 |    93230 |  0.4685112926118228
 Toyon                   | This is a beautiful toyon tree that can grow to be over 20 feet tall. It is an e |      10.00 |    93230 |  0.4835677149651668
 California Lilac        | This is a beautiful lilac tree that can grow to be over 10 feet tall. It is an d |       5.00 |    93230 |  0.4947204525907498
 California Peppertree   | This is a beautiful peppertree that can grow to be over 30 feet tall. It is an e |      25.00 |    93230 |  0.5054166905547247
 California Black Walnut | This is a beautiful walnut tree that can grow to be over 80 feet tall. It is a d |     100.00 |    93230 |  0.5084219510932597
 California Sycamore     | This is a beautiful sycamore tree that can grow to be over 100 feet tall. It is  |     300.00 |    93230 |  0.5140519790508755
 Coast Live Oak          | This is a beautiful oak tree that can grow to be over 100 feet tall. It is an ev |     500.00 |    93230 |  0.5143126438081371
 Fremont Cottonwood      | This is a beautiful cottonwood tree that can grow to be over 100 feet tall. It i |     200.00 |    93230 |  0.5174774727252058
 Madrone                 | This is a beautiful madrona tree that can grow to be over 80 feet tall. It is an |      50.00 |    93230 |  0.5227400803389093
(10 rows)

9. 取得したデータを使用して LLM のレスポンスを改善する

Gemini Enterprise Agent Platform の基盤言語モデルへのプロンプトで、クエリ結果をグラウンディングされたコンテキストとして渡すことで、クライアント アプリケーションに対する生成 AI のレスポンスを改善します。

手順は次のとおりです。

  1. Cloud SQL のベクトル検索結果から JSON ペイロードを生成します。
  2. Agent Platform Studio でプロンプトをテストします。
  3. google_ml 統合を使用して、SQL からエンドツーエンドのプロンプトを直接実行します。

JSON 形式で出力を生成する

クエリを変更して、結果を JSON としてフォーマットし、1 行を返します。

WITH trees as (
SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        cp.uniq_id as product_id
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        (cp.embedding <=> embedding('text-embedding-005','What kind of fruit trees grow well here?')::vector) ASC
LIMIT 1)
SELECT json_agg(trees) FROM trees;

想定される JSON 出力:

[{"product_name":"Cherry Tree","description":"This is a beautiful cherry tree that will produce delicious cherries. It is an d","sale_price":75.00,"zip_code":93230,"product_id":"d536e9e823296a2eba198e52dd23e712"}]

Agent Platform Studio でプロンプトを実行する

生成された JSON を Agent Platform Studio の生成モデルへのプロンプトのコンテキストとして指定します。

  1. Google Cloud コンソールで Agent Platform Studio を開きます。

Agent Platform Studio のナビゲーション

  1. Agent Platform Studio に次のプロンプトを入力します。

Agent Platform Studio でプロンプトを入力する

You are a friendly advisor helping to find a product based on the customer's needs.
Based on the client request we have loaded a list of products closely related to search.
The list in JSON format with list of values like {"product_name":"name","description":"some description","sale_price":10,"zip_code": 10234, "product_id": "02056727942aeb714dc9a2313654e1b0"}
Here is the list of products:
<JSON_OUTPUT>
The customer asked "What tree is growing the best here?"
You should give information about the product, price and some supplemental information.
Do not ask any additional questions and assume location based on the zip code provided in the list of products.

は、クエリからの JSON レスポンスに置き換えます。

You are a friendly advisor helping to find a product based on the customer's needs.
Based on the client request we have loaded a list of products closely related to search.
The list in JSON format with list of values like {"product_name":"name","description":"some description","sale_price":10,"zip_code": 10234, "product_id": "02056727942aeb714dc9a2313654e1b0"}
Here is the list of products:
[{"product_name":"Cherry Tree","description":"This is a beautiful cherry tree that will produce delicious cherries. It is an d","sale_price":75.00,"zip_code":93230,"product_id":"d536e9e823296a2eba198e52dd23e712"}]
The customer asked "What tree is growing the best here?"
You should give information about the product, price and some supplemental information.
Do not ask any additional questions and assume location based on the zip code provided in the list of products.

Agent Platform Studio のプロンプト

  1. プロンプトを実行します。

Agent Platform Studio のプロンプトの結果

回答には、木と場所に関する情報に基づいてモデルが外部ソースから取得した価格、説明、補足情報が含まれます。

psql でプロンプトを実行する

また、Cloud SQL AI 統合と Gemini Enterprise Agent Platform を使用して、SQL 内で生成モデルから直接レスポンスを取得することもできます。まず、モデルを登録します。

  1. 必要に応じて、拡張機能をバージョン 1.4.3 以降にアップグレードします。quickstart_db に接続して、次のコマンドを実行します。
SELECT extversion from pg_extension where extname='google_ml_integration';

返されたバージョンが 1.4.3 より低い場合は、次のコマンドを実行します。

ALTER EXTENSION google_ml_integration UPDATE TO '1.4.3';
  1. google_ml_integration.enable_model_support データベース フラグを確認します。
SHOW google_ml_integration.enable_model_support;

フラグが off の場合は、Cloud Shell でデータベース フラグを更新します。

gcloud sql instances patch my-cloudsql-instance \
--database-flags google_ml_integration.enable_model_support=on,cloudsql.enable_google_ml_integration=on

この操作には 1 ~ 3 分かかります。設定を再度確認します。

SHOW google_ml_integration.enable_model_support;
  1. レスポンスを生成する gemini-3.5-flash モデルを登録します( は実際のプロジェクト ID に置き換えます)。
CALL
  google_ml.create_model(
    model_id => 'gemini-3.5-flash',
    model_request_url => 'https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/publishers/google/models/gemini-3.5-flash:generateContent',
    model_provider => 'google',
    model_auth_type => 'cloudsql_service_agent_iam');

登録されたモデルを確認します。

SELECT model_id, model_type FROM google_ml.model_info_view WHERE model_id='gemini-3.5-flash';
  1. 完全な SQL クエリを実行してベクトル検索結果を取得し、gemini-3.5-flash に直接渡します。
WITH trees AS (
SELECT
        cp.product_name,
        cp.product_description AS description,
        cp.sale_price,
        cs.zip_code,
        cp.uniq_id AS product_id
FROM
        cymbal_products cp
JOIN cymbal_inventory ci ON
        ci.uniq_id = cp.uniq_id
JOIN cymbal_stores cs ON
        cs.store_id = ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        (cp.embedding <=> embedding('text-embedding-005',
        'What kind of fruit trees grow well here?')::vector) ASC
LIMIT 1),
prompt AS (
SELECT
        'You are a friendly advisor helping to find a product based on the customer''s needs.
Based on the client request we have loaded a list of products closely related to search.
The list in JSON format with list of values like {"product_name":"name","product_description":"some description","sale_price":10}
Here is the list of products:' || json_agg(trees) || 'The customer asked "What kind of fruit trees grow well here?"
You should give information about the product, price and some supplemental information' AS prompt_text
FROM
        trees),
response AS (
SELECT
        google_ml.predict_row( model_id =>'gemini-3.5-flash',
        request_body => json_build_object('contents',
        json_build_object('role',
        'user',
        'parts',
        json_build_object('text',
        prompt_text))))->'candidates'->0->'content'->'parts'->0->'text' AS resp
FROM
        prompt)
SELECT
REPLACE(resp::text, '\n', CHR(10))
FROM
        response;

予想される出力:

"Hello there! If you're looking for a wonderful fruit tree to plant, I have a fantastic option for you: ### **Cherry Tree** * **Price:** $75.00 * **Product ID:** `d536e9e823296a2eba198e52dd23e712` --- ### **Why it's a great choice:** * **Fruit & Shade:** Not only will it produce delicious, sweet cherries, but it also grows into a beautiful 15-foot deciduous tree that provides excellent shade and privacy for your yard. * **Seasonal Beauty:** Its leaves are a lovely dark green throughout the summer and transition into a striking red during the fall. * **Ideal Growing Conditions:** Cherry trees thrive best in cool, moist climates with sandy soil and are suitable for **USDA hardiness zones 4–9**. If your local climate matches these conditions, this Cherry Tree would make a beautiful and tasty addition to your garden! Let me know if you'd like more details or help placing an order."

10. 最近傍インデックスを作成する

数百万のベクトルを含む大規模なデータセットの場合、ベクトル検索にはかなりのコンピューティング リソースが必要になることがあります。クエリのパフォーマンスを向上させるには、ベクトル エンベディングにインデックスを作成します。

HNSW インデックスを作成する

Hierarchical Navigable Small World(HNSW)は、グラフベースのベクトル インデックスです。

embedding 列に HNSW インデックスを作成するには、距離関数(vector_cosine_ops)と、m や ef_construction などのオプション パラメータを指定します。詳細については、ベクトル エンベディングを操作するをご覧ください。

CREATE INDEX cymbal_products_embeddings_hnsw ON cymbal_products
  USING hnsw (embedding vector_cosine_ops)
  WITH (m = 16, ef_construction = 64);

予想される出力:

quickstart_db=> CREATE INDEX cymbal_products_embeddings_hnsw ON cymbal_products
  USING hnsw (embedding vector_cosine_ops)
  WITH (m = 16, ef_construction = 64);
CREATE INDEX
quickstart_db=>

クエリのパフォーマンスを比較する

EXPLAIN (ANALYZE) を使用してベクトル検索クエリを実行し、クエリ プランナーがインデックスを使用していることを確認します。

EXPLAIN (ANALYZE) 
WITH trees as (
SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        cp.uniq_id as product_id
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        (cp.embedding <=> embedding('text-embedding-005','What kind of fruit trees grow well here?')::vector) ASC
LIMIT 1)
SELECT json_agg(trees) FROM trees;

予想される出力:

 Aggregate  (cost=779.12..779.13 rows=1 width=32) (actual time=1.066..1.069 rows=1 loops=1)
   ->  Subquery Scan on trees  (cost=769.05..779.12 rows=1 width=142) (actual time=1.038..1.041 rows=1 loops=1)
         ->  Limit  (cost=769.05..779.11 rows=1 width=158) (actual time=1.022..1.024 rows=1 loops=1)
               ->  Nested Loop  (cost=769.05..9339.69 rows=852 width=158) (actual time=1.020..1.021 rows=1 loops=1)
                     ->  Nested Loop  (cost=768.77..9316.48 rows=852 width=945) (actual time=0.858..0.859 rows=1 loops=1)
                           ->  Index Scan using cymbal_products_embeddings_hnsw on cymbal_products cp  (cost=768.34..2572.47 rows=941 width=941) (actual time=0.532..0.539 rows=3 loops=1)
...
 Planning Time: 112.398 ms
 Execution Time: 1.221 ms

実行プランに Index Scan using cymbal_products_embeddings_hnsw が表示されます。

EXPLAIN なしでクエリを実行します。

WITH trees as (
SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        cp.uniq_id as product_id
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        (cp.embedding <=> embedding('text-embedding-005','What kind of fruit trees grow well here?')::vector) ASC
LIMIT 1)
SELECT json_agg(trees) FROM trees;

予想される出力:

[{"product_name":"Cherry Tree","description":"This is a beautiful cherry tree that will produce delicious cherries. It is an d","sale_price":75.00,"zip_code":93230,"product_id":"d536e9e823296a2eba198e52dd23e712"}]

LangChain とベクトル インデックスの詳細と例については、Cloud SQL AI の概要のドキュメントをご覧ください。

11. リソースをクリーンアップする

この Codelab を完了したら、Cloud SQL インスタンスを削除してください。

セッションが切断された場合は、Cloud Shell でプロジェクトと環境変数を設定します。

export INSTANCE_NAME=my-cloudsql-instance
export PROJECT_ID=$(gcloud config get-value project)

インスタンスを削除します。

gcloud sql instances delete $INSTANCE_NAME --project=$PROJECT_ID

予想される出力:

student@cloudshell:~$ gcloud sql instances delete $INSTANCE_NAME --project=$PROJECT_ID
All of the instance data will be lost when the instance is deleted.

Do you want to continue (Y/n)?  y

Deleting Cloud SQL instance...done.                                                                                                                
Deleted [https://sandbox.googleapis.com/v1beta4/projects/test-project-001-402417/instances/my-cloudsql-instance].

12. 完了

おめでとうございます!この Codelab は終了です。

このラボは、「Google Cloud でのプロダクション レディな AI の開発」学習プログラムの一部です。

  • カリキュラム全体を確認して、プロトタイプから本番環境への移行をスムーズに進めましょう。
  • ハッシュタグ #ProductionReadyAI を使用して進捗状況を共有しましょう。

概要

具体的には、以下の方法について学習しました。

  • Cloud SQL for PostgreSQL インスタンスをデプロイする
  • データベースを作成して Cloud SQL AI 統合を有効にする
  • データベースにデータを読み込む
  • Cloud SQL Studio を使用する
  • Cloud SQL で Gemini Enterprise Agent Platform エンベディング モデルを使用する
  • Agent Platform Studio を使用する
  • Gemini Enterprise Agent Platform 生成モデルを使用してクエリ結果を拡充する
  • ベクトル インデックスを使用してクエリのパフォーマンスを向上させる

HNSW ではなく ScaNN インデックスを使用して、AlloyDB AI ベクトル エンベディング Codelab を試す。