AI.GENERATE_EMBEDDING 함수를 사용하여 텍스트 임베딩 생성

AI.GENERATE_EMBEDDING 함수를 사용하면 BigQuery 테이블의 텍스트를 시맨틱 의미를 포착하는 숫자 벡터(임베딩)로 변환할 수 있습니다. 이러한 임베딩을 사용하면 데이터를 내보내지 않고도 SQL에서 직접 시맨틱 검색, 추천, 분류, 클러스터링 워크플로를 지원할 수 있습니다.

이 튜토리얼에서는 호스팅된 Gemini Enterprise Agent Platform 텍스트 임베딩 모델을 통해 BigQuery ML 원격 모델을 만들고, 공개 뉴스 기사를 임베딩하고, 시맨틱 유사성을 기준으로 샘플 영화 리뷰의 순위를 매깁니다. 원격 모델을 만들지 않고 쿼리에 개별 값을 삽입하려면 스칼라 AI.EMBED 함수를 대신 사용합니다. 자체 배포된 오픈소스 모델로 임베딩을 생성하려면 개방형 모델을 사용하여 텍스트 임베딩 생성을 참조하세요.

목표

  • BigQuery 데이터 세트와 Cloud 리소스 연결을 만듭니다.
  • 연결의 서비스 계정에 권한 부여하기
  • gemini-embedding-001 임베딩 모델을 통해 BigQuery ML 원격 모델을 만듭니다.
  • AI.GENERATE_EMBEDDING 함수를 사용하여 공개 데이터 세트에서 문서 임베딩을 생성합니다.
  • VECTOR_SEARCH 함수를 사용하여 의미론적 유사성에 따라 텍스트 순위를 지정합니다.

비용

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

  • BigQuery ML: You incur costs for the data that you process in BigQuery.
  • Agent Platform: You incur costs for calls to the Agent Platform model that's represented by the remote model.

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

Google Cloud 신규 사용자는 무료 체험판을 사용할 수 있습니다.

자세한 내용은 BigQuery 가격 책정 및 에이전트 플랫폼 가격 책정을 참조하세요.

시작하기 전에

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.

  4. Verify that billing is enabled for your Google Cloud project.

  5. Enable the BigQuery, BigQuery Connection, and Agent Platform API APIs, if any are not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the APIs

  6. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  7. If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.

  8. Verify that billing is enabled for your Google Cloud project.

  9. Enable the BigQuery, BigQuery Connection, and Agent Platform API APIs, if any are not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the APIs

필요한 역할

이 튜토리얼을 완료하는 데 필요한 권한을 얻으려면 관리자에게 다음의 IAM 역할을 부여해 달라고 요청하세요.

  • BigQuery 데이터 세트, 테이블, 모델 만들기 및 사용: 프로젝트에 대한 BigQuery 데이터 편집자(roles/bigquery.dataEditor)
  • BigQuery 연결을 만들고, 위임하고, 사용하기: 프로젝트에 대한 BigQuery 연결 관리자(roles/bigquery.connectionAdmin)
  • 연결의 서비스 계정에 권한 부여: 프로젝트에 대한 프로젝트 IAM 관리자(roles/resourcemanager.projectIamAdmin)
  • BigQuery 작업 만들기: 프로젝트에 대한 BigQuery 작업 사용자(roles/bigquery.jobUser)

역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.

이러한 사전 정의된 역할에는 이 튜토리얼을 완료하는 데 필요한 권한이 포함되어 있습니다. 필요한 정확한 권한을 보려면 필수 권한 섹션을 펼치세요.

필수 권한

이 튜토리얼을 완료하려면 다음 권한이 필요합니다.

  • 데이터 세트 만들기: bigquery.datasets.create
  • 연결을 만들고, 위임하고, 사용하기: bigquery.connections.*
  • 서비스 계정 권한 설정:
    • resourcemanager.projects.getIamPolicy
    • resourcemanager.projects.setIamPolicy
  • 모델을 만들고 추론을 실행하기:
    • bigquery.jobs.create
    • bigquery.models.create
    • bigquery.models.getData
    • bigquery.models.updateData
    • bigquery.models.updateMetadata
  • 테이블 데이터 쿼리: bigquery.tables.getData

