ai.analyze_sentiment 함수는 텍스트의 감정을 긍정적, 부정적 또는 중립적으로 분류하는 기본 제공 AlloyDB AI 도구입니다. PostgreSQL용 AlloyDB는 이 기능을 데이터베이스에 직접 임베딩하여 SQL을 사용해 Gemini 언어 이해를 비정형 엔터프라이즈 데이터에 실시간으로 적용할 수 있게 해줍니다. 이를 통해 복잡한 추출, 변환, 로드(ETL) 파이프라인 없이도 수천 개의 행에 걸쳐 단일 문자열 분석, 스칼라 함수 가속, 배열 기반 또는 커서 기반 일괄 처리를 지원합니다.
ai.analyze_sentiment를 사용하여 비정형 제품 리뷰와 고객 의견을 분류하거나 소셜 미디어 멘션을 분석하여 브랜드 인식을 측정할 수 있습니다.
시작하기 전에
ai.analyze_sentiment 함수를 사용하기 전에 다음 요구사항을 충족하는지 확인하세요.
확장 프로그램 사용 설정
ai.analyze_sentiment 함수를 사용하려면 권한을 구성하고 google_ml_integration 확장 프로그램을 설치하거나 업데이트하고 google_ml_integration.enable_ai_query_engine 플래그를 사용 설정합니다.
AlloyDB 인스턴스에 Agent Platform 엔드포인트를 호출하는 데 필요한 Identity and Access Management 권한이 있는지 확인합니다. 자세한 내용은 Agent Platform 모델에 대한 사용자 액세스 구성을 참조하세요.
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;
현재 세션 또는 전체 데이터베이스에
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');
단일 문자열의 감정 분석
단일 텍스트 입력의 감정을 평가하려면 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)는 입력을 개별적으로 처리하는 대신 자동으로 일괄 그룹화하여 스칼라 함수 실행 속도를 높입니다. GUC(Grand Unified Configuration) 설정을 사용하여 스칼라 함수에 AIFA를 사용 설정하면 오버헤드를 줄이고 쿼리 성능을 개선할 수 있습니다. AIFA를 사용 설정하고 구성하는 방법에 대한 자세한 내용은 AI 함수를 사용하여 쿼리 성능 가속화를 참조하세요.
일괄 감정 분석
더 큰 데이터 세트에서 성능을 향상시키려면 배열 기반 버전의 함수를 사용하여 단일 호출에서 여러 문자열을 처리합니다.
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 요청의 지연 시간과 비슷합니다.