分析文字情緒

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.analyze_sentiment 等預先發布版 AI 函式的存取權。

  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

後續步驟