커스텀 역할이나 다른 사전 정의된 역할을 사용하여 이 권한을 부여받을 수도 있습니다.

데이터 세트 만들기

BigQuery 데이터 세트를 만들려면 다음 옵션 중 하나를 선택합니다.

콘솔

  1. Google Cloud 콘솔에서 BigQuery 페이지로 이동합니다.

    BigQuery로 이동

  2. 왼쪽 창에서 탐색기를 클릭합니다.

    강조 표시된 탐색기 창 버튼

    왼쪽 창이 표시되지 않으면 왼쪽 창 펼치기를 클릭하여 창을 엽니다.

  3. 탐색기에서 프로젝트를 펼친 다음 데이터 세트를 클릭합니다.

  4. 데이터 세트 페이지에서 데이터 세트 만들기를 클릭합니다.

  5. 데이터 세트 만들기 창에서 다음을 수행합니다.

    • 데이터 세트 ID에 bqml_tutorial를 입력합니다.

    • 데이터 위치로 미국을 선택합니다.

    나머지 기본 설정은 그대로 둡니다.

  6. 데이터 세트 만들기를 클릭합니다.

bq

새 데이터 세트를 만들려면 bq mk --dataset 명령어를 사용합니다.

  1. 데이터 위치가 US로 설정된 bqml_tutorial 데이터 세트를 만듭니다.

    bq mk --dataset \
      --location=US \
      --description "BigQuery ML tutorial dataset." \
      bqml_tutorial
  2. 데이터 세트가 생성되었는지 확인합니다.

    bq ls

API

데이터 세트 리소스가 정의된 datasets.insert 메서드를 호출합니다.

{
  "datasetReference": {
     "datasetId": "bqml_tutorial"
  }
}

연결 만들기

데이터 세트를 만든 US 멀티 리전에서 Cloud 리소스 연결을 만든 후 연결의 서비스 계정을 가져옵니다. 기본 연결이 이미 구성되어 있거나 BigQuery 관리자(roles/bigquery.admin) 역할이 있는 경우 연결 만들기를 건너뛰고 CREATE MODEL 문에 DEFAULT를 지정할 수 있습니다.

다음 옵션 중 하나를 선택합니다.

콘솔

  1. BigQuery 페이지로 이동합니다.

    BigQuery로 이동

  2. 왼쪽 창에서 탐색기를 클릭합니다.

    강조 표시된 탐색기 창 버튼

    왼쪽 창이 표시되지 않으면 왼쪽 창 펼치기를 클릭하여 창을 엽니다.

  3. 탐색기 창에서 프로젝트 이름을 펼친 후 연결을 클릭합니다.

  4. 연결 페이지에서 연결 만들기를 클릭합니다.

  5. 연결 유형으로 Vertex AI 원격 모델, 원격 함수, BigLake, Spanner(Cloud 리소스)를 선택합니다.

  6. 연결 ID 필드에 연결 이름을 입력합니다.

  7. 위치 유형에서 연결 위치를 선택합니다. 연결은 데이터 세트와 같이 다른 리소스와 함께 배치해야 합니다.

  8. 연결 만들기를 클릭합니다.

  9. 연결로 이동을 클릭합니다.

  10. 연결 정보 창에서 이후 단계에 사용할 서비스 계정 ID를 복사합니다.

SQL

CREATE CONNECTION 문을 사용합니다.

  1. Google Cloud 콘솔에서 BigQuery 페이지로 이동합니다.

    BigQuery로 이동

  2. 쿼리 편집기에서 다음 문을 입력합니다.

    CREATE CONNECTION [IF NOT EXISTS] `CONNECTION_NAME`
    OPTIONS (
      connection_type = "CLOUD_RESOURCE",
      friendly_name = "FRIENDLY_NAME",
      description = "DESCRIPTION"
      );

    다음을 바꿉니다.

    • CONNECTION_NAME: PROJECT_ID.LOCATION.CONNECTION_ID, LOCATION.CONNECTION_ID 또는 CONNECTION_ID 형식의 연결 이름입니다. 프로젝트 또는 위치를 생략하면 문이 실행되는 프로젝트 및 위치에서 추론됩니다.
    • FRIENDLY_NAME(선택사항): 연결을 설명하는 이름입니다.
    • DESCRIPTION(선택사항): 연결에 대한 설명입니다.

  3. 실행을 클릭합니다.

