擷取結構化資料

ai.extract 函式是內建的 AlloyDB AI 工具,可根據提供的結構定義,從非結構化文字中擷取指定的結構化詳細資料。AlloyDB for PostgreSQL 直接在資料庫中嵌入這項功能,因此您不必建構複雜的擷取、轉換和載入 (ETL) 管道,或整合外部服務,即可處理非結構化資料。

資料擷取功能有下列好處:

  • 擴充性:支援 AI 函式的智慧批次處理 (也稱為 AI 函式加速),這是 AlloyDB AI 的自動查詢執行最佳化功能,可在查詢執行期間,在背景將個別、逐列的純量 AI 函式呼叫,透明地分組為批次模型要求。此外,也支援陣列和游標式處理,可有效率地處理數千個資料列。
  • 抽象化:提供高階抽象化,自動管理模型叫用和資料準備。

AlloyDB AI 的資料擷取函式支援多種用途,包括:

  • 醫療照護:將自由格式的醫療筆記剖析為結構化格式欄位,例如病患姓名、症狀和藥物。
  • 房地產:將非結構化的房地產說明轉換為特定資料點,例如房地產類型和臥室數量。
  • 法律技術:自動從長篇法律文件中,找出並擷取準據法和責任限制等重要條款。
  • 財務營運:處理轉錄的應付憑據文字,準確擷取中繼資料和總金額,並轉換為一致的格式。

事前準備

使用 ai.extract 函式前,請確認您符合下列規定:

  • PostgreSQL 版本:PostgreSQL 18 以上版本支援 ai.extract 函式。確認 AlloyDB 叢集執行的是 PostgreSQL 18 以上版本。詳情請參閱「支援的資料庫版本」。
  • 擴充功能版本:請確認您已安裝最新版本 google_ml_integration 擴充功能 (1.6.1 以上版本),並啟用預覽功能。

啟用擴充功能

請確認您已安裝最新版本的 google_ml_integration 擴充功能 (1.6.1 以上版本),並啟用預覽功能。

如要在 AlloyDB 中啟用 google_ml_integration.enable_ai_query_engine 和 google_ml_integration.enable_preview_ai_functions 旗標,請使用 SET 指令。這些旗標可控管 AI 查詢引擎的存取權,以及預先發布版 AI 函式 (例如 ai.extract)。這些旗標的預設值為 off。

  1. 請確認 google_ml_integration 擴充功能為 1.6.1 以上版本。執行下列指令,查看版本:

    SELECT extversion FROM pg_extension WHERE extname = 'google_ml_integration';
    
  2. 如要為目前的工作階段、整個資料庫或執行個體上的所有資料庫啟用旗標,請執行下列一或多項工作:

    • 如要為目前的工作階段啟用旗標,請執行下列指令:

      SET google_ml_integration.enable_ai_query_engine = 'on';
      SET google_ml_integration.enable_preview_ai_functions = 'on';
      

      這項變更不需要重新啟動資料庫。

    • 如要為特定資料庫永久啟用旗標,請執行下列指令:

      ALTER DATABASE DATABASE_NAME SET google_ml_integration.enable_ai_query_engine = 'on';
      ALTER DATABASE DATABASE_NAME SET google_ml_integration.enable_preview_ai_functions = 'on';
      
    • 如要為執行個體上的所有資料庫啟用旗標,請使用 gcloud alloydb instances update 指令,將 google_ml_integration.enable_ai_query_engine 和 google_ml_integration.enable_preview_ai_functions 資料庫旗標設為 on:

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

      詳情請參閱「設定資料庫旗標」。

啟用 AI 函式的智慧批次處理功能

如要在多個資料列中執行純量 ai.extract 時,縮短總查詢執行時間,請將 google_ml_integration.enable_ai_function_acceleration 資料庫旗標設為 on,啟用 AI 函式的智慧批次處理功能:

SET google_ml_integration.enable_ai_function_acceleration = 'on';

啟用這個旗標後,AlloyDB 會自動在背景將個別純量 ai.extract 呼叫分組為智慧型批次。

建立範例資料表

如要按照本文件中的擷取函式範例操作,請建立資料表,並填入下列範例資料。

CREATE TABLE IF NOT EXISTS sales_leads (
    lead_id INT PRIMARY KEY,
    raw_transcript TEXT,
    lead_status VARCHAR(20)
);

INSERT INTO sales_leads (lead_id, raw_transcript, lead_status) VALUES
(1, 'Spoke with Alex R., Director of IT at Example Organization. They are looking to upgrade their cloud storage.', 'new'),
(2, 'Call with Kai L., Senior DevOps Engineer at Example Organization. They are currently using MySQL and Redis. Interested in automating enterprise database backups, cross-region replication, and automated scaling.', 'new'),
(3, 'Meeting with Taylor K., VP of Engineering at Example Organization. They need a scalable managed PostgreSQL database for their analytics platform. Budget is approved for Q3 launch.', 'new');

從單一字串擷取結構化資料

如要從單一文字輸入內容擷取結構化詳細資料,請使用 ai.extract 的純量版本。詳情請參閱 ai.extract 參考資料。

