PostgreSQL용 Cloud SQL에서 벡터 임베딩 시작하기

1. 소개

이 Codelab에서는 벡터 검색과 Gemini Enterprise Agent Platform 임베딩을 결합하여 PostgreSQL용 Cloud SQL AI 통합을 사용하는 방법을 알아봅니다.

Gemini Enterprise Agent Platform과의 Cloud SQL 통합을 보여주는 아키텍처 다이어그램

기본 요건

  • Google Cloud 및 Google Cloud 콘솔에 대한 기본적인 이해
  • 명령줄 인터페이스 및 Cloud Shell에 대한 기본 경험

실습할 내용

  • PostgreSQL용 Cloud SQL 인스턴스 배포
  • 데이터베이스를 만들고 Cloud SQL AI 통합 사용 설정
  • 데이터베이스에 데이터 로드
  • Cloud SQL Studio 사용
  • Cloud SQL에서 Gemini Enterprise Agent Platform을 사용하여 임베딩 생성
  • Agent Platform Studio 사용
  • Gemini Enterprise Agent Platform 생성형 모델을 사용하여 쿼리 결과 보강
  • HNSW 벡터 색인을 사용하여 쿼리 성능 개선

필요한 항목

  • Google Cloud 계정 및 Google Cloud 프로젝트
  • 웹브라우저(예: Chrome)

2. 설정 및 요건

프로젝트 설정

  1. Google Cloud 콘솔에 로그인합니다. 아직 Google 계정 (Gmail 또는 Google Workspace)이 없으면 Google 계정을 만들어야 합니다.

직장 또는 학교 계정 대신 개인 계정을 사용하세요.

  1. 새 프로젝트를 만들거나 기존 프로젝트를 재사용합니다. Google Cloud 콘솔에서 새 프로젝트를 만들려면 툴바에서 프로젝트 선택을 클릭합니다.

Google Cloud 콘솔의 프로젝트 선택 대화상자

프로젝트 선택 대화상자에서 새 프로젝트를 클릭합니다.

37d264871000675d.png

대화상자에서 프로젝트 이름을 입력하고 위치를 선택합니다.

96d86d3d5655cdbe.png

  • 프로젝트 이름은 이 프로젝트 참가자의 표시 이름입니다. 프로젝트 이름은 Google API에서 사용되지 않으며 언제든지 변경할 수 있습니다.
  • 프로젝트 ID는 모든 Google Cloud 프로젝트에서 고유하며, 변경할 수 없습니다 (설정된 후에는 변경할 수 없음). Google Cloud 콘솔에서 고유 ID를 자동으로 생성하지만 이를 맞춤설정할 수 있습니다. 생성된 ID가 마음에 들지 않으면 다른 임의 ID를 생성하거나 자체 ID를 제공하여 사용 가능 여부를 확인할 수 있습니다. 대부분의 Codelab에서는 프로젝트 ID를 참조하며, 이는 일반적으로 자리표시자로 식별됩니다.
  • 세 번째 값인 프로젝트 번호는 일부 API에서 사용됩니다. 이 세 가지 값에 대한 자세한 내용은 프로젝트 만들기 및 관리 문서를 참고하세요.

결제 사용 설정

개인 결제 계정 설정

Google Cloud 크레딧을 사용하여 결제를 설정한 경우 이 단계를 건너뛸 수 있습니다.

개인 결제 계정을 설정하려면 Google Cloud Billing 콘솔에서 결제를 사용 설정하세요.

참고:

  • 이 실습을 완료하는 데 드는 Google Cloud 리소스 비용은 5달러 미만입니다.
  • 이 실습의 마지막 단계에 따라 리소스를 삭제하여 추가 요금이 청구되지 않도록 하세요.
  • 신규 사용자는 미화$300 상당의 무료 체험판을 이용할 수 있습니다.

Cloud Shell 시작