쿼리를 실행하는 방법에 대한 자세한 내용은 대화형 쿼리 실행을 참조하세요.

bq

  1. 명령줄 환경에서 연결을 만듭니다.

    bq mk --connection --location=REGION --project_id=PROJECT_ID \
        --connection_type=CLOUD_RESOURCE CONNECTION_ID

    --project_id 매개변수는 기본 프로젝트를 재정의합니다.

    다음을 바꿉니다.

    • REGION: 연결 리전
    • PROJECT_ID: Google Cloud 프로젝트 ID
    • CONNECTION_ID: 연결의 ID

    연결 리소스를 만들면 BigQuery가 고유한 시스템 서비스 계정을 만들고 이를 연결에 연계합니다.

    문제 해결: 다음 연결 오류가 발생하면 Google Cloud SDK를 업데이트하세요.

    Flags parsing error: flag --connection_type=CLOUD_RESOURCE: value should be one of...
    
  2. 이후 단계에서 사용할 수 있도록 서비스 계정 ID를 가져와 복사합니다.

    bq show --connection PROJECT_ID.REGION.CONNECTION_ID

    출력은 다음과 비슷합니다.

    name                          properties
    1234.REGION.CONNECTION_ID     {"serviceAccountId": "connection-1234-9u56h9@gcp-sa-bigquery-condel.iam.gserviceaccount.com"}
    

Python

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용의 Python 설정 안내를 따르세요. 자세한 내용은 Vertex AI Python API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

import google.api_core.exceptions
from google.cloud import bigquery_connection_v1

client = bigquery_connection_v1.ConnectionServiceClient()


def create_connection(
    project_id: str,
    location: str,
    connection_id: str,
):
    """Creates a BigQuery connection to a Cloud Resource.

    Cloud Resource connection creates a service account which can then be
    granted access to other Google Cloud resources for federated queries.

    Args:
        project_id: The Google Cloud project ID.
        location: The location of the connection (for example, "us-central1").
        connection_id: The ID of the connection to create.
    """

    parent = client.common_location_path(project_id, location)

    connection = bigquery_connection_v1.Connection(
        friendly_name="Example Connection",
        description="A sample connection for a Cloud Resource.",
        cloud_resource=bigquery_connection_v1.CloudResourceProperties(),
    )

    try:
        created_connection = client.create_connection(
            parent=parent, connection_id=connection_id, connection=connection
        )
        print(f"Successfully created connection: {created_connection.name}")
        print(f"Friendly name: {created_connection.friendly_name}")
        print(
            f"Service Account: {created_connection.cloud_resource.service_account_id}"
        )

    except google.api_core.exceptions.AlreadyExists:
        print(f"Connection with ID '{connection_id}' already exists.")
        print("Please use a different connection ID.")
    except Exception as e:
        print(f"An unexpected error occurred while creating the connection: {e}")

Node.js

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용의 Node.js 설정 안내를 따르세요. 자세한 내용은 Vertex AI Node.js API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

const {ConnectionServiceClient} =
  require('@google-cloud/bigquery-connection').v1;
const {status} = require('@grpc/grpc-js');

const client = new ConnectionServiceClient();

/**
 * Creates a new BigQuery connection to a Cloud Resource.
 *
 * A Cloud Resource connection creates a service account that can be granted access
 * to other Google Cloud resources.
 *
 * @param {string} projectId The Google Cloud project ID. for example, 'example-project-id'
 * @param {string} location The location of the project to create the connection in. for example, 'us-central1'
 * @param {string} connectionId The ID of the connection to create. for example, 'example-connection-id'
 */
