使用 AI 函式執行智慧型 SQL 查詢

本頁面說明如何使用 AI 函式提供的 AI 輔助 SQL 運算子進行查詢。您可以使用 ai.if 篩選器、ai.rankai.generate 運算子,將自然語言與 SQL 查詢合併。

如要使用本頁的說明,您必須瞭解 AlloyDB,並熟悉生成式 AI 概念。

AlloyDB AI 會保留並建立 ai 結構定義。

事前準備

在 SQL 運算子中使用自然語言前,請先完成下列步驟:

與 Vertex AI 整合並安裝擴充功能

  1. 設定 Vertex AI 模型的使用者存取權
  2. 確認已安裝最新版 google_ml_integration
    1. 如要檢查已安裝的版本,請執行下列指令:

              SELECT extversion FROM pg_extension WHERE extname = 'google_ml_integration';
              extversion 
              ------------
              1.5.2
              (1 row)
            
    2. 如果尚未安裝擴充功能,或安裝的版本低於 1.5.2,請更新擴充功能。

              CREATE EXTENSION IF NOT EXISTS google_ml_integration;
              ALTER EXTENSION google_ml_integration UPDATE;
            

      如果在執行上述指令時遇到問題,或執行上述指令後,擴充功能未更新至 1.5.2 版,請與Google Cloud 支援團隊聯絡。

  3. 如要使用 AlloyDB AI 查詢引擎功能,請將 google_ml_integration.enable_ai_query_engine 標記設為 true

    SQL

    1. 為目前工作階段啟用 AI 查詢引擎。
                    SET google_ml_integration.enable_ai_query_engine = true;
                    
    2. 跨工作階段啟用特定資料庫的功能。
                    ALTER DATABASE DATABASE_NAME SET google_ml_integration.enable_ai_query_engine = 'on';
                    
    3. 為特定使用者啟用 AI 查詢引擎,適用於所有工作階段和資料庫。
                    ALTER ROLE postgres SET google_ml_integration.enable_ai_query_engine = 'on';
                  

    控制台

    如要修改 google_ml_integration.enable_ai_query_engine 旗標的值,請按照「設定執行個體的資料庫旗標」一文中的步驟操作。

    gcloud

    如要使用 gcloud CLI,可以安裝並初始化 Google Cloud CLI,也可以使用 Cloud Shell

    你可以修改 google_ml_integration.enable_ai_query_engine 旗標的值。 詳情請參閱「設定執行個體的資料庫旗標」。

                 gcloud alloydb instances update INSTANCE_ID \
                   --database-flags google_ml_integration.enable_ai_query_engine=on \
                   --region=REGION_ID \
                   --cluster=CLUSTER_ID \
                   --project=PROJECT_ID
                

使用所在地區支援的 Gemini 模型

如果 AlloyDB for PostgreSQL 叢集位於不支援 gemini-2.0-flash 的區域,您可以使用 model_id parameter,在該區域使用其他可用的 Gemini 模型。

或者,您也可以註冊 Gemini 模型端點,並將該模型 ID 提供給 AI 運算子。詳情請參閱「使用模型端點管理服務註冊及呼叫遠端 AI 模型」。

