分析文字情緒

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.analyze_sentiment 等 AI 函式的存取權。

  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

後續步驟