ai.extract 함수는 제공된 스키마를 기반으로 비정형 텍스트에서 지정된 정형 세부정보를 추출하는 기본 제공 AlloyDB AI 도구입니다.
이 기능을 데이터베이스에 직접 임베딩함으로써 PostgreSQL용 AlloyDB는 복잡한 추출, 변환, 로드 (ETL) 파이프라인이나 외부 서비스 통합을 빌드하지 않고도 비정형 데이터를 처리할 수 있게 해줍니다.
데이터 추출 기능은 다음과 같은 이점을 제공합니다.
- 확장성: AI 함수를 위한 스마트 일괄 처리(AI 함수 가속이라고도 함)를 지원합니다. 이는 AlloyDB AI의 자동 쿼리 실행 최적화 기능으로, 쿼리 실행 중에 백그라운드에서 개별 행별 스칼라 AI 함수 호출을 일괄 모델 요청으로 투명하게 그룹화합니다. 또한 배열 기반 및 커서 기반 처리를 지원하여 수천 개의 행을 효율적으로 처리합니다.
- 추상화: 모델 호출 및 데이터 준비를 자동으로 관리하는 상위 수준 추상화를 제공합니다.
AlloyDB AI의 데이터 추출 함수는 다음을 포함한 여러 사용 사례를 지원합니다.
- 의료: 자유 텍스트 의료 메모를 환자 이름, 증상, 약물과 같은 정형 형식 필드로 파싱합니다.
- 부동산: 비정형 부동산 설명을 부동산 유형, 침실 수와 같은 특정 데이터 포인트로 변환합니다.
- 법률 기술: 긴 법률 문서에서 준거법 및 책임 한도와 같은 중요한 용어를 자동으로 식별하고 가져옵니다.
- 재무 운영: 스크립트 작성된 인보이스 텍스트를 처리하여 메타데이터와 총 금액을 일관된 형식으로 정확하게 추출합니다.
시작하기 전에
ai.extract 함수를 사용하기 전에 다음 요구사항을 충족하는지 확인하세요.
- PostgreSQL 버전:
ai.extract함수는 PostgreSQL 버전 18 이상에서 지원됩니다. AlloyDB 클러스터가 PostgreSQL 18 이상을 실행 중인지 확인합니다. 자세한 내용은 지원되는 데이터베이스 버전을 참조하세요. - 확장 프로그램 버전: 프리뷰 기능이 사용 설정된 최신 버전의
google_ml_integration확장 프로그램 (버전1.6.1이상)이 설치되어 있는지 확인합니다.
확장 프로그램 사용 설정
미리보기 기능이 사용 설정된 최신 버전의 google_ml_integration 확장 프로그램 (버전 1.6.1 이상)이 설치되어 있는지 확인합니다.
AlloyDB에서 google_ml_integration.enable_ai_query_engine 및 google_ml_integration.enable_preview_ai_functions 플래그를 사용 설정하려면 SET 명령어를 사용합니다. 이러한 플래그는 AI 쿼리 엔진에 대한 액세스를 제어하고 ai.extract와 같은 AI 함수를 미리 봅니다. 이러한 플래그의 기본값은 off입니다.
google_ml_integration확장 프로그램이 버전1.6.1이상인지 확인합니다. 다음을 실행하여 버전을 확인합니다.SELECT extversion FROM pg_extension WHERE extname = 'google_ml_integration';현재 세션, 전체 데이터베이스 또는 인스턴스의 모든 데이터베이스에 대해 플래그를 사용 설정하려면 다음 작업 중 하나 이상을 수행합니다.
현재 세션에 플래그를 사용 설정하려면 다음을 실행합니다.
SET google_ml_integration.enable_ai_query_engine = 'on'; SET google_ml_integration.enable_preview_ai_functions = 'on';이 변경사항은 데이터베이스를 다시 시작할 필요가 없습니다.
특정 데이터베이스에 플래그를 영구적으로 사용 설정하려면 다음을 실행합니다.
ALTER DATABASE DATABASE_NAME SET google_ml_integration.enable_ai_query_engine = 'on'; ALTER DATABASE DATABASE_NAME SET google_ml_integration.enable_preview_ai_functions = 'on';인스턴스의 모든 데이터베이스에 플래그를 사용 설정하려면
gcloud alloydb instances update명령어를 사용하여google_ml_integration.enable_ai_query_engine및google_ml_integration.enable_preview_ai_functions데이터베이스 플래그를on로 설정합니다.gcloud alloydb instances update INSTANCE_ID --database-flags google_ml_integration.enable_ai_query_engine=on,google_ml_integration.enable_preview_ai_functions=on --region=REGION_ID --cluster=CLUSTER_ID --project=PROJECT_ID자세한 내용은 데이터베이스 플래그 구성을 참조하세요.
AI 함수에 스마트 일괄 처리 사용 설정하기
여러 행에서 스칼라 ai.extract를 실행할 때 총 쿼리 실행 시간을 단축하려면 google_ml_integration.enable_ai_function_acceleration 데이터베이스 플래그를 on로 설정하여 AI 함수에 스마트 일괄 처리를 사용 설정합니다.
SET google_ml_integration.enable_ai_function_acceleration = 'on';
이 플래그를 사용 설정하면 AlloyDB가 백그라운드에서 개별 스칼라 ai.extract 호출을 스마트 배치로 자동 그룹화합니다.
예시 테이블 만들기
이 문서의 추출 함수 예시를 따라 하려면 테이블을 만들고 다음 샘플 데이터로 채웁니다.
CREATE TABLE IF NOT EXISTS sales_leads (
lead_id INT PRIMARY KEY,
raw_transcript TEXT,
lead_status VARCHAR(20)
);
INSERT INTO sales_leads (lead_id, raw_transcript, lead_status) VALUES
(1, 'Spoke with Alex R., Director of IT at Example Organization. They are looking to upgrade their cloud storage.', 'new'),
(2, 'Call with Kai L., Senior DevOps Engineer at Example Organization. They are currently using MySQL and Redis. Interested in automating enterprise database backups, cross-region replication, and automated scaling.', 'new'),
(3, 'Meeting with Taylor K., VP of Engineering at Example Organization. They need a scalable managed PostgreSQL database for their analytics platform. Budget is approved for Q3 launch.', 'new');
단일 문자열에서 구조화된 데이터 추출
단일 텍스트 입력에서 구조화된 세부정보를 추출하려면 ai.extract의 스칼라 버전을 사용합니다. 자세한 내용은 ai.extract 참조를 확인하세요.
SELECT ai.extract(
input => 'TEXT_CONTENT',
output_schema => 'OUTPUT_SCHEMA',
model_id => 'MODEL_ID' -- Optional. The default value is gemini-3.5-flash-lite.
);
테이블에서 데이터 추출
다음 예시에서는 raw_transcript 테이블 열에서 정형 정보를 추출합니다.
SELECT
lead_id,
ai.extract(
input => raw_transcript,
output_schema => '{"contact_name": {"type": "string"}, "company_name": {"type": "string"}, "job_title": {"type": "string"}}'
) AS extracted_info
FROM
sales_leads
WHERE
lead_status = 'new';
제공된 JSON 스키마를 기반으로 필드 추출
다음 예시에서는 제공된 JSON 스키마를 기반으로 입력 텍스트에서 특정 필드를 추출합니다.
SELECT ai.extract(
input => 'Spoke with Alex R., Director of IT at Example Organization. They are looking to upgrade their cloud storage.',
output_schema => '{"contact_name": {"type": "string"}, "job_title": {"type": "string"}, "company_name": {"type": "string"}, "need": {"type": "string"}}'
);
출력 예시는 다음과 같습니다.
{
"contact_name": "Alex R.",
"job_title": "Director of IT",
"company_name": "Example Organization",
"need": "upgrade cloud storage"
}
자연어 프롬프트를 기반으로 필드 추출
다음 예시에서는 설명 텍스트 스키마를 사용하여 판매 리드 세부정보를 추출합니다.
SELECT ai.extract(
input => 'Meeting with Taylor K., VP of Engineering at Example Organization. They need a scalable managed PostgreSQL database for their analytics platform. Budget is approved for Q3 launch.',
output_schema => 'Extract the following details as a clean, line-by-line list: Contact Name, Job Title, Company Name, Technical Requirement, Target Use Case, and Timeline.'
);
출력 예시는 다음과 같습니다.
Contact Name: Taylor K.
Job Title: VP of Engineering
Company Name: Example Organization
Technical Requirement: Scalable managed PostgreSQL database
Target Use Case: Analytics platform
Timeline: Q3 launch
배열이 있는 필드 추출
다음 예시에서는 출력 스키마를 기반으로 여러 값을 배열 필드로 추출합니다.
SELECT ai.extract(
input => 'Call with Kai L., Senior DevOps Engineer at Example Organization. They are currently using MySQL and Redis. Interested in automating enterprise database backups, cross-region replication, and automated scaling.',
output_schema => '{"contact_name": {"type": "string"}, "company_name": {"type": "string"}, "current_technologies": {"type": "array", "items": {"type": "string"}}, "interested_features": {"type": "array", "items": {"type": "string"}}}'
);
출력 예시는 다음과 같습니다.
{
"contact_name": "Kai L.",
"company_name": "Example Organization",
"current_technologies": ["MySQL", "Redis"],
"interested_features": ["enterprise database backups", "cross-region replication", "automated scaling"]
}
구조화된 데이터 일괄 추출
더 큰 데이터 세트에서 총 쿼리 실행 시간을 단축하려면 배열 기반 버전의 함수를 사용하여 단일 호출에서 여러 입력을 처리합니다.
자세한 내용은 ai.extract 참조를 확인하세요.
SELECT ai.extract(
inputs => TEXT[],
output_schema => TEXT,
batch_size => INT, -- Optional. The default value is 10.
model_id => VARCHAR(100) -- Optional. The default value is gemini-3.5-flash-lite.
);
다음 예시에서는 여러 레코드에서 구조화된 세부정보를 추출합니다.
SELECT
ai.extract(
inputs => array_agg(raw_transcript ORDER BY lead_id),
output_schema => '{"contact_name": {"type": "string"}, "company_name": {"type": "string"}, "job_title": {"type": "string"}}',
batch_size => 4
)
FROM sales_leads;
커서를 사용하여 구조화된 데이터 추출
커서 기반 함수는 모든 데이터를 한 번에 메모리에 로드할 필요 없이 시스템이 관리 가능한 배치로 AI 모델을 통해 데이터를 스트리밍할 수 있으므로 대규모 데이터 세트를 처리하는 데 적합합니다. 자세한 내용은 ai.extract 참조를 확인하세요.
커서 기반 버전의 ai.extract에 대한 함수 서명은 다음과 같습니다.
CREATE OR REPLACE FUNCTION ai.extract(
input_cursor REFCURSOR,
output_schema TEXT,
batch_size INT DEFAULT NULL,
model_id VARCHAR(100) DEFAULT NULL)
RETURNS REFCURSOR
다음 예시에서는 커서를 사용하여 ai.extract 함수에 행별로 데이터를 제공하는 방법을 보여줍니다.
DO $$
DECLARE
input_cur REFCURSOR;
output_cur REFCURSOR;
result_record RECORD;
BEGIN
-- Open the input cursor with the data to process
OPEN input_cur FOR
SELECT raw_transcript
FROM sales_leads
WHERE lead_status = 'new';
-- Call ai.extract passing the input cursor
output_cur := ai.extract(
input_cursor => input_cur,
output_schema => '{"contact_name": "string", "company_name": "string", "job_title": "string"}',
batch_size => 10
);
-- Loop through the output cursor (columns: input TEXT, output TEXT)
LOOP
FETCH output_cur INTO result_record;
EXIT WHEN NOT FOUND;
RAISE NOTICE 'Extracted Data: %', result_record.output;
END LOOP;
CLOSE input_cur;
CLOSE output_cur;
END $$;