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

ai.analyze_sentiment 関数は、テキストの感情をポジティブ、ネガティブ、ニュートラルに分類する組み込みの AlloyDB AI ツールです。この機能をデータベースに直接埋め込むことで、AlloyDB for PostgreSQL では、SQL を使用して Gemini の言語理解を非構造化エンタープライズ データにリアルタイムで適用できます。これにより、複雑な抽出、変換、読み込み(ETL)パイプラインを使用せずに、単一文字列分析、スカラー関数の高速化、配列ベースまたはカーソルベースのバッチ処理を数千行にわたってサポートできます。

ai.analyze_sentiment を使用して、非構造化された商品レビューや顧客フィードバックを分類したり、ソーシャル メディアのメンションを分析してブランドの認知度を測定したりできます。

始める前に

ai.analyze_sentiment 関数を使用する前に、次の要件を満たしていることを確認してください。

拡張機能を有効にする

ai.analyze_sentiment 関数を使用するには、権限を構成し、google_ml_integration 拡張機能をインストールまたは更新して、google_ml_integration.enable_ai_query_engine フラグを有効にします。

  1. AlloyDB インスタンスに、Agent Platform エンドポイントを呼び出すために必要な Identity and Access Management 権限があることを確認します。詳細については、Agent Platform モデルへのユーザー アクセスを構成するをご覧ください。

  2. google_ml_integration 拡張機能がバージョン 1.6.4 以降であることを確認します。インストールされているバージョンを確認するには、次のコマンドを実行します。

   SELECT extversion FROM pg_extension WHERE extname = 'google_ml_integration';

拡張機能がインストールされていない場合、または以前のバージョンの場合は、次のコマンドを実行してインストールして更新します。

   CREATE EXTENSION IF NOT EXISTS google_ml_integration;
   ALTER EXTENSION google_ml_integration UPDATE;
  1. 現在のセッションまたはデータベース全体で google_ml_integration.enable_ai_query_engine フラグを有効にします。現在のセッションでフラグを有効にするには、次のコマンドを実行します。

    SET google_ml_integration.enable_ai_query_engine = 'on';
    

    この変更により、データベースの再起動は必要ありません。このフラグのデフォルト値は on です。

サンプル テーブルを作成する

このドキュメントの感情分析の例に沿って、テーブルを作成し、次の映画レビューを入力します。

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 のスカラー バージョンを使用します。この関数は、入力ごとに positive、negative、neutral のいずれかの感情分類を返します。

ai.analyze_sentiment のスカラー バージョンの関数シグネチャは次のとおりです。

CREATE OR REPLACE FUNCTION ai.analyze_sentiment(
  input TEXT,
  model_id VARCHAR(100) DEFAULT NULL)
RETURNS TEXT

スカラー関数を呼び出すには、次の構文を使用します。

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

次のように置き換えます。

  • TEXT_CONTENT: 分析するテキスト文字列。
  • MODEL_ID: 省略可。使用するモデルの ID。省略すると、関数は google_ml_integration.default_llm_model フラグで指定されたモデルを使用します。デフォルトは gemini-3.5-flash-lite です。

次の例は、単一の文字列でスカラー関数を呼び出すさまざまな方法を示しています。

SELECT ai.analyze_sentiment('I am feeling joyful today');

SELECT ai.analyze_sentiment(input => 'I am feeling joyful today');

SELECT ai.analyze_sentiment(
  input => 'I am feeling joyful today',
  model_id => 'gemini-3.5-flash-lite'
);

これらのクエリは positive を返します。

次の例では、reviews テーブルに保存されているテキストデータに対して行レベルの感情分析を実行します。SELECT クエリは、テーブルの各行の review_content 列に ai.analyze_sentiment 関数を適用し、計算された感情(positive、negative、neutral)を返します。

-- Row-level sentiment analysis
SELECT id, ai.analyze_sentiment(review_content) FROM reviews ORDER BY id;

出力例を次に示します。

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

AI 関数アクセラレーションでスカラー関数を高速化する

AI 関数アクセラレーション(AIFA)は、入力を個別に処理するのではなく、自動的にバッチにグループ化することで、スカラー関数の実行を高速化します。Grand Unified Configuration(GUC)設定を使用してスカラー関数で AIFA を有効にすると、オーバーヘッドを削減し、クエリのパフォーマンスを向上させることができます。AIFA の有効化と構成の詳細については、AI 関数を使用してクエリのパフォーマンスを高速化するをご覧ください。

感情をバッチで分析する

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

配列ベースの ai.analyze_sentiment の関数シグネチャは次のとおりです。

CREATE OR REPLACE FUNCTION ai.analyze_sentiment(
  inputs TEXT[],
  batch_size INT DEFAULT NULL,
  model_id VARCHAR(100) DEFAULT NULL)
RETURNS TEXT[]

配列ベース関数を呼び出すには、次の構文を使用します。

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

