分析文本情感

选择文档版本:

ai.analyze_sentiment 函数是一个内置的 AlloyDB AI 工具,可将文本的情感分类为正面、负面或中性。通过将此功能直接嵌入到数据库中,AlloyDB Omni 让您无需构建复杂的提取、转换和加载 (ETL) 流水线或外部服务集成,即可处理非结构化数据。

情感分析功能具有以下优势:

  • 世界知识:大语言模型 (LLM) 在预训练阶段获取的关于世界的庞大事实、概念、关系和情境理解集合。
  • 实时分析:使用 SQL 将 Gemini 的世界知识应用于企业数据。
  • 可伸缩性:支持基于数组和基于游标的处理,可高效处理数千行数据。
  • 简单性:提供高级抽象,可自动管理模型调用和数据准备。

AlloyDB AI 情感分析函数支持多种应用场景,包括:

  • 客户反馈:对数千条原始、非结构化的产品评价进行分类,以确定客户满意度。
  • 社交媒体监控:分析社交媒体提及或评论中的情感倾向,以衡量公众对品牌的看法。

准备工作

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

启用扩展程序

确保您已安装 google_ml_integration 扩展程序(1.6.3 版或更高版本),并启用了 AI 查询引擎。

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

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

    SELECT extversion FROM pg_extension WHERE extname = 'google_ml_integration';
    

    如果您需要更新扩展程序,请运行以下命令:

    ALTER EXTENSION google_ml_integration UPDATE;
    
  2. 为当前会话或整个数据库启用该标志。如需为当前会话启用该标志,请执行以下命令:

    SET google_ml_integration.enable_ai_query_engine = '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 id, 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.
);
WITH sentiment_results AS (
SELECT
  ARRAY_AGG(id ORDER BY id) as ids,
  ai.analyze_sentiment( 
    inputs => array_agg(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;

以下是示例输出:

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

使用光标分析情感

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

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 函数提供数据:

-- Start a transaction
BEGIN;

-- Declare a cursor for the review content
DECLARE review_cursor REFCURSOR;

-- 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
DECLARE result_cursor REFCURSOR;
SELECT ai.analyze_sentiment(
    input_cursor => review_cursor,
    batch_size => 5  -- Optional: Process in batches of 5
) INTO result_cursor;

-- Fetch and display results from the result_cursor
-- The exact way to fetch from a REFCURSOR depends on the SQL environment.
-- This is a conceptual example.
FETCH ALL FROM result_cursor;

-- Close the cursors
CLOSE review_cursor;
CLOSE result_cursor;

-- End the transaction
COMMIT;

输出如下所示:

              input               |  output
----------------------------------+----------
 This movie is very good          | positive
 The actors play the parts well   | positive
 I like the music in this film    | positive
 The story is easy to follow      | positive
 Many people will enjoy this show | positive
 The film is too long             | negative
 I do not like the ending         | negative
 This movie is very boring        | negative
 The story is okay                | neutral
 Some parts are fine              | neutral

后续步骤