ai.analyze_sentiment 함수는 텍스트의 감정을 긍정적, 부정적, 중립적으로 분류하는 기본 제공 AlloyDB AI 도구입니다. 이 기능을 데이터베이스에 직접 삽입하면 AlloyDB Omni에서 복잡한 추출, 변환, 로드 (ETL) 파이프라인이나 외부 서비스 통합을 빌드하지 않고도 비정형 데이터를 처리할 수 있습니다.
감정 분석 함수는 다음과 같은 이점을 제공합니다.
- 세계 지식: 대규모 언어 모델 (LLM)이 선행 학습 단계에서 획득하는 세계에 대한 방대한 사실, 개념, 관계, 문맥 이해의 모음입니다.
- 실시간 분석: SQL을 사용하여 Gemini의 전 세계 지식을 엔터프라이즈 데이터에 적용합니다.
- 확장성: 배열 기반 및 커서 기반 처리를 지원하여 수천 개의 행을 효율적으로 처리합니다.
- 단순성: 모델 호출 및 데이터 준비를 자동으로 관리하는 상위 수준 추상화를 제공합니다.
AlloyDB AI 감정 분석 함수는 다음을 포함한 여러 사용 사례를 지원합니다.
- 고객 의견: 수천 개의 원시 비정형 제품 리뷰를 분류하여 고객 만족도 수준을 파악합니다.
- 소셜 미디어 모니터링: 소셜 미디어 언급 또는 댓글의 감정을 분석하여 브랜드에 대한 대중의 인식을 측정합니다.
시작하기 전에
ai.analyze_sentiment 함수를 사용하기 전에 다음 요구사항을 충족하는지 확인하세요.
확장 프로그램 사용 설정
AI 쿼리 엔진이 사용 설정된 google_ml_integration 확장 프로그램 (버전 1.6.3 이상)이 설치되어 있는지 확인합니다.
AlloyDB Omni에서 google_ml_integration.enable_ai_query_engine 플래그를 사용 설정하려면 SET 명령어를 사용합니다. 이 플래그는 ai.analyze_sentiment와 같은 AI 함수에 대한 액세스를 제어합니다.
google_ml_integration확장 프로그램이 버전 1.6.3 이상인지 확인합니다. 다음을 실행하여 버전을 확인할 수 있습니다.SELECT extversion FROM pg_extension WHERE extname = 'google_ml_integration';확장 프로그램을 업데이트해야 하는 경우 다음 명령어를 실행합니다.
ALTER EXTENSION google_ml_integration UPDATE;현재 세션 또는 전체 데이터베이스에 플래그를 사용 설정합니다. 현재 세션에 플래그를 사용 설정하려면 다음을 실행합니다.
SET google_ml_integration.enable_ai_query_engine = '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.
);
다음 예시에서는 리뷰 데이터를 저장하기 위해 id 및 review_content 열이 있는 reviews이라는 테이블에 저장된 텍스트 데이터에 대해 행 수준 감정 분석을 수행하는 방법을 보여줍니다. 이 예시에서는 테이블의 각 행에 대해 review_content 열에 ai.analyze_sentiment() 함수를 적용하는 SELECT 쿼리를 실행합니다. 이 함수는 각 리뷰를 개별적으로 처리하고 계산된 감정(positive, negative 또는 neutral)을 반환합니다.
--- Row Level sentiment analysis
SELECT id, 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.
);
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 => 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;
출력 예시는 다음과 같습니다.
id | sentiment
----+-----------
1 | positive
2 | positive
3 | positive
4 | positive
5 | positive
6 | negative
7 | negative
8 | negative
9 | neutral
10 | neutral
커서를 사용하여 감정 분석
커서 기반 함수는 대규모 데이터 세트를 효율적으로 처리하기 위한 것으로, 모든 데이터를 한 번에 메모리에 로드할 필요 없이 시스템이 관리 가능한 배치로 AI 모델을 통해 데이터를 스트리밍할 수 있게 해줍니다.
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 함수에 행별로 데이터를 제공하는 방법을 보여줍니다.
-- 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(
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;
출력은 다음과 같습니다.
input | output
----------------------------------+----------
This movie is very good | positive
The actors play the parts well | positive
I like the music in this film | positive
The story is easy to follow | positive
Many people will enjoy this show | positive
The film is too long | negative
I do not like the ending | negative
This movie is very boring | negative
The story is okay | neutral
Some parts are fine | neutral