次のように置き換えます。

  • TEXT_1、TEXT_2: TEXT[] 配列の要素として分析するテキスト文字列。
  • BATCH_SIZE: 省略可。バッチごとに処理する入力の数。デフォルト値は 10 です。
  • MODEL_ID: 省略可。使用するモデルの ID。省略すると、関数は google_ml_integration.default_llm_model フラグで指定されたモデルを使用します。デフォルトは gemini-3.5-flash-lite です。

次の例では、文字列の配列を ai.analyze_sentiment に直接渡します。

SELECT ai.analyze_sentiment(
  ARRAY[
    'I am feeling joyful today',
    'I am feeling sad today',
    'what is the capital of India ?'
  ]
);

出力例を次に示します。

{positive,negative,neutral}

次の例では、reviews テーブルの行を配列に集計し、レビューの感情をバッチで分析します。

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 => 10
    ) 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, reviews.review_content, correlated_results.sentiment AS sentiment
FROM reviews
JOIN correlated_results ON reviews.id = correlated_results.id
ORDER BY reviews.id;

出力例を次に示します。

 id |          review_content          | sentiment
----+----------------------------------+-----------
  1 | This movie is very good          | positive
  2 | The actors play the parts well   | positive
  3 | I like the music in this film    | positive
  4 | The story is easy to follow      | positive
  5 | Many people will enjoy this show | positive
  6 | The film is too long             | negative
  7 | I do not like the ending         | negative
  8 | This movie is very boring        | negative
  9 | The story is okay                | neutral
 10 | Some parts are fine              | 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

カーソルベースの関数を呼び出すには、次の構文を使用します。

SELECT ai.analyze_sentiment(
  input_cursor => INPUT_CURSOR,
  batch_size => BATCH_SIZE, -- Optional. The default value is 10.
  model_id => 'MODEL_ID' -- Optional. The default value is gemini-3.5-flash-lite.
);

次のように置き換えます。

  • INPUT_CURSOR: 分析する単一の TEXT 列を返すクエリを指す REFCURSOR。
  • BATCH_SIZE: 省略可。バッチごとに処理する入力の数。デフォルト値は 10 です。
  • MODEL_ID: 省略可。使用するモデルの ID。省略すると、関数は google_ml_integration.default_llm_model フラグで指定されたモデルを使用します。デフォルトは gemini-3.5-flash-lite です。

ai.analyze_sentiment は REFCURSOR を想定しているため、分析する単一のテキスト列のカーソルを開きます。この関数は、各行の input 列と output 列を含む結果カーソルを返します。

次の例では、reviews テーブルの review_content 列でカーソルを開き、ai.analyze_sentiment に渡します。

-- Run the cursor logic in an anonymous PL/pgSQL block
DO $$
DECLARE
  prompt_cursor REFCURSOR;
  result_cursor REFCURSOR;
  rec RECORD;
BEGIN
  -- 1. Open the input cursor
  OPEN prompt_cursor FOR
    SELECT review_content
    FROM reviews
    ORDER BY id;

  -- 2. Pass the input cursor to the function; it handles the processing and returns a result cursor
  result_cursor := ai.analyze_sentiment(
    input_cursor => prompt_cursor,
    batch_size => 10
  );

  -- 3. Loop through and print the results
  LOOP
    FETCH result_cursor INTO rec;
    EXIT WHEN NOT FOUND;
    RAISE NOTICE 'Review: %, Sentiment: %', rec.input, rec.output;
  END LOOP;

  -- 4. Clean up cursors
  CLOSE prompt_cursor;
  CLOSE result_cursor;
END;
$$;

出力例を次に示します。

NOTICE:  Review: This movie is very good, Sentiment: positive
NOTICE:  Review: The actors play the parts well, Sentiment: positive
NOTICE:  Review: I like the music in this film, Sentiment: positive
NOTICE:  Review: The story is easy to follow, Sentiment: positive
NOTICE:  Review: Many people will enjoy this show, Sentiment: positive
NOTICE:  Review: The film is too long, Sentiment: negative
NOTICE:  Review: I do not like the ending, Sentiment: negative
NOTICE:  Review: This movie is very boring, Sentiment: negative
NOTICE:  Review: The story is okay, Sentiment: neutral
NOTICE:  Review: Some parts are fine, Sentiment: neutral

制限事項

ai.analyze_sentiment 関数を使用する場合は、次の制限事項を考慮してください。

  • LLM は、予期しない出力を生成することがあります。モデルが positive、negative、neutral 以外の値を返した場合、ai.analyze_sentiment 関数はクエリエラーで失敗するのではなく、その入力に対して NULL を返します。配列ベースのバージョンでは、警告メッセージも返され、出力配列内のそのアイテムの位置に NULL が配置されます。
  • ai.analyze_sentiment 関数は、入力テキストが NULL、空の文字列('')、またはスペースのみを含む場合、または NULL または空の配列を配列ベースのバージョンに渡した場合、エラー(Invalid input: input cannot be null or empty.)を返します。
  • モデルのレイテンシはクエリのパフォーマンスに影響します。観測されたクエリ レイテンシは、モデルに対して行われた REST リクエストのレイテンシに似ています。

次のステップ