AlloyDB Omni에서 벡터 검색 실행

문서 버전을 선택합니다.

이 튜토리얼에서는 AlloyDB Omni에서 벡터 검색을 설정하고 수행하는 방법을 설명합니다. 정확한 최근접 이웃 검색 (KNN) 및 근사 최근접 이웃 (ANN) 기반 ScaNN 색인을 사용하여 쿼리를 실행합니다. 또한 ScaNN 색인을 사용하여 필터링된 벡터 검색어를 효율적으로 실행하는 방법도 알아봅니다.

목표

  • AlloyDB Omni에 AlloyDB AI를 설치합니다.
  • 데이터베이스에 연결하고 필요한 확장 프로그램을 설치합니다.
  • productproduct inventory 테이블을 만듭니다.
  • productproduct inventory 테이블에 데이터를 삽입하고 기본 벡터 검색을 수행합니다.
  • 제품 테이블에 ScaNN 색인을 만듭니다.
  • 벡터 검색을 실행합니다.
  • 필터와 조인을 사용하여 복잡한 벡터 검색을 수행합니다.

비용

이 문서에서는 비용이 청구될 수 있는 Google Cloud구성요소를 사용합니다.

프로젝트 사용량을 기준으로 예상 비용을 산출하려면 가격 계산기를 사용합니다.

이 문서에 설명된 작업을 완료하면 만든 리소스를 삭제하여 비용이 계속 청구되지 않도록 할 수 있습니다. 자세한 내용은 삭제를 참조하세요.

기본 요건

벡터 검색을 실행하기 전에 다음 기본 요건을 완료하세요.

컴퓨팅 환경에 따라 AlloyDB Omni에 AlloyDB AI 설치

사용 중인 컴퓨팅 환경에 따라 AlloyDB Omni에 AlloyDB AI 설치의 안내를 완료하여 AlloyDB Omni를 설치합니다.

psql을 사용하여 데이터베이스에 연결

psql을 사용하여 데이터베이스에 연결합니다.

    export DBPOD=`kubectl get pod --selector=alloydbomni.internal.dbadmin.goog/dbcluster=my-db-cluster,alloydbomni.internal.dbadmin.goog/task-type=database -o jsonpath='{.items[0].metadata.name}'`
    kubectl exec -ti $DBPOD -c database -- psql -h localhost -U postgres

필수 확장 프로그램 설치

다음 쿼리를 실행하여 vector, alloydb_scann, google_ml_integration 확장 프로그램을 설치합니다.

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

이 문서에 설명된 태스크를 완료했으면 만든 리소스를 삭제하여 청구가 계속되는 것을 방지할 수 있습니다. 자세한 내용은 삭제를 참고하세요.

제품 및 제품 인벤토리 데이터 삽입 및 기본 벡터 검색 수행