컴퓨터에서 Google Cloud를 원격으로 운영할 수도 있지만, 이 Codelab에서는 클라우드에서 실행되는 명령줄 환경인 Google Cloud Shell을 사용합니다.

Google Cloud 콘솔 툴바에서 Cloud Shell 활성화를 클릭합니다.

Cloud Shell 활성화

또는 Google Cloud 콘솔에서 g와 s를 차례로 누르거나 Cloud Shell을 엽니다.

환경을 프로비저닝하고 연결하는 데 몇 분 정도만 걸립니다. 완료되면 연결된 터미널이 표시됩니다.

환경이 연결되었음을 보여주는 Google Cloud Shell 터미널 스크린샷

이 가상 머신에는 필요한 모든 개발 도구가 로드되어 있습니다. 영구적인 5GB 홈 디렉터리를 제공하고 Google Cloud에서 실행되므로 네트워크 성능과 인증이 개선됩니다. 이 Codelab의 모든 작업은 브라우저 내에서 수행할 수 있습니다.

3. API 사용 설정

Cloud SQL, Compute Engine, Service Networking, Gemini Enterprise Agent Platform을 사용하려면 Google Cloud 프로젝트에서 각 API를 사용 설정해야 합니다.

Cloud Shell 터미널에서 프로젝트 ID가 설정되어 있는지 확인합니다.

gcloud config set project <PROJECT_ID>

PROJECT_ID 환경 변수를 설정합니다.

PROJECT_ID=$(gcloud config get-value project)

필수 서비스를 모두 사용 설정합니다.

gcloud services enable sqladmin.googleapis.com \
                       compute.googleapis.com \
                       cloudresourcemanager.googleapis.com \
                       servicenetworking.googleapis.com \
                       aiplatform.googleapis.com

예상 출력:

student@cloudshell:~ (test-project-001-402417)$ gcloud config set project test-project-001-402417
Updated property [core/project].
student@cloudshell:~ (test-project-001-402417)$ PROJECT_ID=$(gcloud config get-value project)
Your active configuration is: [cloudshell-14650]
student@cloudshell:~ (test-project-001-402417)$ 
student@cloudshell:~ (test-project-001-402417)$ gcloud services enable sqladmin.googleapis.com \
                       compute.googleapis.com \
                       cloudresourcemanager.googleapis.com \
                       servicenetworking.googleapis.com \
                       aiplatform.googleapis.com
Operation "operations/acat.p2-4470404856-1f44ebd8-894e-4356-bea7-b84165a57442" finished successfully.

사용 설정된 각 API에 대한 자세한 내용은 문서를 참고하세요.

4. Cloud SQL 인스턴스 만들기

Gemini Enterprise Agent Platform 데이터베이스 통합을 사용하여 Cloud SQL 인스턴스를 만듭니다.

데이터베이스 비밀번호 만들기

기본 데이터베이스 사용자의 비밀번호를 정의합니다. 직접 비밀번호를 정의하거나 무작위 함수를 사용하여 비밀번호를 생성할 수 있습니다.

export CLOUDSQL_PASSWORD=$(openssl rand -hex 16)

생성된 비밀번호 값을 표시합니다.

echo $CLOUDSQL_PASSWORD

나중에 사용할 수 있도록 생성된 비밀번호를 기록해 둡니다.

PostgreSQL용 Cloud SQL 인스턴스 만들기

Google Cloud 콘솔, Terraform, Google Cloud CLI (gcloud) 등 여러 방법을 사용하여 Cloud SQL 인스턴스를 만들 수 있습니다. 이 Codelab에서는 gcloud를 사용합니다. 다른 도구를 사용하여 인스턴스를 만드는 방법을 알아보려면 인스턴스 만들기 문서를 참고하세요.

Cloud Shell에서 다음 명령어를 실행하여 인스턴스를 만듭니다.