以下範例說明如何註冊另一個 Gemini 端點。在本例中,第二個 Gemini 端點是 gemini-2.0-flash 的全域端點。只要傳遞 model_id =>gemini-2.0-flash-global` 做為額外引數,即可搭配 AI 運算子使用這個已註冊的模型。

CALL
  google_ml.create_model(
    model_id => 'gemini-2.0-flash-global',
    model_type => 'llm',
    model_provider => 'google',
    model_qualified_name => 'gemini-2.0-flash',
    model_request_url =>  'https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/publishers/google/models/gemini-2.0-flash:generateContent',
    model_auth_type => 'alloydb_service_agent_iam'
);

使用 Gemini 3.0 模型

部分 Gemini 模型 (例如 gemini-3.0-pro-preview) 只能透過全球端點使用。您必須按照下列方式註冊這類模型:

CALL
  google_ml.create_model(
    model_id => 'gemini-3-preview-model',
    model_request_url => 'https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/publishers/google/models/gemini-3-pro-preview:generateContent',
    model_qualified_name => 'gemini-3-pro-preview',
    model_provider => 'google',
    model_type => 'llm',
    model_auth_type => 'alloydb_service_agent_iam'
);

PROJECT_ID 替換為 Vertex AI 模型所在的專案 ID。請注意,AlloyDB 服務帳戶必須在該專案中具備 Vertex AI 使用者角色

註冊模型後,您可以在 AI 函式中使用模型,如下所示:

SELECT ai.generate(prompt => 'What is AlloyDB?', model_id => 'gemini-3-preview-model');

在查詢中使用篩選器

AlloyDB AI 提供多種 AI 輔助的 SQL 函式,可讓您直接在資料庫查詢中使用自然語言處理和大型語言模型,包括 ai.ifai.rank 運算子。

篩選器

如要評估是否符合以自然語言陳述的條件,請使用 ai.if/google_ml.if 運算子。函式會傳回布林值 true 或 false,如果無法清楚偵測輸出內容,則會傳回 false

- Function signature
FUNCTION ai.if(prompt TEXT, model_id VARCHAR(100) DEFAULT NULL) RETURNS bool

以下範例說明如何使用 ai.if 運算子做為篩選器,找出位於人口超過 10 萬的城市,且有超過 500 則正面評論的餐廳。這個範例使用 restaurant_reviews,並包含評論和城市位置等資料。ai.if 運算子可協助你瞭解評論情緒,並將資料庫中的地點與 Gemini 對這些地點人口的一般知識結合。

SELECT r.name, r.location_city
FROM restaurant_reviews r
WHERE
  AI.IF(r.location_city || ' has a population OF more than 100,000 AND the following is a positive review; Review: ' || r.review)
GROUP BY r.name, r.location_city
HAVING COUNT(*) > 500;

以下範例與使用您所在區域支援的 Gemini 模型中的範例相同,但使用的是您註冊的模型。

SELECT r.name, r.location_city
FROM restaurant_reviews r
WHERE
  AI.IF(r.location_city || ' has a population of more than 100,000 AND the following is a positive review; Review: ' || r.review, model_id => 'gemini-2.0-flash-global')
GROUP BY r.name, r.location_city
HAVING COUNT(*) > 500;

對使用 if 運算子的查詢執行聯結

如要執行聯結作業,請搭配聯結使用 ai.if/google_ml.if 運算子。下列查詢範例會找出提及餐廳菜單中各個菜單項目的評論數量。

    SELECT item_name, COUNT(*)
    FROM menu_items JOIN user_reviews
      ON ai.if(
        prompt => 'Does the following user review talk about the menu item mentioned ? review: ' || user_reviews.review_text || ' menu item: ' || item_name)
    GROUP BY item_name;

生成和摘要文字

ai.generate 函式會結合提供的資料和使用者提示,產生文字。

-- Function Signature
FUNCTION ai.generate(prompt TEXT, model_id VARCHAR(100) DEFAULT NULL) RETURNS TEXT

舉例來說,您可以使用下列查詢,為每則使用者評論產生簡要摘要。

SELECT
  ai.generate(
    prompt => 'Summarize the review in 20 words or less. Review: ' || review) AS review_summary
FROM user_reviews

為查詢結果評分

如需使用自訂自然語言指令排序查詢結果,請使用 ai.rank 運算子。這項函式可讓您提供提示,說明排名條件,並傳回每個項目的分數。

-- Function signature
FUNCTION ai.rank(prompt TEXT, model_id VARCHAR(100) DEFAULT NULL) RETURNS real

舉例來說,下列查詢會使用 LLM 的評分,取得前 20 則最正面的餐廳評論。

SELECT review AS top20
FROM user_reviews
ORDER BY ai.rank(
  'Score the following review according to these rules:
  (1) Score OF 8 to 10 IF the review says the food IS excellent.
  (2) 4 to 7 IF the review says the food is ok.
  (3) 1 to 3 IF the review says the food is not good. Here is the review:' || review) DESC
LIMIT 20;

後續步驟