テキストの感情を分析する

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');

1 つの文字列の感情分析

単一のテキスト入力の感情を評価するには、ai.analyze_sentiment のスカラー バージョンを使用します。

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

次の例は、レビューデータを保存する id 列と review_content 列を含む reviews という名前のテーブルに保存されているテキストデータに対して、行レベルの感情分析を実行する方法を示しています。この例では、テーブルの各行の review_content 列に ai.analyze_sentiment() 関数を適用する SELECT クエリを実行します。この関数は、各レビューを個別に処理し、計算された感情(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

感情をバッチで分析する

大規模なデータセットでパフォーマンスを向上させるには、配列ベースの関数を使用して、1 回の呼び出しで複数の文字列を処理します。

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

次のステップ