gcloud sql instances create my-cloudsql-instance \
--database-version=POSTGRES_18 \
--tier=db-custom-1-3840 \
--region=us-central1 \
--edition=ENTERPRISE \
--enable-google-ml-integration \
--database-flags cloudsql.enable_google_ml_integration=on

인스턴스를 만든 후 기본 사용자 (postgres)의 비밀번호를 설정하고 연결할 수 있는지 확인합니다.

gcloud sql users set-password postgres \
    --instance=my-cloudsql-instance \
    --password=$CLOUDSQL_PASSWORD

gcloud sql connect를 사용하여 인스턴스에 연결합니다. 메시지가 표시되면 다음 비밀번호를 입력합니다.

gcloud sql connect my-cloudsql-instance --user=postgres

Ctrl+D를 누르거나 exit를 입력하여 psql 세션을 종료합니다.

exit

Gemini Enterprise Agent Platform 통합 사용 설정

Gemini Enterprise Agent Platform 통합을 사용 설정하기 위해 Cloud SQL 서비스 계정에 필요한 IAM 역할을 부여합니다.

Cloud SQL 서비스 계정 이메일을 가져와 환경 변수로 내보냅니다.

SERVICE_ACCOUNT_EMAIL=$(gcloud sql instances describe my-cloudsql-instance --format="value(serviceAccountEmailAddress)")
echo $SERVICE_ACCOUNT_EMAIL

Cloud SQL 서비스 계정에 roles/aiplatform.user 역할을 부여합니다.

PROJECT_ID=$(gcloud config get-value project)
gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:$SERVICE_ACCOUNT_EMAIL" \
  --role="roles/aiplatform.user"

인스턴스 생성 및 구성에 대한 자세한 내용은 Cloud SQL과 Gemini Enterprise Agent Platform 통합을 참고하세요.

5. 데이터베이스 준비

데이터베이스를 만들고 벡터 지원을 사용 설정합니다.

데이터베이스 만들기

quickstart_db라는 데이터베이스를 만듭니다. 데이터베이스 클라이언트 (예: psql), Google Cloud CLI 또는 Cloud SQL Studio를 사용하여 데이터베이스를 만들 수 있습니다. 이 단계에서는 gcloud를 사용합니다.

Cloud Shell에서 다음 명령어를 실행하여 데이터베이스를 만듭니다.

gcloud sql databases create quickstart_db --instance=my-cloudsql-instance

확장 프로그램 사용 설정

Gemini Enterprise Agent Platform 및 벡터를 사용하려면 quickstart_db 데이터베이스에서 google_ml_integrationvector의 두 확장 프로그램을 사용 설정하세요.

Cloud Shell에서 데이터베이스에 연결합니다.

gcloud sql connect my-cloudsql-instance --database quickstart_db --user=postgres

메시지가 표시되면 데이터베이스 비밀번호를 입력합니다.

SQL 세션에서 다음 명령어를 실행합니다.

CREATE EXTENSION IF NOT EXISTS google_ml_integration CASCADE;
CREATE EXTENSION IF NOT EXISTS vector CASCADE;

SQL 세션을 종료합니다.

exit;

6. 데이터 로드

데이터베이스에 테이블을 만들고 공개 Cloud Storage 버킷에 CSV 형식으로 저장된 가상의 Cymbal Store 데이터 세트 파일을 사용하여 데이터를 로드합니다.

먼저 필요한 스키마 객체를 만듭니다. gcloud sql connectgcloud storage을 실행하여 스키마를 다운로드하고 가져옵니다.

Cloud Shell에서 다음 명령어를 실행합니다. 메시지가 표시되면 인스턴스에 대해 만든 비밀번호를 입력합니다.

gcloud storage cat gs://cloud-training/gcc/gcc-tech-004/cymbal_demo_schema.sql | gcloud sql connect my-cloudsql-instance --database quickstart_db --user=postgres