SELECT ai.extract(
  input => 'TEXT_CONTENT',
  output_schema => 'OUTPUT_SCHEMA',
  model_id => 'MODEL_ID' -- Optional. The default value is gemini-3.5-flash-lite.
);

從資料表擷取資料

以下範例會從 raw_transcript 資料表資料欄中擷取結構化資訊:

SELECT
  lead_id,
  ai.extract(
    input => raw_transcript,
    output_schema => '{"contact_name": {"type": "string"}, "company_name": {"type": "string"}, "job_title": {"type": "string"}}'
   ) AS extracted_info
FROM
  sales_leads
WHERE
  lead_status = 'new';

根據提供的 JSON 結構定義擷取欄位

下列範例會根據提供的 JSON 結構定義,從輸入文字中擷取特定欄位:

SELECT ai.extract(
  input => 'Spoke with Alex R., Director of IT at Example Organization. They are looking to upgrade their cloud storage.',
  output_schema => '{"contact_name": {"type": "string"}, "job_title": {"type": "string"}, "company_name": {"type": "string"}, "need": {"type": "string"}}'
);

輸出範例如下:

{
  "contact_name": "Alex R.",
  "job_title": "Director of IT",
  "company_name": "Example Organization",
  "need": "upgrade cloud storage"
}

根據自然語言提示擷取欄位

以下範例使用描述性文字結構定義,擷取待開發銷售對象詳細資料:

SELECT ai.extract(
  input => 'Meeting with Taylor K., VP of Engineering at Example Organization. They need a scalable managed PostgreSQL database for their analytics platform. Budget is approved for Q3 launch.',
  output_schema => 'Extract the following details as a clean, line-by-line list: Contact Name, Job Title, Company Name, Technical Requirement, Target Use Case, and Timeline.'
);

輸出範例如下:

Contact Name: Taylor K.
Job Title: VP of Engineering
Company Name: Example Organization
Technical Requirement: Scalable managed PostgreSQL database
Target Use Case: Analytics platform
Timeline: Q3 launch

使用陣列擷取欄位

以下範例會根據輸出結構定義,將多個值擷取至陣列欄位:

SELECT ai.extract(
  input => 'Call with Kai L., Senior DevOps Engineer at Example Organization. They are currently using MySQL and Redis. Interested in automating enterprise database backups, cross-region replication, and automated scaling.',
  output_schema => '{"contact_name": {"type": "string"}, "company_name": {"type": "string"}, "current_technologies": {"type": "array", "items": {"type": "string"}}, "interested_features": {"type": "array", "items": {"type": "string"}}}'
);

輸出範例如下:

{
  "contact_name": "Kai L.",
  "company_name": "Example Organization",
  "current_technologies": ["MySQL", "Redis"],
  "interested_features": ["enterprise database backups", "cross-region replication", "automated scaling"]
}

批次擷取結構化資料

如要在較大的資料集上縮短總查詢執行時間,請使用陣列式函式,在單一呼叫中處理多個輸入內容。詳情請參閱 ai.extract 參考資料。

SELECT ai.extract(
  inputs => TEXT[],
  output_schema => TEXT,
  batch_size => INT, -- Optional. The default value is 10.
  model_id => VARCHAR(100) -- Optional. The default value is gemini-3.5-flash-lite.
);

以下範例會從多筆記錄中擷取結構化詳細資料:

SELECT
  ai.extract(
    inputs => array_agg(raw_transcript ORDER BY lead_id),
    output_schema => '{"contact_name": {"type": "string"}, "company_name": {"type": "string"}, "job_title": {"type": "string"}}',
    batch_size => 4
  )
FROM sales_leads;

使用游標擷取結構化資料

游標式函式非常適合處理大型資料集,因為系統可以透過 AI 模型,以可管理的大小批次串流資料,不必一次將所有資料載入記憶體。詳情請參閱 ai.extract 參考資料。

ai.extract 游標版本函式簽章如下:

CREATE OR REPLACE FUNCTION ai.extract(
    input_cursor REFCURSOR,
    output_schema TEXT,
    batch_size INT DEFAULT NULL,
    model_id VARCHAR(100) DEFAULT NULL)
  RETURNS REFCURSOR

以下範例說明如何使用游標,逐列將資料提供給 ai.extract 函式:

DO $$
DECLARE
    input_cur REFCURSOR;
    output_cur REFCURSOR;
    result_record RECORD;
BEGIN
    -- Open the input cursor with the data to process
    OPEN input_cur FOR
        SELECT raw_transcript
        FROM sales_leads
        WHERE lead_status = 'new';

    -- Call ai.extract passing the input cursor
    output_cur := ai.extract(
        input_cursor => input_cur,
        output_schema => '{"contact_name": "string", "company_name": "string", "job_title": "string"}',
        batch_size => 10
    );

    -- Loop through the output cursor (columns: input TEXT, output TEXT)
    LOOP
        FETCH output_cur INTO result_record;
        EXIT WHEN NOT FOUND;

        RAISE NOTICE 'Extracted Data: %', result_record.output;
    END LOOP;

    CLOSE input_cur;
    CLOSE output_cur;
END $$;

後續步驟