async function createConnection(projectId, location, connectionId) {
  const parent = client.locationPath(projectId, location);

  const connection = {
    friendlyName: 'Example Connection',
    description: 'A sample connection for a Cloud Resource',
    // The service account for this cloudResource will be created by the API.
    // Its ID will be available in the response.
    cloudResource: {},
  };

  const request = {
    parent,
    connectionId,
    connection,
  };

  try {
    const [response] = await client.createConnection(request);

    console.log(`Successfully created connection: ${response.name}`);
    console.log(`Friendly name: ${response.friendlyName}`);

    console.log(`Service Account: ${response.cloudResource.serviceAccountId}`);
  } catch (err) {
    if (err.code === status.ALREADY_EXISTS) {
      console.log(`Connection '${connectionId}' already exists.`);
    } else {
      console.error(`Error creating connection: ${err.message}`);
    }
  }
}

자바

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용의 Java 설정 안내를 따르세요. 자세한 내용은 Vertex AI Java API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

import com.google.api.gax.rpc.AlreadyExistsException;
import com.google.api.gax.rpc.ApiException;
import com.google.cloud.bigquery.connection.v1.CloudResourceProperties;
import com.google.cloud.bigquery.connection.v1.Connection;
import com.google.cloud.bigquery.connection.v1.CreateConnectionRequest;
import com.google.cloud.bigquery.connection.v1.LocationName;
import com.google.cloud.bigqueryconnection.v1.ConnectionServiceClient;
import java.io.IOException;

public class CreateConnection {

  /**
   * Creates a BigQuery connection to a Cloud Resource. A Cloud Resource connection provisions a
   * service account that can be granted access to other Google Cloud resources for federated
   * queries.
   *
   * @param projectId The Google Cloud project ID (for example, "example-project-id").
   * @param location The geographic location of the connection (for example, "us-central1").
   * @param connectionId The ID of the connection to create (for example, "example-connection-id").
   */
  public static void createConnection(String projectId, String location, String connectionId) {
    LocationName parent = LocationName.of(projectId, location);

    // CloudResourceProperties provisions a managed Google Cloud service account on creation.
    CloudResourceProperties cloudResourceProperties = CloudResourceProperties.newBuilder().build();
    Connection connection =
        Connection.newBuilder()
            .setFriendlyName("Example Connection")
            .setDescription("Cloud Resource connection for federated queries.")
            .setCloudResource(cloudResourceProperties)
            .build();

    CreateConnectionRequest request =
        CreateConnectionRequest.newBuilder()
            .setParent(parent.toString())
            .setConnectionId(connectionId)
            .setConnection(connection)
            .build();

    try (ConnectionServiceClient client = ConnectionServiceClient.create()) {
      Connection response = client.createConnection(request);

      System.out.printf("Successfully created connection: %s%n", response.getName());
      System.out.printf("Friendly name: %s%n", response.getFriendlyName());
      System.out.printf(
          "Service Account: %s%n", response.getCloudResource().getServiceAccountId());
    } catch (AlreadyExistsException err) {
      System.err.printf(
          "error: connection '%s' already exists in location '%s' for project '%s': %s%n",
          connectionId, location, projectId, err.getMessage());
    } catch (ApiException | IOException err) {
      System.err.printf(
          "error: failed to create connection '%s' in location '%s' for project '%s': %s%n",
          connectionId, location, projectId, err.getMessage());
    }
  }

Terraform

google_bigquery_connection 리소스를 사용합니다.

BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 클라이언트 라이브러리의 인증 설정을 참조하세요.

다음 예시에서는 US 리전에 my_cloud_resource_connection이라는 Cloud 리소스 연결을 만듭니다.


# This queries the provider for project information.
data "google_project" "default" {}

# This creates a cloud resource connection in the US region named my_cloud_resource_connection.
# Note: The cloud resource nested object has only one output field - serviceAccountId.
resource "google_bigquery_connection" "default" {
  connection_id = "my_cloud_resource_connection"
  project       = data.google_project.default.project_id
  location      = "US"
  cloud_resource {}
}

Google Cloud 프로젝트에 Terraform 구성을 적용하려면 다음 섹션의 단계를 완료하세요.

Cloud Shell 준비

  1. Cloud Shell을 실행합니다.
  2. Terraform 구성을 적용할 기본 Google Cloud 프로젝트를 설정합니다.

    이 명령어는 프로젝트당 한 번만 실행하면 되며 어떤 디렉터리에서도 실행할 수 있습니다.

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID

    Terraform 구성 파일에서 명시적 값을 설정하면 환경 변수가 재정의됩니다.

디렉터리 준비

각 Terraform 구성 파일에는 자체 디렉터리(루트 모듈이라고도 함)가 있어야 합니다.

  1. Cloud Shell에서 디렉터리를 만들고 해당 디렉터리 내에 새 파일을 만드세요. 파일 이름에는 .tf 확장자가 있어야 합니다(예: main.tf). 이 튜토리얼에서는 파일을 main.tf라고 합니다.
    mkdir DIRECTORY && cd DIRECTORY && touch main.tf
  2. 튜토리얼을 따라 하는 경우 각 섹션이나 단계에서 샘플 코드를 복사할 수 있습니다.

    샘플 코드를 새로 만든 main.tf에 복사합니다.

    필요한 경우 GitHub에서 코드를 복사합니다. 이는 Terraform 스니펫이 엔드 투 엔드 솔루션의 일부인 경우에 권장됩니다.

  3. 환경에 적용할 샘플 파라미터를 검토하고 수정합니다.
  4. 변경사항을 저장합니다.
  5. Terraform을 초기화합니다. 이 작업은 디렉터리당 한 번만 수행하면 됩니다.
    terraform init

    원하는 경우 최신 Google 공급업체 버전을 사용하려면 -upgrade 옵션을 포함합니다.

    terraform init -upgrade

변경사항 적용

  1. 구성을 검토하고 Terraform에서 만들거나 업데이트할 리소스가 예상과 일치하는지 확인합니다.
    terraform plan

    필요에 따라 구성을 수정합니다.

  2. 다음 명령어를 실행하고 프롬프트에 yes를 입력하여 Terraform 구성을 적용합니다.
    terraform apply

    Terraform에 '적용 완료' 메시지가 표시될 때까지 기다립니다.

  3. 결과를 보려면 Google Cloud 프로젝트를 엽니다. Google Cloud 콘솔에서 UI의 리소스로 이동하여 Terraform이 리소스를 만들었거나 업데이트했는지 확인합니다.

연결의 서비스 계정에 권한 부여

연결의 서비스 계정에 Agent Platform 사용자(roles/aiplatform.user) 역할을 부여합니다. 시작하기 전에 섹션에서 만들었거나 선택한 것과 동일한 프로젝트에서 이 역할을 부여해야 합니다. 다른 프로젝트에서 역할을 부여하면 bqcx-1234567890-xxxx@gcp-sa-bigquery-condel.iam.gserviceaccount.com does not have the permission to access resource 오류가 발생합니다.

역할을 부여하려면 다음 단계를 따르세요.

  1. IAM 및 관리자 페이지로 이동합니다.

    IAM 및 관리자로 이동

  2. 액세스 권한 부여를 클릭합니다.

  3. 새 주 구성원 필드에 앞에서 복사한 서비스 계정 ID를 입력합니다.

  4. 역할 선택 필드에서 Agent Platform 사용자 역할을 검색합니다.

  5. 저장을 클릭합니다.

원격 모델 만들기

CREATE MODEL 문을 사용하여 호스팅된 Agent Platform gemini-embedding-001 텍스트 임베딩 모델을 나타내는 원격 모델을 만듭니다.

  1. Google Cloud 콘솔에서 BigQuery 페이지로 이동합니다.

    BigQuery로 이동

  2. 쿼리 편집기에서 다음 쿼리를 실행합니다.

    CREATE OR REPLACE MODEL `bqml_tutorial.embedding_model`
      REMOTE WITH CONNECTION `LOCATION.CONNECTION_ID`
      OPTIONS (ENDPOINT = 'gemini-embedding-001');

    다음을 바꿉니다.

    • <var>LOCATION</var>: 연결 위치입니다(예: US 멀티 리전에서 연결을 만든 경우 us).
    • <var>CONNECTION_ID</var>: BigQuery 연결의 ID입니다. Google Cloud 콘솔에서 연결 세부정보를 볼 때 이 값은 연결 ID에 표시되는 정규화된 ID의 마지막 세그먼트에 표시됩니다(예: projects/myproject/locations/us/connections/myconnection의 myconnection). 기본 연결을 사용하는 경우 `<var>LOCATION</var>.<var>CONNECTION_ID</var>`를 DEFAULT로 바꿉니다.