이 명령어는 데이터베이스에 연결하고 다운로드된 SQL 코드를 실행하여 테이블, 색인, 시퀀스를 만듭니다.

그런 다음 Cloud Storage에서 CSV 데이터 파일을 다운로드합니다.

gcloud storage cp gs://cloud-training/gcc/gcc-tech-004/cymbal_products.csv .
gcloud storage cp gs://cloud-training/gcc/gcc-tech-004/cymbal_inventory.csv .
gcloud storage cp gs://cloud-training/gcc/gcc-tech-004/cymbal_stores.csv .

데이터베이스에 연결합니다.

gcloud sql connect my-cloudsql-instance --database quickstart_db --user=postgres

CSV 파일에서 데이터를 가져옵니다.

\copy cymbal_products from 'cymbal_products.csv' csv header
\copy cymbal_inventory from 'cymbal_inventory.csv' csv header
\copy cymbal_stores from 'cymbal_stores.csv' csv header

자체 데이터를 사용하고 CSV 파일이 Google Cloud 콘솔의 Cloud SQL 가져오기 도구와 호환되는 경우 명령줄 대신 콘솔을 사용할 수 있습니다.

7. 임베딩 만들기

Gemini Enterprise Agent Platform의 text-embedding-005 모델을 사용하여 제품 설명의 임베딩을 빌드하고 벡터 데이터로 저장합니다.

세션 연결이 해제된 경우 데이터베이스에 연결합니다.

gcloud sql connect my-cloudsql-instance --database quickstart_db --user=postgres

embedding 함수를 사용하여 cymbal_products 테이블에 embedding라는 생성된 열을 만듭니다. 이 명령어는 테이블의 모든 행에 대해 product_description 열에서 생성된 벡터 임베딩을 보유하는 저장된 생성된 열을 만듭니다. 모델은 첫 번째 매개변수로, 소스 텍스트 열은 두 번째 매개변수로 지정됩니다.

ALTER TABLE cymbal_products ADD COLUMN embedding vector(768) GENERATED ALWAYS AS (google_ml.embedding('text-embedding-005', product_description)) STORED;

900~1, 000개의 행의 경우 이 프로세스는 일반적으로 1~5분이 소요됩니다.

테이블에 새 행을 삽입하거나 기존 행에서 product_description를 업데이트하면 embedding 열이 자동으로 업데이트됩니다.

8. 유사성 검색 실행

제품 설명에 대해 계산된 벡터 임베딩을 검색어의 임베딩과 비교하여 유사성 검색을 실행합니다.

gcloud sql connect를 사용하여 명령줄에서 또는 Cloud SQL Studio에서 SQL 쿼리를 실행할 수 있습니다. Cloud SQL 스튜디오는 출력이 여러 행인 긴 SQL 문을 더 편리하게 수정하고 실행할 수 있는 방법을 제공합니다.

Cloud SQL Studio 시작

  1. Google Cloud 콘솔에서 Cloud SQL 인스턴스로 이동하여 my-cloudsql-instance를 클릭합니다.

Google Cloud 콘솔의 Cloud SQL 인스턴스 목록

  1. 탐색 메뉴에서 Cloud SQL Studio를 클릭합니다.

Cloud SQL Studio 메뉴 항목

  1. 인증 대화상자에서 데이터베이스 이름과 사용자 인증 정보를 입력합니다.
    • Database: quickstart_db
    • 사용자: postgres
    • 비밀번호:
  2. 인증을 클릭합니다.

Cloud SQL Studio 인증 대화상자

  1. 편집기 탭을 클릭하여 SQL 편집기를 엽니다.

Cloud SQL Studio SQL 편집기 탭

쿼리 실행

'여기에서 잘 자라는 과일 나무는 뭐야?'와 같은 고객 질문과 가장 관련성이 높은 상위 10개 제품을 가져오는 쿼리를 실행합니다.

SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        (cp.embedding <=> embedding('text-embedding-005','What kind of fruit trees grow well here?')::vector) as distance
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        distance ASC
LIMIT 10;

Cloud SQL Studio에서 쿼리를 입력하고 실행을 클릭하거나 psql 세션에서 쿼리를 실행합니다.

Cloud SQL Studio에서 SQL 쿼리 실행

이 쿼리는 코사인 거리로 정렬된 일치하는 제품을 반환합니다.

product_name       |                                   description                                    | sale_price | zip_code |      distance       
-------------------------+----------------------------------------------------------------------------------+------------+----------+---------------------
 Cherry Tree             | This is a beautiful cherry tree that will produce delicious cherries. It is an d |      75.00 |    93230 | 0.43922018972266397
 Meyer Lemon Tree        | Meyer Lemon trees are California's favorite lemon tree! Grow your own lemons by  |         34 |    93230 |  0.4685112926118228
 Toyon                   | This is a beautiful toyon tree that can grow to be over 20 feet tall. It is an e |      10.00 |    93230 |  0.4835677149651668
 California Lilac        | This is a beautiful lilac tree that can grow to be over 10 feet tall. It is an d |       5.00 |    93230 |  0.4947204525907498
 California Peppertree   | This is a beautiful peppertree that can grow to be over 30 feet tall. It is an e |      25.00 |    93230 |  0.5054166905547247
 California Black Walnut | This is a beautiful walnut tree that can grow to be over 80 feet tall. It is a d |     100.00 |    93230 |  0.5084219510932597
 California Sycamore     | This is a beautiful sycamore tree that can grow to be over 100 feet tall. It is  |     300.00 |    93230 |  0.5140519790508755
 Coast Live Oak          | This is a beautiful oak tree that can grow to be over 100 feet tall. It is an ev |     500.00 |    93230 |  0.5143126438081371
 Fremont Cottonwood      | This is a beautiful cottonwood tree that can grow to be over 100 feet tall. It i |     200.00 |    93230 |  0.5174774727252058
 Madrone                 | This is a beautiful madrona tree that can grow to be over 80 feet tall. It is an |      50.00 |    93230 |  0.5227400803389093
(10 rows)

9. 검색된 데이터를 사용하여 LLM 응답 개선

Gemini Enterprise Agent Platform 파운데이션 언어 모델에 대한 프롬프트에서 그라운딩된 컨텍스트로 질문 결과를 전달하여 클라이언트 애플리케이션에 대한 생성형 AI 응답을 개선합니다.

이 경우 방법은 다음과 같습니다.

  1. Cloud SQL의 벡터 검색 결과에서 JSON 페이로드를 생성합니다.
  2. Agent Platform Studio에서 프롬프트를 테스트합니다.
  3. google_ml 통합을 사용하여 SQL에서 직접 엔드 투 엔드 프롬프트를 실행합니다.

JSON 형식으로 출력 생성

결과를 JSON으로 포맷하고 하나의 행을 반환하도록 쿼리를 수정합니다.

WITH trees as (
SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        cp.uniq_id as product_id
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        (cp.embedding <=> embedding('text-embedding-005','What kind of fruit trees grow well here?')::vector) ASC
LIMIT 1)
SELECT json_agg(trees) FROM trees;

예상되는 JSON 출력:

[{"product_name":"Cherry Tree","description":"This is a beautiful cherry tree that will produce delicious cherries. It is an d","sale_price":75.00,"zip_code":93230,"product_id":"d536e9e823296a2eba198e52dd23e712"}]

Agent Platform Studio에서 프롬프트 실행

생성된 JSON을 Agent Platform Studio의 생성형 모델에 대한 프롬프트의 컨텍스트로 제공합니다.

  1. Google Cloud 콘솔에서 Agent Platform Studio를 엽니다.

Agent Platform Studio 탐색

  1. Agent Platform Studio에 다음 프롬프트를 입력합니다.

Agent Platform Studio에 프롬프트 입력