이 튜토리얼에서는 product_inventoryproduct 테이블을 사용하여 복잡한 벡터 검색어를 실행합니다.

  1. 다음 문을 실행하여 다음 작업을 수행하는 product 테이블을 만듭니다.

    • 기본 제품 정보를 저장합니다.
    • 각 제품의 제품 설명에 대한 임베딩 벡터를 계산하고 저장하는 embedding 벡터 열이 포함됩니다.
      CREATE TABLE product (
        id INT PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        description TEXT,
        category VARCHAR(255),
        color VARCHAR(255),
        embedding vector(768) GENERATED ALWAYS AS (embedding('text-embedding-004', description)) STORED
      );
    
  2. 다음 쿼리를 실행하여 사용 가능한 인벤토리와 해당 가격에 대한 정보를 저장하는 product_inventory 테이블을 만듭니다.

    CREATE TABLE product_inventory (
      id INT PRIMARY KEY,
      product_id INT REFERENCES product(id),
      inventory INT,
      price DECIMAL(10,2)
    );
    
  3. 다음 쿼리를 실행하여 product 테이블에 제품 데이터를 삽입합니다.

    INSERT INTO product (id, name, description,category, color) VALUES
    (1, 'Stuffed Elephant', 'Soft plush elephant with floppy ears.', 'Plush Toys', 'Gray'),
    (2, 'Remote Control Airplane', 'Easy-to-fly remote control airplane.', 'Vehicles', 'Red'),
    (3, 'Wooden Train Set', 'Classic wooden train set with tracks and trains.', 'Vehicles', 'Multicolor'),
    (4, 'Kids Tool Set', 'Toy tool set with realistic tools.', 'Pretend Play', 'Multicolor'),
    (5, 'Play Food Set', 'Set of realistic play food items.', 'Pretend Play', 'Multicolor'),
    (6, 'Magnetic Tiles', 'Set of colorful magnetic tiles for building.', 'Construction Toys', 'Multicolor'),
    (7, 'Kids Microscope', 'Microscope for kids with different magnification levels.', 'Educational Toys', 'White'),
    (8, 'Telescope for Kids', 'Telescope designed for kids to explore the night sky.', 'Educational Toys', 'Blue'),
    (9, 'Coding Robot', 'Robot that teaches kids basic coding concepts.', 'Educational Toys', 'White'),
    (10, 'Kids Camera', 'Durable camera for kids to take pictures and videos.', 'Electronics', 'Pink'),
    (11, 'Walkie Talkies', 'Set of walkie talkies for kids to communicate.', 'Electronics', 'Blue'),
    (12, 'Karaoke Machine', 'Karaoke machine with built-in microphone and speaker.', 'Electronics', 'Black'),
    (13, 'Kids Drum Set', 'Drum set designed for kids with adjustable height.', 'Musical Instruments', 'Blue'),
    (14, 'Kids Guitar', 'Acoustic guitar for kids with nylon strings.', 'Musical Instruments', 'Brown'),
    (15, 'Kids Keyboard', 'Electronic keyboard with different instrument sounds.', 'Musical Instruments', 'Black'),
    (16, 'Art Easel', 'Double-sided art easel with chalkboard and whiteboard.', 'Arts & Crafts', 'White'),
    (17, 'Finger Paints', 'Set of non-toxic finger paints for kids.', 'Arts & Crafts', 'Multicolor'),
    (18, 'Modeling Clay', 'Set of colorful modeling clay.', 'Arts & Crafts', 'Multicolor'),
    (19, 'Watercolor Paint Set', 'Watercolor paint set with brushes and palette.', 'Arts & Crafts', 'Multicolor'),
    (20, 'Beading Kit', 'Kit for making bracelets and necklaces with beads.', 'Arts & Crafts', 'Multicolor'),
    (21, '3D Puzzle', '3D puzzle of a famous landmark.', 'Puzzles', 'Multicolor'),
    (22, 'Race Car Track Set', 'Race car track set with cars and accessories.', 'Vehicles', 'Multicolor'),
    (23, 'RC Monster Truck', 'Remote control monster truck with oversized tires.', 'Vehicles', 'Green'),
    (24, 'Train Track Expansion Set', 'Expansion set for wooden train tracks.', 'Vehicles', 'Multicolor');
    
  4. 선택사항: 데이터가 product 테이블에 삽입되었는지 확인하려면 다음 쿼리를 실행합니다.

    SELECT * FROM product;
    
  5. 다음 쿼리를 실행하여 product_inventory 테이블에 인벤토리 데이터를 삽입합니다.

    INSERT INTO product_inventory (id, product_id, inventory, price) VALUES
    (1, 1, 9, 13.09),
    (2, 2, 40, 79.82),
    (3, 3, 34, 52.49),
    (4, 4, 9, 12.03),
    (5, 5, 36, 71.29),
    (6, 6, 10, 51.49),
    (7, 7, 7, 37.35),
    (8, 8, 6, 10.87),
    (9, 9, 7, 42.47),
    (10, 10, 3, 24.35),
    (11, 11, 4, 10.20),
    (12, 12, 47, 74.57),
    (13, 13, 5, 28.54),
    (14, 14, 11, 25.58),
    (15, 15, 21, 69.84),
    (16, 16, 6, 47.73),
    (17, 17, 26, 81.00),
    (18, 18, 11, 91.60),
    (19, 19, 8, 78.53),
    (20, 20, 43, 84.33),
    (21, 21, 46, 90.01),
    (22, 22, 6, 49.82),
    (23, 23, 37, 50.20),
    (24, 24, 27, 99.27);
    
  6. 다음 벡터 검색어를 실행하여 music 단어와 유사한 제품을 검색합니다. 제품 설명에 music 단어가 명시적으로 언급되지 않더라도 쿼리와 관련된 제품이 결과에 표시됩니다.

    SELECT * FROM product
    ORDER BY embedding <=> embedding('text-embedding-005', 'music')::vector
    LIMIT 3;
    

    색인을 만들지 않고 기본 벡터 검색을 수행하면 AlloyDB AI는 효율적인 재현율을 제공하는 KNN을 사용합니다. 하지만 대규모로 KNN을 사용하면 성능이 영향을 받을 수 있습니다. 더 나은 쿼리 성능을 위해 ANN 검색에 높은 재현율과 짧은 지연 시간을 제공하는 ScaNN 색인을 사용하는 것이 좋습니다.

    색인을 만들지 않으면 AlloyDB Omni는 기본적으로 KNN을 사용합니다.