    쿼리가 완료되는 데 몇 초 정도 걸리며 그 이후에는 embedding_model 모델이 bqml_tutorial 데이터 세트에 표시됩니다. 이 쿼리에서는 CREATE MODEL 문을 사용하므로 쿼리 결과가 없습니다.

임베딩 생성

AI.GENERATE_EMBEDDING 함수를 사용하여 bigquery-public-data.bbc_news.fulltext 공개 테이블의 뉴스 기사를 임베딩합니다. 입력 쿼리는 content라는 STRING 열에 임베딩할 텍스트를 제공해야 합니다. 검색 문서의 임베딩을 생성할 때 task_type를 'RETRIEVAL_DOCUMENT'로 설정하고 title 열을 포함하여 모델이 더 높은 품질의 문서 임베딩을 생성하도록 합니다. 다른 태스크 유형 및 output_dimensionality과 같은 선택적 매개변수에 대한 자세한 내용은 AI.GENERATE_EMBEDDING 문법 및 임베딩 태스크 유형 선택을 참조하세요.

  1. Google Cloud 콘솔에서 BigQuery 페이지로 이동합니다.

    BigQuery로 이동

  2. 쿼리 편집기에서 다음 문을 실행하여 뉴스 기사 5개에 대한 임베딩을 생성합니다.

    SELECT
      title,
      content,
      embedding,
      statistics,
      status
    FROM
      AI.GENERATE_EMBEDDING(
        MODEL `bqml_tutorial.embedding_model`,
        (
          SELECT
            title,
            body AS content
          FROM
            `bigquery-public-data.bbc_news.fulltext`
          LIMIT 5
        ),
        STRUCT('RETRIEVAL_DOCUMENT' AS task_type)
      );

    출력은 다음과 비슷합니다.

    +-------------------------------+------------------------------------+-----------------------+----------------------------------------+--------+
    | title                         | content                            | embedding             | statistics                             | status |
    +-------------------------------+------------------------------------+-----------------------+----------------------------------------+--------+
    | DVD copy protection...        | DVDs will be harder to copy thanks | -0.015901241451501846 | {"token_count":385,"truncated":false}  |        |
    |                               | to new anti-piracy measures...     | -0.001598291913978755 |                                        |        |
    |                               |                                    | ...                   |                                        |        |
    +-------------------------------+------------------------------------+-----------------------+----------------------------------------+--------+
    | Mobile games come of age...   | The BBC News website takes a look  | -0.00565318763256073  | {"token_count":1051,"truncated":false} |        |
    | fall                          | at how games on mobile phones...   | -0.02261657640337944  |                                        |        |
    |                               |                                    | ...                   |                                        |        |
    +-------------------------------+------------------------------------+-----------------------+----------------------------------------+--------+
    | ...                           | ...                                | ...                   | ...                                    | ...    |
    +-------------------------------+------------------------------------+-----------------------+----------------------------------------+--------+
    

    출력에는 입력 열과 다음 열이 포함됩니다.

    • embedding: 생성된 임베딩 벡터가 포함된 ARRAY<FLOAT64> 값입니다(gemini-embedding-001의 경우 기본적으로 3072 차원).
    • statistics: 입력 token_count 및 입력 텍스트가 truncated인지 여부를 보고하는 JSON 값입니다.
    • status: 요청이 성공하면 비어 있고 해당 행의 요청이 실패하면 오류 세부정보가 포함된 STRING 값입니다.

시맨틱 유사성을 기준으로 텍스트 순위 지정

임베딩을 생성한 후에는 VECTOR_SEARCH 함수를 사용하여 임베딩을 비교하여 의미론적으로 유사한 항목을 찾을 수 있습니다. 코사인 거리 값이 작을수록 시맨틱 유사성이 높습니다. 벡터 검색 및 벡터 색인에 대한 자세한 내용은 벡터 검색 소개를 참조하세요.

  1. Google Cloud 콘솔에서 BigQuery 페이지로 이동합니다.

    BigQuery로 이동