You are a friendly advisor helping to find a product based on the customer's needs.
Based on the client request we have loaded a list of products closely related to search.
The list in JSON format with list of values like {"product_name":"name","description":"some description","sale_price":10,"zip_code": 10234, "product_id": "02056727942aeb714dc9a2313654e1b0"}
Here is the list of products:
<JSON_OUTPUT>
The customer asked "What tree is growing the best here?"
You should give information about the product, price and some supplemental information.
Do not ask any additional questions and assume location based on the zip code provided in the list of products.

을 쿼리의 JSON 응답으로 바꿉니다.

You are a friendly advisor helping to find a product based on the customer's needs.
Based on the client request we have loaded a list of products closely related to search.
The list in JSON format with list of values like {"product_name":"name","description":"some description","sale_price":10,"zip_code": 10234, "product_id": "02056727942aeb714dc9a2313654e1b0"}
Here is the list of products:
[{"product_name":"Cherry Tree","description":"This is a beautiful cherry tree that will produce delicious cherries. It is an d","sale_price":75.00,"zip_code":93230,"product_id":"d536e9e823296a2eba198e52dd23e712"}]
The customer asked "What tree is growing the best here?"
You should give information about the product, price and some supplemental information.
Do not ask any additional questions and assume location based on the zip code provided in the list of products.

Agent Platform Studio의 프롬프트

  1. 프롬프트를 실행합니다.

Agent Platform Studio의 프롬프트 결과

답변에는 나무와 위치에 관한 정보를 기반으로 모델이 외부 소스에서 가져온 가격, 설명, 추가 정보가 포함됩니다.

psql에서 프롬프트 실행

또한 Gemini Enterprise Agent Platform과 함께 Cloud SQL AI 통합을 사용하여 SQL 내에서 직접 생성형 모델의 응답을 받을 수 있습니다. 먼저 모델을 등록합니다.

  1. 필요한 경우 확장 프로그램을 버전 1.4.3 이상으로 업그레이드합니다. quickstart_db에 연결하고 다음을 실행합니다.
SELECT extversion from pg_extension where extname='google_ml_integration';

반환된 버전이 1.4.3보다 낮은 경우 다음을 실행합니다.

ALTER EXTENSION google_ml_integration UPDATE TO '1.4.3';
  1. google_ml_integration.enable_model_support 데이터베이스 플래그를 확인합니다.
SHOW google_ml_integration.enable_model_support;

플래그가 off인 경우 Cloud Shell에서 데이터베이스 플래그를 업데이트합니다.

gcloud sql instances patch my-cloudsql-instance \
--database-flags google_ml_integration.enable_model_support=on,cloudsql.enable_google_ml_integration=on

이 작업은 1~3분이 걸립니다. 설정을 다시 확인합니다.

SHOW google_ml_integration.enable_model_support;
  1. 대답을 생성하도록 gemini-3.5-flash 모델을 등록합니다 (를 프로젝트 ID로 바꿈).
CALL
  google_ml.create_model(
    model_id => 'gemini-3.5-flash',
    model_request_url => 'https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/publishers/google/models/gemini-3.6-flash:generateContent',
    model_provider => 'google',
    model_auth_type => 'cloudsql_service_agent_iam');

등록된 모델을 확인합니다.

SELECT model_id, model_type FROM google_ml.model_info_view WHERE model_id='gemini-3.5-flash';
  1. 전체 SQL 쿼리를 실행하여 벡터 검색 결과를 가져오고 이를 gemini-3.5-flash에 직접 전달합니다.
