分析文本情感

ai.analyze_sentiment 函数是一个内置的 AlloyDB AI 工具,可将文本的情感分类为正面、负面或中性。通过将此功能直接嵌入数据库,AlloyDB for PostgreSQL 可让您使用 SQL 将 Gemini 语言理解功能实时应用于非结构化企业数据,从而支持跨数千行进行基于数组和基于游标的批处理,而无需复杂的提取、转换和加载 (ETL) 流水线。

您可以使用 ai.analyze_sentiment 对非结构化商品评价和客户反馈进行分类,或分析社交媒体提及情况,以衡量品牌认知度。

准备工作

在使用 ai.analyze_sentiment 函数之前,请确保您满足以下要求。

启用扩展程序

确保您已安装最新版本的 google_ml_integration.enable_preview_ai_functions 扩展程序(1.5.7 版或更高版本),并启用了预览功能。

如需在 AlloyDB 中启用 google_ml_integration.enable_preview_ai_functions 标志,请使用 SET 命令。此标志用于控制对预览版 AI 函数(例如 ai.analyze_sentiment)的访问权限。

  1. 确保您的 google_ml_integration 扩展程序版本为 1.6.1 或更高版本。 您可以通过运行以下命令来检查版本:

    SELECT extversion FROM pg_extension WHERE extname = 'google_ml_integration';
    

    如果您需要升级到包含这些预览版函数的版本,请调用以下命令:

    CALL google_ml.upgrade_to_preview_version();
    
  2. 为当前会话或整个数据库启用该标志。如需为当前会话启用该标志,请执行以下命令:

    SET google_ml_integration.enable_preview_ai_functions = 'on';
    

    此更改不需要重启数据库。此标志的默认值为 off。

创建示例表

如需按照本文档中的情感分析函数示例进行操作,请创建一个表,并使用以下影评填充该表。

CREATE TABLE IF NOT EXISTS reviews (
    id INT PRIMARY KEY,
    review_content TEXT
);

INSERT INTO reviews (id, review_content) VALUES 
(1, 'This movie is very good'),
(2, 'The actors play the parts well'),
(3, 'I like the music in this film'),
(4, 'The story is easy to follow'),
(5, 'Many people will enjoy this show'),
(6, 'The film is too long'),
(7, 'I do not like the ending'),
(8, 'This movie is very boring'),
(9, 'The story is okay'),
(10, 'Some parts are fine');

分析单个字符串的情感

如需评估单个文本输入的情感,请使用标量版本的 ai.analyze_sentiment。

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

以下示例展示了如何对存储在名为 reviews 的表中的文本数据执行行级情感分析,该表包含 id 和 review_content 列,用于存储评价数据。该示例执行一个 SELECT 查询,该查询将 ai.analyze_sentiment() 函数应用于表中每一行的 review_content 列。此函数会单独处理每条评价,并返回计算出的情感(positive、negative 或 neutral)。

--- Row Level sentiment analysis
SELECT ai.analyze_sentiment(review_content) FROM reviews;

以下是示例输出:

 id | analyze_sentiment
----+-------------------
  1 | positive
  2 | positive
  3 | positive
  4 | positive
  5 | positive
  6 | negative
  7 | negative
  8 | negative
  9 | neutral
 10 | neutral

批量分析情感

为了在处理大型数据集时获得更好的性能,请使用基于数组的函数版本,以便在单次调用中处理多个字符串。

SELECT ai.analyze_sentiment(
  inputs => ARRAY['TEXT_1', 'TEXT_2'],
  batch_size => BATCH_SIZE, -- Optional. The default value is 10.
  model_id => 'MODEL_ID' -- Optional. The default value is gemini-3.5-flash-lite.
);

以下示例分析了名为 reviews 的表中客户评价的情感。

WITH sentiment_results AS (
SELECT
  ARRAY_AGG(id ORDER BY id) as ids,
  ai.analyze_sentiment(
    inputs => array_agg( 'Please analyze the sentiment of this review: ' || review_content
      ORDER BY id),
    batch_size => 15) as sentiments 
FROM reviews
),
correlated_results AS (
    SELECT ids[i] as id, sentiments[i] as sentiment
    FROM sentiment_results,
    generate_series(1, array_length(ids, 1)) AS i
)
SELECT reviews.id, correlated_results.sentiment as sentiment
FROM reviews
JOIN correlated_results ON reviews.id = correlated_results.id
ORDER BY reviews.id DESC;

以下是示例输出:

 id | sentiment
----+-----------
  1 | positive
  2 | positive
  3 | positive
  4 | positive
  5 | positive
  6 | negative
  7 | negative
  8 | negative
  9 | neutral
 10 | neutral

使用光标分析情感

基于游标的函数旨在高效处理大型数据集,因为它允许系统以可管理的分批方式通过 AI 模型流式传输数据,而无需一次性将所有数据加载到内存中。

基于游标的 ai.analyze_sentiment 版本的函数签名如下所示:

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

现在,您可以使用 ai.analyze_sentiment 函数。由于它需要 REFCURSOR,因此您需要为要分析的输入数据打开一个游标。在此示例中,您将分析 reviews 表中的 review_content。

以下示例展示了如何使用游标逐行向 ai.analyze_sentiment 函数提供数据:

-- Run the cursor logic in an anonymous PL/pgSQL block
DO $$
DECLARE
    -- Declare a cursor for the review content
    review_cursor REFCURSOR;
    result_cursor REFCURSOR;
    result_record RECORD;
BEGIN
    -- Open the cursor with the query to fetch the review content
    OPEN review_cursor FOR SELECT review_content FROM reviews;

    -- Call the AI function, passing the cursor
    -- This function will return another cursor containing the results
    result_cursor := ai.analyze_sentiment(
            input_cursor => review_cursor,
        batch_size => 5  -- Optional: Process in batches of 5. The default value is 10.
    );

    -- Fetch and display results from the result_cursor
    LOOP
        FETCH result_cursor INTO result_record;
        EXIT WHEN NOT FOUND;
        RAISE NOTICE '%', result_record;
    END LOOP;

    -- Close the cursors
    CLOSE review_cursor;
    CLOSE result_cursor;
-- End the anonymous block
END $$;

输出如下所示:

      review_content            | sentiment | score
------------------------------+-----------+-------
This movie is very good        | Positive  |   0.9
The actors play the parts well | Positive  |   0.8
I like the music in this film  | Positive  |   0.8
The story is easy to follow    | Positive  |   0.7
Many people will enjoy this show | Positive  |   0.8
The film is too long           | Negative  |  -0.6
I do not like the ending       | Negative  |  -0.8
This movie is very boring      | Negative  |  -0.9
The story is okay              | Neutral   |   0.1
Some parts are fine            | Neutral   |   0.2

后续步骤