PostgreSQL용 AlloyDB의 ai.summarize 함수는 Gemini와 같은 대규모 언어 모델(LLM)을 사용하여 입력 텍스트를 가장 핵심적인 요점으로 압축하고 재구성합니다. SQL에서 직접 요약을 실행하면 수동 검토 없이 대규모 데이터 세트에서 주요 결과를 추출하고, 프롬프트에서 단어 또는 문장 제한을 지정하여 출력 길이를 제어하고, 행을 비동기식으로 일괄 처리할 수 있습니다.
ai.summarize를 사용하여 회의 스크립트를 결정 및 작업 항목으로 압축하거나, 기술 문서를 대략적인 개요로 요약하거나, 고객 지원 로그 및 사용자 리뷰를 통합된 문제 요약으로 집계할 수 있습니다.
시작하기 전에
ai.summarize 함수를 사용하기 전에 다음 요구사항을 충족하는지 확인하세요.
확장 프로그램 사용 설정
미리보기 기능이 사용 설정된 최신 버전의 google_ml_integration.enable_preview_ai_functions 확장 프로그램 (버전 1.6.1 이상)이 설치되어 있는지 확인합니다.
AlloyDB에서 google_ml_integration.enable_preview_ai_functions 플래그를 사용 설정하려면 SET 명령어를 사용합니다. 이 플래그는 ai.summarize와 같은 프리뷰 AI 함수에 대한 액세스를 제어합니다.
google_ml_integration extension이 버전 1.6.1 이상인지 확인합니다. 다음을 실행하여 버전을 확인할 수 있습니다.SELECT extversion FROM pg_extension WHERE extname = 'google_ml_integration';이러한 프리뷰 함수가 포함된 버전으로 업그레이드해야 하는 경우 다음을 호출합니다.
CALL google_ml.upgrade_to_preview_version();현재 세션 또는 전체 데이터베이스에 플래그를 사용 설정합니다. 현재 세션에 플래그를 사용 설정하려면 다음을 실행합니다.
SET google_ml_integration.enable_preview_ai_functions = 'on';이 변경사항은 데이터베이스를 다시 시작할 필요가 없습니다. 이 플래그의 기본값은
off입니다.
예시 테이블 만들기
이 문서의 요약 함수 예시를 따라 하려면 테이블을 만들고 다음 영화 리뷰로 채웁니다.
CREATE TABLE movie_reviews (
id INT PRIMARY KEY,
movie_id INT,
review TEXT
);
INSERT INTO movie_reviews (id, movie_id, review) VALUES
(1, 1, 'The Midnight Echo represents a masterclass in atmospheric tension. The cinematography captures the isolation of the frozen tundra perfectly while the lead actor delivers a superb performance. Although the pacing slows down significantly in the second act, the final twist remains unexpected. This is a truly remarkable experience.'),
(2, 1, 'Neon Velocity delivers high octane action but lacks the narrative depth required to make the stakes feel real. The visual effects are undeniably stunning, creating a vibrant cyberpunk world that pops off the screen. However, the dialogue feels cliched and the secondary characters are thin. This film is a shallow blockbuster.');
-- more rows are present in this table
단일 문자열 요약
단일 텍스트 블록을 처리하려면 ai.summarize의 스칼라 버전을 사용합니다.
SELECT ai.summarize(
input => 'TEXT_CONTENT',
additional_instructions => 'INSTRUCTIONS', -- Optional
model_id => 'MODEL_ID' -- Optional
);
다음 예시 쿼리를 실행하여 영화 리뷰의 간결한 요약을 제공합니다.
SELECT ai.summarize(review) FROM movie_reviews;
출력 예시는 다음과 같습니다.
id | summary
----+-----------------------------------------------------------
1 | "Atmospheric thriller with a haunting performance and shocking twist."
2 | "Visually stunning cyberpunk action film lacks narrative depth."
...
일괄 요약
여러 레코드를 효율적으로 처리하려면 배열 기반 버전을 사용하세요.
SELECT ai.summarize(
inputs => TEXT[],
additional_instructions => 'INSTRUCTIONS', -- Optional
batch_size => INT, -- Optional. The default value is 10.
model_id => VARCHAR(100) -- Optional. The default value is gemini-3.5-flash-lite.
);
다음 예시에서는 ai.summarize 함수의 배열 기반 버전을 사용하여 단일 호출에서 여러 텍스트 레코드를 효율적으로 처리하는 방법을 보여줍니다.
WITH summarized_results AS (
SELECT
ARRAY_AGG(id ORDER BY id) as ids,
ai.summarize(
inputs => array_agg(review ORDER BY id),
additional_instructions =>
'Please summarize this in max 10 words, review : ',
batch_size => 15
) as summaries
FROM movie_reviews
),
correlated_results AS (
SELECT ids[i] as ID, summaries[i] as summary
FROM summarized_results,
generate_series(1, array_length(ids, 1)) AS i
)
SELECT movie_reviews.id, correlated_results.summary as summary
FROM movie_reviews
JOIN correlated_results ON movie_reviews.id = correlated_results.id
ORDER BY movie_reviews.id DESC ;
출력 예시는 다음과 같습니다.
id | summary
---+----------------------------------------------------------------------------
1 | "Masterclass in tension, haunting performance with a twist."
2 | "High octane action, stunning visuals, shallow blockbuster."
3 | "Gentle, moving exploration of emotional honesty."
커서를 사용하여 요약하기
커서를 사용하면 잠재적으로 큰 리뷰 집합을 효율적으로 처리하여 AI 함수에 입력한 다음 결과를 하나씩 처리하여 데이터베이스에 다시 저장할 수 있습니다.
다음 예시에서는 ai.summarize 함수와 함께 커서를 사용하여 movie_reviews 테이블의 행을 효율적으로 처리하고, 각 리뷰의 요약을 생성하고, 이러한 요약을 review_summaries라는 새 테이블에 저장하는 방법을 보여줍니다.
이 커서 기반 접근 방식은 단일 배치로 처리하거나 한 번에 메모리에 맞추기에는 너무 큰 대규모 데이터 세트를 처리하는 데 유용합니다.
input_cursor 매개변수는 REFCURSOR를 사용합니다. 즉, SQL 쿼리 결과에 대한 포인터 역할을 하는 커서 이름을 제공해야 합니다. 그러면 ai.summarize 함수가 이 커서에서 데이터를 가져와 요약의 입력으로 사용합니다.
CREATE OR REPLACE FUNCTION ai.summarize(
input_cursor REFCURSOR,
additional_instructions TEXT DEFAULT NULL,
batch_size INT DEFAULT NULL,
model_id VARCHAR(100) DEFAULT NULL)
RETURNS REFCURSOR
다음 예시에서는 필요한 경우 review_summaries 테이블을 만든 다음 영화 리뷰를 반복하고 AI 함수를 사용하여 각 리뷰에 대한 간결한 요약을 생성하고 원본 리뷰 ID에 연결된 요약을 테이블에 저장합니다.
-- Create a table to store the results
CREATE TABLE IF NOT EXISTS review_summaries (
review_id INT,
summary_text TEXT
);
DO $$
DECLARE
-- Use descriptive cursor and variable names
review_cursor REFCURSOR;
result_record RECORD;
cursor_response REFCURSOR;
id_array INT[];
idx INT := 1;
BEGIN
-- 1. Open cursor for the input text
OPEN review_cursor FOR
SELECT review AS input FROM movie_reviews ORDER BY id;
-- 2. Call the AI summarize function
cursor_response := ai.summarize(
input_cursor => review_cursor,
additional_instructions => 'Please summarize the following review in max 10 words: '
);
-- 3. Map IDs into an array to maintain relational integrity during the loop
SELECT ARRAY_AGG(id ORDER BY id) INTO id_array FROM movie_reviews;
-- 4. Iterate through AI results and insert into the results table
LOOP
FETCH cursor_response INTO result_record;
EXIT WHEN NOT FOUND;
INSERT INTO review_summaries (review_id, summary_text)
VALUES (id_array[idx], result_record.output);
idx := idx + 1;
END LOOP;
-- 5. Clean up cursors
CLOSE review_cursor;
CLOSE cursor_response;
END;
$$;
-- Verify results
SELECT * FROM review_summaries;
출력 예시는 다음과 같습니다.
review_id | summary_text
-----------+---------------------------------------------------------------------------
1 | "Masterclass in atmospheric tension with haunting performance, devastating twist."
2 | "High octane action, stunning visuals, but shallow blockbuster."
3 | "Gentle, moving exploration of grief with poetic screenplay."
추가 요청 사항을 포함하여 요약하기
다음 SQL 쿼리는 요약을 안내하는 추가 안내를 전달합니다.
SELECT ai.agg_summarize(review, 'Please summarize this within 10 words') FROM movie_reviews GROUP BY movie_id;
특정 모델로 요약
추가 요청 사항을 제공하지 않고 모델을 지정하려면 모델 ID를 전달하고 명시적으로 VARCHAR로 변환하여 요청 사항으로 오인되지 않도록 해야 합니다.
SELECT ai.agg_summarize(review, 'gemini-3.5-flash-lite'::VARCHAR) FROM movie_reviews GROUP BY movie_id;
추가 요청 사항 및 특정 모델을 사용하여 요약하기
다음 SQL 쿼리는 추가 요청 사항과 특정 모델 ID를 모두 전달합니다.
SELECT ai.agg_summarize(review, 'Please summarize this within 10 words', 'gemini-3.5-flash-lite') FROM movie_reviews GROUP BY movie_id;
행 간 집계 요약
ai.agg_summarize 함수는 열의 여러 행에서 작동합니다.
값을 통합 프롬프트로 집계하여 전체 그룹에 대한 단일 요약을 생성합니다.
다음 SQL 쿼리는 ai.agg_summarize 집계 함수를 사용하여 movie_reviews 테이블의 모든 리뷰를 기반으로 각 movie_id에 대한 단일 통합 요약을 생성합니다.
SELECT ai.agg_summarize(review) FROM movie_reviews GROUP BY movie_id;
각 행을 개별적으로 요약하는 ai.summarize와 달리 ai.agg_summarize는 여러 행의 텍스트를 단일 입력으로 결합하여 전체 행 그룹에 대한 하나의 통합 요약을 생성합니다.
출력 예시는 다음과 같습니다.
agg_summarize
"The Midnight Echo is a masterclass in atmospheric tension, featuring haunting performances and stunning cinematography, though its pacing falters in the second act before a final twist. Neon Velocity offers stunning visual effects and high-octane action within a vibrant cyberpunk world, but suffers from shallow narrative depth, cliched dialogue, and underdeveloped characters. Garden of Whispers is a gentle, moving, and emotionally honest exploration of and life, characterized by poetic screenwriting and natural performances. Shadow Protocol ambitiously attempts to reinvent the spy thriller with a non-linear narrative and precise action, but ultimately confuses the audience and presents a derivative central mystery. The Last Alchemist uniquely blends historical drama with subtle fantasy, boasting meticulous production design and electric chemistry between its protagonists."