WITH trees AS (
SELECT
        cp.product_name,
        cp.product_description AS description,
        cp.sale_price,
        cs.zip_code,
        cp.uniq_id AS product_id
FROM
        cymbal_products cp
JOIN cymbal_inventory ci ON
        ci.uniq_id = cp.uniq_id
JOIN cymbal_stores cs ON
        cs.store_id = ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        (cp.embedding <=> embedding('text-embedding-005',
        'What kind of fruit trees grow well here?')::vector) ASC
LIMIT 1),
prompt AS (
SELECT
        'You are a friendly advisor helping to find a product based on the customer''s needs.
Based on the client request we have loaded a list of products closely related to search.
The list in JSON format with list of values like {"product_name":"name","product_description":"some description","sale_price":10}
Here is the list of products:' || json_agg(trees) || 'The customer asked "What kind of fruit trees grow well here?"
You should give information about the product, price and some supplemental information' AS prompt_text
FROM
        trees),
response AS (
SELECT
        google_ml.predict_row( model_id =>'gemini-3.5-flash',
        request_body => json_build_object('contents',
        json_build_object('role',
        'user',
        'parts',
        json_build_object('text',
        prompt_text))))->'candidates'->0->'content'->'parts'->0->'text' AS resp
FROM
        prompt)
SELECT
REPLACE(resp::text, '\n', CHR(10))
FROM
        response;

예상 출력:

"Hello there! If you're looking for a wonderful fruit tree to plant, I have a fantastic option for you: ### **Cherry Tree** * **Price:** $75.00 * **Product ID:** `d536e9e823296a2eba198e52dd23e712` --- ### **Why it's a great choice:** * **Fruit & Shade:** Not only will it produce delicious, sweet cherries, but it also grows into a beautiful 15-foot deciduous tree that provides excellent shade and privacy for your yard. * **Seasonal Beauty:** Its leaves are a lovely dark green throughout the summer and transition into a striking red during the fall. * **Ideal Growing Conditions:** Cherry trees thrive best in cool, moist climates with sandy soil and are suitable for **USDA hardiness zones 4–9**. If your local climate matches these conditions, this Cherry Tree would make a beautiful and tasty addition to your garden! Let me know if you'd like more details or help placing an order."

10. 최근접 이웃 색인 만들기

수백만 개의 벡터가 포함된 대규모 데이터 세트의 경우 벡터 검색에 상당한 컴퓨팅 리소스가 필요할 수 있습니다. 쿼리 성능을 개선하려면 벡터 임베딩에 색인을 만드세요.

HNSW 색인 만들기

HNSW (Hierarchical Navigable Small World)는 그래프 기반 벡터 색인입니다.

embedding 열에 HNSW 색인을 빌드하려면 거리 함수(vector_cosine_ops)와 선택적 매개변수(예: mef_construction)를 지정합니다. 자세한 내용은 벡터 임베딩 사용을 참고하세요.

CREATE INDEX cymbal_products_embeddings_hnsw ON cymbal_products
  USING hnsw (embedding vector_cosine_ops)
  WITH (m = 16, ef_construction = 64);

예상 출력:

quickstart_db=> CREATE INDEX cymbal_products_embeddings_hnsw ON cymbal_products
  USING hnsw (embedding vector_cosine_ops)
  WITH (m = 16, ef_construction = 64);
CREATE INDEX
quickstart_db=>

쿼리 성능 비교

EXPLAIN (ANALYZE)를 사용하여 벡터 검색 쿼리를 실행하여 쿼리 플래너가 색인을 사용하는지 확인합니다.

EXPLAIN (ANALYZE) 
WITH trees as (
SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        cp.uniq_id as product_id
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        (cp.embedding <=> embedding('text-embedding-005','What kind of fruit trees grow well here?')::vector) ASC
LIMIT 1)
SELECT json_agg(trees) FROM trees;

