텍스트 감정 분석

ai.analyze_sentiment 함수는 텍스트의 감정을 긍정, 부정 또는 중립으로 분류하는 기본 제공 AlloyDB AI 도구입니다. 이 기능을 데이터베이스에 직접 삽입함으로써 PostgreSQL용 AlloyDB를 사용하면 복잡한 추출, 변환, 로드 (ETL) 파이프라인 또는 외부 서비스 통합을 빌드하지 않고도 비정형 데이터를 처리할 수 있습니다.

감정 분석 함수는 다음과 같은 이점을 제공합니다.

  • 세계 지식: 대규모 언어 모델 (LLM)이 사전 학습 단계에서 습득하는 방대한 사실, 개념, 관계, 세계에 대한 맥락적 이해 모음입니다.
  • 실시간 분석: SQL을 사용하여 Gemini의 세계 지식을 엔터프라이즈 데이터에 적용합니다.
  • 확장성: 배열 기반 및 커서 기반 처리를 지원하여 수천 개의 행을 효율적으로 처리합니다.
  • 간단성: 모델 호출 및 데이터 준비를 자동으로 관리하는 상위 수준 추상화를 제공합니다.

AlloyDB AI의 감정 분석 함수는 다음과 같은 여러 사용 사례를 지원합니다.

  • 고객 의견: 수천 개의 원시 비정형 제품 리뷰를 분류하여 고객 만족도를 파악합니다.
  • 소셜 미디어 모니터링: 소셜 멘션 또는 댓글의 감정을 분석하여 브랜드에 대한 대중의 인식을 측정합니다.

시작하기 전에

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 extension이 버전 1.5.7 이상인지 확인합니다. 다음 명령어를 실행하여 버전을 확인할 수 있습니다.

    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(
  prompt => 'TEXT_CONTENT',
  model_id => 'MODEL_ID' -- Optional. The default value is gemini-2.5-flash-lite.
);

다음 예시에서는 리뷰 데이터를 저장하기 위한 idreview_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

일괄 감정 분석

더 큰 데이터 세트에서 더 나은 성능을 얻으려면 함수의 배열 기반 버전을 사용하여 단일 호출에서 여러 문자열을 처리합니다.

SELECT ai.analyze_sentiment(
  prompts => 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-2.5-flash-lite.
);

다음 예시에서는 reviews라는 테이블의 고객 리뷰 감정을 분석합니다.

WITH sentiment_results AS (
SELECT
  ARRAY_AGG(id ORDER BY id) as ids,
  ai.analyze_sentiment( 
    prompts => 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(
    prompt TEXT,
    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(
    prompt => 'Analyze the sentiment of the following movie review:',
    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;

출력은 다음과 같습니다.

      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

다음 단계