  2. 쿼리 편집기에서 다음 다중 문 쿼리를 실행하여 샘플 영화 리뷰 4개의 임베딩을 임시 테이블에 저장한 다음 쿼리 "This movie was average"에 대한 코사인 거리를 기준으로 정렬합니다.

    CREATE TEMPORARY TABLE movie_review_embeddings AS (
      SELECT *
      FROM
        AI.GENERATE_EMBEDDING(
          MODEL `bqml_tutorial.embedding_model`,
          (
            SELECT 'This movie was fantastic' AS content
            UNION ALL
            SELECT "This was the best movie I've ever seen!!" AS content
            UNION ALL
            SELECT 'This movie was just okay...' AS content
            UNION ALL
            SELECT 'This movie was terrible.' AS content
          )
        )
    );
    
    WITH
      average_review_embedding AS (
        SELECT embedding
        FROM
          AI.GENERATE_EMBEDDING(
            MODEL `bqml_tutorial.embedding_model`,
            (SELECT 'This movie was average' AS content)
          )
      )
    SELECT
      base.content AS content,
      distance AS distance_to_average_review
    FROM
      VECTOR_SEARCH(
        TABLE movie_review_embeddings,
        'embedding',
        (SELECT embedding FROM average_review_embedding),
        distance_type => 'COSINE'
      )
    ORDER BY distance_to_average_review;

    출력은 다음과 비슷합니다.

    +------------------------------------------+----------------------------+
    | content                                  | distance_to_average_review |
    +------------------------------------------+----------------------------+
    | This movie was just okay...              | 0.062789813467745592       |
    | This movie was fantastic                 | 0.18579561313064263        |
    | This movie was terrible.                 | 0.35707466240930985        |
    | This was the best movie I've ever seen!! | 0.41844932504542975        |
    +------------------------------------------+----------------------------+
    

    출력은 리뷰 "This movie was just okay..."가 쿼리 "This movie was average"에 의미론적으로 가장 가깝고 "This was the best movie I've ever seen!!"가 의미론적으로 가장 멀다는 것을 보여줍니다.

삭제

이 튜토리얼에서 사용된 리소스 비용이 Google Cloud 계정에 청구되지 않도록 하려면 리소스가 포함된 프로젝트를 삭제하거나 프로젝트를 유지하고 개별 리소스를 삭제하세요.

프로젝트 삭제

    Google Cloud 프로젝트 삭제:

    gcloud projects delete PROJECT_ID

개별 리소스 삭제

프로젝트를 재사용하려면 이 튜토리얼에서 만든 리소스를 삭제합니다.

콘솔

  1. Google Cloud 콘솔에서 BigQuery 페이지로 이동합니다.

    BigQuery로 이동

  2. bqml_tutorial 데이터 세트를 삭제합니다. 그러면 원격 모델도 삭제됩니다.

    1. 탐색기 창에서 프로젝트를 펼친 후 데이터 세트를 클릭합니다.

    2. 데이터 세트 목록에서 bqml_tutorial를 클릭합니다.

    3. 세부정보 창에서 삭제를 클릭합니다.

    4. 데이터 세트 삭제 대화상자에서 삭제를 클릭합니다.

  3. 이 튜토리얼용 연결을 만든 경우 연결을 삭제합니다.

    1. 탐색기 창에서 프로젝트를 펼친 후 연결을 클릭합니다.

    2. 연결 목록에서 만든 연결을 클릭합니다.

    3. 세부정보 창에서 삭제를 클릭합니다.

    4. 연결 삭제 대화상자에서 delete를 입력한 후 삭제를 클릭합니다.

gcloud

  1. bqml_tutorial 데이터 세트와 원격 모델을 삭제합니다.

    bq rm --dataset --recursive bqml_tutorial
  2. 이 튜토리얼용 연결을 만든 경우 연결을 삭제합니다.

    bq rm --connection \
    PROJECT_ID.LOCATION.CONNECTION_ID

    다음을 바꿉니다.

    • <var>PROJECT_ID</var>: Google Cloud 프로젝트 ID입니다.
    • <var>LOCATION</var>: 연결 위치
    • <var>CONNECTION_ID</var>: 연결 ID입니다.

다음 단계