제품 테이블에 ScaNN 색인 만들기

다음 쿼리를 실행하여 product 테이블에 product_index ScaNN 색인을 만듭니다.

  CREATE INDEX product_index ON product
  USING scann (embedding cosine)
  WITH (num_leaves=5);

num_leaves 파라미터는 트리 기반 색인에서 색인을 빌드하는 리프 노드 수를 나타냅니다. 이 파라미터를 조정하는 방법에 대한 자세한 내용은 벡터 쿼리 성능 조정을 참고하세요.

자연어 쿼리 music과 유사한 제품을 찾으려고 시도하는 다음 벡터 검색어를 실행합니다. 제품 설명에 music 단어가 포함되어 있지 않더라도 결과에는 쿼리와 관련된 제품이 표시됩니다.

SET LOCAL scann.num_leaves_to_search = 2;

SELECT * FROM product
ORDER BY embedding <=> embedding('text-embedding-005', 'music')::vector
  LIMIT 3;

scann.num_leaves_to_search 쿼리 파라미터는 유사성 검색 중에 검색되는 리프 노드 수를 제어합니다. num_leavesscann.num_leaves_to_search 파라미터 값은 쿼리 성능과 재현율의 균형을 맞추는 데 도움이 됩니다.

다음과 같은 복잡한 벡터 검색어를 실행합니다. 이 검색어는 필터가 있더라도 쿼리 조건을 충족하는 관련 결과를 반환합니다.

SET LOCAL scann.num_leaves_to_search = 2;

SELECT * FROM product p
JOIN product_inventory pi ON p.id = pi.product_id
WHERE pi.price < 80.00
ORDER BY embedding <=> embedding('text-embedding-005', 'music')::vector
LIMIT 3;

삭제

데이터베이스 클러스터 삭제

      kubectl patch dbclusters.alloydbomni.dbadmin.goog my-db-cluster -p '{"spec":{"isDeleted":true}}' --type=merge

AlloyDB Omni 오퍼레이터 제거

Kubernetes 클러스터에서 AlloyDB Omni Kubernetes 연산자를 제거하려면 다음 단계를 완료하세요.

  1. 모든 데이터베이스 클러스터를 삭제합니다.

          for ns in $(kubectl get dbclusters.alloydbomni.dbadmin.goog --all-namespaces -o=jsonpath='{range .items[*]}{.metadata.namespace}{"\n"}{end}'); do
          for cr in $(kubectl get dbclusters.alloydbomni.dbadmin.goog -n $ns -o=jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}'); do
          kubectl patch dbclusters.alloydbomni.dbadmin.goog $cr -n $ns --type=merge -p '{"spec":{"isDeleted":true}}'
          done
          done
      ```
  2. 다음 명령어를 실행하여 AlloyDB Omni Kubernetes 연산자가 모든 데이터베이스 클러스터를 삭제했는지 확인합니다.

        kubectl get dbclusters.alloydbomni.dbadmin.goog --all-namespaces
  3. AlloyDB Omni Kubernetes 오퍼레이터가 만든 다른 리소스를 삭제합니다.

        kubectl delete failovers.alloydbomni.dbadmin.goog --all --all-namespaces
        kubectl delete restores.alloydbomni.dbadmin.goog --all --all-namespaces
        kubectl delete switchovers.alloydbomni.dbadmin.goog --all --all-namespaces
  4. AlloyDB Omni Kubernetes 오퍼레이터를 제거합니다.

        helm uninstall alloydbomni-operator --namespace alloydb-omni-system
  5. AlloyDB Omni Kubernetes 오퍼레이터와 관련된 보안 비밀, 커스텀 리소스 설명, 네임스페이스를 정리합니다.

        kubectl delete certificate -n alloydb-omni-system --all
        kubectl get secrets --all-namespaces -o custom-columns=NAMESPACE:.metadata.namespace,NAME:.metadata.name,ANNOTATION:.metadata.annotations.cert-manager\.io/issuer-name | grep -E 'alloydbomni|dbs-al' | awk '{print $1 " " $2}' | xargs -n 2 kubectl delete secret -n
        kubectl delete crd -l alloydb-omni=true
        kubectl delete ns alloydb-omni-system

다음 단계