예상 출력:

 Aggregate  (cost=779.12..779.13 rows=1 width=32) (actual time=1.066..1.069 rows=1 loops=1)
   ->  Subquery Scan on trees  (cost=769.05..779.12 rows=1 width=142) (actual time=1.038..1.041 rows=1 loops=1)
         ->  Limit  (cost=769.05..779.11 rows=1 width=158) (actual time=1.022..1.024 rows=1 loops=1)
               ->  Nested Loop  (cost=769.05..9339.69 rows=852 width=158) (actual time=1.020..1.021 rows=1 loops=1)
                     ->  Nested Loop  (cost=768.77..9316.48 rows=852 width=945) (actual time=0.858..0.859 rows=1 loops=1)
                           ->  Index Scan using cymbal_products_embeddings_hnsw on cymbal_products cp  (cost=768.34..2572.47 rows=941 width=941) (actual time=0.532..0.539 rows=3 loops=1)
...
 Planning Time: 112.398 ms
 Execution Time: 1.221 ms

실행 계획에 Index Scan using cymbal_products_embeddings_hnsw이 표시됩니다.

EXPLAIN 없이 쿼리를 실행합니다.

WITH trees as (
SELECT
        cp.product_name,
        left(cp.product_description,80) as description,
        cp.sale_price,
        cs.zip_code,
        cp.uniq_id as product_id
FROM
        cymbal_products cp
JOIN cymbal_inventory ci on
        ci.uniq_id=cp.uniq_id
JOIN cymbal_stores cs on
        cs.store_id=ci.store_id
        AND ci.inventory>0
        AND cs.store_id = 1583
ORDER BY
        (cp.embedding <=> embedding('text-embedding-005','What kind of fruit trees grow well here?')::vector) ASC
LIMIT 1)
SELECT json_agg(trees) FROM trees;

예상 출력:

[{"product_name":"Cherry Tree","description":"This is a beautiful cherry tree that will produce delicious cherries. It is an d","sale_price":75.00,"zip_code":93230,"product_id":"d536e9e823296a2eba198e52dd23e712"}]

LangChain 및 벡터 색인을 사용한 자세한 내용과 예시는 Cloud SQL AI 개요 문서를 참고하세요.

11. 리소스 삭제

코드랩을 완료한 후 Cloud SQL 인스턴스를 삭제합니다.

세션 연결이 끊어진 경우 Cloud Shell에서 프로젝트와 환경 변수를 설정합니다.

export INSTANCE_NAME=my-cloudsql-instance
export PROJECT_ID=$(gcloud config get-value project)

인스턴스를 삭제합니다.

gcloud sql instances delete $INSTANCE_NAME --project=$PROJECT_ID

예상 출력:

student@cloudshell:~$ gcloud sql instances delete $INSTANCE_NAME --project=$PROJECT_ID
All of the instance data will be lost when the instance is deleted.

Do you want to continue (Y/n)?  y

Deleting Cloud SQL instance...done.                                                                                                                
Deleted [https://sandbox.googleapis.com/v1beta4/projects/test-project-001-402417/instances/my-cloudsql-instance].

12. 축하합니다

수고하셨습니다 Codelab을 완료했습니다.

이 실습은 Google Cloud를 사용한 프로덕션 레디 AI 학습 과정의 일부입니다.

  • 전체 교육과정을 살펴보고 프로토타입에서 프로덕션으로 전환하세요.
  • #ProductionReadyAI 해시태그를 사용하여 진행 상황을 공유하세요.

요약

지금까지 배운 내용은 다음과 같습니다.

  • PostgreSQL용 Cloud SQL 인스턴스 배포
  • 데이터베이스를 만들고 Cloud SQL AI 통합 사용 설정
  • 데이터베이스에 데이터 로드
  • Cloud SQL Studio 사용
  • Cloud SQL에서 Gemini Enterprise Agent Platform 임베딩 모델 사용
  • Agent Platform Studio 사용
  • Gemini Enterprise Agent Platform 생성형 모델을 사용하여 쿼리 결과 보강
  • 벡터 색인을 사용하여 쿼리 성능 개선

HNSW 대신 ScaNN 색인을 사용하여 AlloyDB AI 벡터 임베딩 Codelab을 사용해 보세요.