提取结构化数据

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

后续步骤