SQL 및 BigQuery DataFrames를 사용하여 멀티모달 데이터 분석

이 튜토리얼에서는 SQL 쿼리와 BigQuery DataFrames를 사용하여 멀티모달 데이터를 분석하는 방법을 보여줍니다.

이 튜토리얼에서는 공개 Cymbal 애완동물 상점 데이터 세트의 제품 카탈로그를 사용합니다.

목표

  • ObjectRef 값을 사용하여 BigQuery 표준 테이블에 정형 데이터와 함께 이미지 데이터를 저장합니다.
  • AI.GENERATE 함수를 사용하여 이미지 설명, 키워드, 동물 유형, 하위 카테고리로 데이터를 보강합니다.
  • AI.EMBED 함수를 사용하여 이미지 데이터를 기반으로 임베딩을 생성합니다.
  • VECTOR_SEARCH 함수를 사용하여 유사한 이미지를 찾습니다.
  • ObjectRef 값의 배열을 사용하여 순서가 지정된 멀티모달 데이터를 처리하여 사용자 매뉴얼을 요약합니다.

비용

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

  • BigQuery: you incur costs for the data that you process in BigQuery.
  • Cloud Storage: you incur costs for the objects stored in Cloud Storage.
  • Gemini Enterprise Agent Platform: you incur costs for calls to Agent Platform models.

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

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

자세한 내용은 다음 가격 책정 페이지를 참고하세요.

시작하기 전에

  1. Google Cloud 콘솔의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트를 선택하거나 만드는 데 필요한 역할

    • 프로젝트 선택: 프로젝트를 선택하는 데는 특정 IAM 역할이 필요하지 않습니다. 역할이 부여된 프로젝트를 선택하면 됩니다.
    • 프로젝트 만들기: 프로젝트를 만들려면 resourcemanager.projects.create 권한이 포함된 프로젝트 생성자 역할(roles/resourcemanager.projectCreator)이 필요합니다. 역할 부여 방법 알아보기

    프로젝트 선택기로 이동

  2. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  3. BigQuery, BigQuery Connection, Cloud Storage, Agent Platform API API를 사용 설정합니다.

    API 사용 설정에 필요한 역할

    API를 사용 설정하려면 serviceusage.services.enable 권한이 포함된 서비스 사용량 관리자 IAM 역할(roles/serviceusage.serviceUsageAdmin)이 필요합니다. 역할 부여 방법 알아보기

    API 사용 설정

필요한 역할

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

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

커스텀 역할이나 다른 사전 정의된 역할을 통해 필요한 권한을 얻을 수도 있습니다.

설정

이 섹션에서는 이 튜토리얼에서 사용되는 데이터 세트, 연결, 테이블, 모델을 만듭니다.

데이터 세트 만들기

이 튜토리얼에서 만드는 객체를 포함할 BigQuery 데이터 세트를 만듭니다.

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

    BigQuery로 이동

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

    강조 표시된 탐색기 창 버튼

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

  3. 탐색기 창에서 프로젝트를 선택합니다.

  4. 작업 보기를 클릭한 후 데이터 세트 만들기를 클릭합니다. 데이터 세트 만들기 창이 열립니다.

  5. 데이터 세트 IDcymbal_pets를 입력합니다.

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

연결 만들기

클라우드 리소스 연결을 만들고 연결의 서비스 계정을 가져옵니다. BigQuery는 연결을 사용하여 Cloud Storage의 객체에 액세스합니다.

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

    BigQuery로 이동

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

    강조 표시된 탐색기 창 버튼

  3. 탐색기 창에서 데이터 추가를 클릭합니다.

    데이터 추가 대화상자가 열립니다.

  4. 필터링 기준 창의 데이터 소스 유형 섹션에서 비즈니스 애플리케이션을 선택합니다.

    또는 데이터 소스 검색 필드에 Vertex AI을 입력할 수 있습니다.

  5. 추천 데이터 소스 섹션에서 Vertex AI를 클릭합니다.

  6. Vertex AI 모델: BigQuery 제휴 솔루션 카드를 클릭합니다.

  7. 연결 유형 목록에서 Vertex AI 원격 모델, 원격 함수, BigLake, Spanner (Cloud 리소스)를 선택합니다.

  8. 연결 ID 필드에 cymbal_conn을 입력합니다.

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

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

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

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

다른 서비스에 액세스할 수 있도록 연결의 서비스 계정에 적절한 역할을 부여합니다. 시작하기 전에 섹션에서 만들었거나 선택한 것과 동일한 프로젝트에서 이러한 역할을 부여해야 합니다. 다른 프로젝트에서 역할을 부여하면 bqcx-1234567890-xxxx@gcp-sa-bigquery-condel.iam.gserviceaccount.com does not have the permission to access resource 오류가 발생합니다.

버킷 만들기

변환된 객체를 저장할 Cloud Storage 버킷을 만듭니다.

  1. 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 만들기를 클릭합니다.

  3. 버킷 만들기 페이지의 시작하기 섹션에서 버킷 이름 요구사항을 충족하는 전역적으로 고유한 이름을 입력합니다.

  4. 만들기를 클릭합니다.

Cloud Storage 버킷에 대한 권한 부여

생성한 버킷의 객체를 사용할 수 있는 액세스 권한을 서비스 계정에 부여합니다.

  1. 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 만든 버킷의 이름을 클릭합니다.

  3. 권한을 클릭합니다.

  4. 액세스 권한 부여를 클릭합니다. 액세스 권한 부여 대화상자가 열립니다.

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

  6. 역할 선택 필드에서 Cloud Storage를 선택한 후 스토리지 객체 사용자를 선택합니다.

  7. 저장을 클릭합니다.

Agent Platform 모델을 사용할 권한 부여

서비스 계정에 Agent Platform 모델을 사용할 수 있는 액세스 권한을 부여합니다.

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

    IAM 및 관리자로 이동

  2. 액세스 권한 부여를 클릭합니다. 액세스 권한 부여 대화상자가 열립니다.

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

  4. 역할 선택 필드에 Agent Platform User를 입력합니다.

  5. 저장을 클릭합니다.

예시 데이터 테이블 만들기

Cymbal 애완동물 제품 정보를 저장할 테이블을 만듭니다.

products 테이블 만들기

Cymbal pets 제품 정보가 포함된 표준 테이블을 만듭니다.

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

    BigQuery로 이동

  2. 다음을 실행하여 products 테이블을 만듭니다.

    SQL

    LOAD DATA OVERWRITE cymbal_pets.products
    FROM
      FILES(
        format = 'avro',
        uris = [
          'gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/tables/products/products_*.avro']);

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    import bigframes.bigquery as bbq
    import bigframes.pandas as bpd
    
    bbq.load_data(
        "cymbal_pets.products",
        write_disposition="OVERWRITE",
        from_files_options={
            "format": "avro",
            "uris": [
                "gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/tables/products/products_*.avro"
            ],
        },
    )

product_images 테이블 만들기

Cymbal 애완동물 제품 이미지가 포함된 객체 테이블을 만듭니다.

  • 다음을 실행하여 product_images 테이블을 만듭니다.

    SQL

    CREATE OR REPLACE EXTERNAL TABLE cymbal_pets.product_images
      WITH CONNECTION `us.cymbal_conn`
      OPTIONS (
        object_metadata = 'SIMPLE',
        uris = ['gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/images/*.png'],
        max_staleness = INTERVAL 30 MINUTE,
        metadata_cache_mode = AUTOMATIC);

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    bbq.create_external_table(
        "cymbal_pets.product_images",
        replace=True,
        connection_name="us.cymbal_conn",
        options={
            "object_metadata": "SIMPLE",
            "uris": [
                "gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/images/*.png"
            ],
        },
    )

모델 만들기

이 튜토리얼의 SQL 안내에서는 모델을 만들지 않아도 되는 AI 함수를 호출하는 방법을 보여줍니다. BigQuery DataFrames 안내를 따르는 경우 이 옵션을 선택하여 Gemini 모델과 멀티모달 임베딩 모델을 나타내는 원격 모델을 만듭니다.

SQL

이 단계를 건너뛸 수 있습니다.

BigQuery DataFrames

이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

gemini_model = bbq.ml.create_model(
    "cymbal_pets.gemini",
    replace=True,
    connection_name="us.cymbal_conn",
    options={"endpoint": "gemini-2.5-flash"},
)

embedding_model = bbq.ml.create_model(
    "cymbal_pets.embedding_model",
    replace=True,
    connection_name="us.cymbal_conn",
    options={"endpoint": "multimodalembedding@001"},
)

멀티모달 데이터로 products_mm 테이블 만들기

product_images 객체 테이블의 제품 이미지로 채워진 image 열이 포함된 products_mm 테이블을 만듭니다. 생성된 image 열은 ObjectRef 형식을 사용하는 STRUCT 열입니다.

  1. 다음을 실행하여 products_mm 테이블을 만들고 image 열을 채웁니다.

    SQL

    CREATE OR REPLACE TABLE cymbal_pets.products_mm
    AS
    SELECT products.* EXCEPT (uri), ot.ref AS image FROM cymbal_pets.products
    INNER JOIN cymbal_pets.product_images ot
    ON ot.uri = products.uri;

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df_images = bpd.read_gbq("SELECT * FROM cymbal_pets.product_images")
    df_products = bpd.read_gbq("cymbal_pets.products")
    
    df_products_mm = df_images.merge(df_products, on="uri").drop(columns="uri")
    df_products_mm = df_products_mm.rename(columns={"ref": "image"})
  2. 다음을 실행하여 image 열 데이터를 확인합니다.

    SQL

    SELECT product_name, image
    FROM cymbal_pets.products_mm

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df_products_mm[["product_name", "image"]]

    결과는 다음과 유사합니다.

    +--------------------------------+--------------------------------------+-----------------------------------------------+------------------------------------------------+
    | product_name                   | image.uri                            | image.version | image.authorizer              | image.details                                  |
    +--------------------------------+--------------------------------------+-----------------------------------------------+------------------------------------------------+
    |  AquaClear Aquarium Background | gs://cloud-samples-data/bigquery/    | 1234567891011 | myproject.region.myconnection | {"gcs_metadata":{"content_type":"image/png",   |
    |                                | tutorials/cymbal-pets/images/        |               |                               | "md5_hash":"494f63b9b137975ff3e7a11b060edb1d", |
    |                                | aquaclear-aquarium-background.png    |               |                               | "size":1282805,"updated":1742492680017000}}    |
    +--------------------------------+--------------------------------------+-----------------------------------------------+------------------------------------------------+
    |  AquaClear Aquarium            | gs://cloud-samples-data/bigquery/    | 2345678910112 | myproject.region.myconnection | {"gcs_metadata":{"content_type":"image/png",   |
    |  Gravel Vacuum                 | tutorials/cymbal-pets/images/        |               |                               | "md5_hash":"b7bfc2e2641a77a402a1937bcf0003fd", |
    |                                | aquaclear-aquarium-gravel-vacuum.png |               |                               | "size":820254,"updated":1742492682411000}}     |
    +--------------------------------+--------------------------------------+-----------------------------------------------+------------------------------------------------+
    | ...                            | ...                                  | ...           |                               | ...                                            |
    +--------------------------------+--------------------------------------+-----------------------------------------------+------------------------------------------------+
    

제품 정보 생성

AI.GENERATE 함수를 사용하여 반려동물 용품점 제품에 대한 다음 데이터를 생성합니다.

  • products_mm 테이블에 image_description 열을 추가합니다.
  • products_mm 테이블의 animal_type, search_keywords, subcategory 열을 채웁니다.
  • 각 제품 브랜드의 설명과 해당 브랜드의 제품 수를 반환하는 쿼리를 실행합니다. 브랜드 설명은 제품 이미지를 비롯해 해당 브랜드의 모든 제품에 대한 제품 정보를 분석하여 생성됩니다.
  1. 다음을 실행하여 image_description 열을 만들고 채웁니다.

    SQL

    CREATE OR REPLACE TABLE cymbal_pets.products_mm AS (
      SELECT
        *, AI.GENERATE(('Describe the following image: ', image), endpoint => 'gemini-2.5-pro').result AS image_description
      FROM
        cymbal_pets.products_mm
    );

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df_products_mm["url"] = bbq.obj.get_access_url(
        df_products_mm["image"], "R"
    ).to_frame()
    df_products_mm["prompt0"] = "Can you describe the following image?"
    
    df_products_mm["prompt"] = bbq.struct(df_products_mm[["prompt0", "url"]])
    df_products_mm = bbq.ai.generate_table(
        gemini_model, df_products_mm, output_schema={"image_description": "STRING"}
    )
    
    df_products_mm = df_products_mm[
        [
            "product_id",
            "product_name",
            "brand",
            "category",
            "subcategory",
            "animal_type",
            "search_keywords",
            "price",
            "description",
            "inventory_level",
            "supplier_id",
            "average_rating",
            "image",
            "image_description",
        ]
    ]
  2. 다음을 실행하여 생성된 데이터로 animal_type, search_keywords, subcategory 열을 업데이트합니다.

    SQL

    CREATE OR REPLACE TABLE cymbal_pets.products_mm AS (
    SELECT * EXCEPT(animal_type, search_keywords, subcategory),
      AI.GENERATE(
        ('For the image and description of a pet product, concisely generate the following metadata: '
        '1) animal_type and 2) 5 SEO search keywords, and 3) product subcategory. ',
        image,
        description),
        endpoint => 'gemini-2.5-pro',
        output_schema => 'animal_type STRING, search_keywords ARRAY, subcategory STRING').*
    FROM cymbal_pets.products_mm);

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df_prompt = bbq.obj.get_access_url(df_products_mm["image"], "R").to_frame()
    df_prompt[
        "prompt0"
    ] = "For the image of a pet product, concisely generate the following metadata: 1) animal_type and 2) 5 SEO search keywords, and 3) product subcategory."
    
    df_products_mm["prompt"] = bbq.struct(df_prompt[["prompt0", "image"]])
    
    df_products_mm = df_products_mm.drop(
        columns=["animal_type", "search_keywords", "subcategory"]
    )
    df_products_mm = bbq.ai.generate_table(
        gemini_model,
        df_products_mm,
        output_schema="animal_type STRING, search_keywords ARRAY<STRING>, subcategory STRING",
    )
  3. 다음을 실행하여 생성된 데이터를 확인합니다.

    SQL

    SELECT
      product_name,
      image_description,
      animal_type,
      search_keywords,
      subcategory,
    FROM cymbal_pets.products_mm;

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df_products_mm[
        [
            "product_name",
            "image_description",
            "animal_type",
            "search_keywords",
            "subcategory",
        ]
    ]

    결과는 다음과 유사합니다.

    +--------------------------------+-------------------------------------+-------------+------------------------+------------------+
    | product_name                   | image.description                   | animal_type | search_keywords        | subcategory      |
    +--------------------------------+-------------------------------------+-------------+------------------------+------------------+
    |  AquaClear Aquarium Background | The image shows a colorful coral    | fish        | aquarium background    | aquarium decor   |
    |                                | reef backdrop. The background is a  |             | fish tank backdrop     |                  |
    |                                | blue ocean with a bright light...   |             | coral reef decor       |                  |
    |                                |                                     |             | underwater scenery     |                  |
    |                                |                                     |             | aquarium decoration    |                  |
    +--------------------------------+-------------------------------------+-------------+------------------------+------------------+
    |  AquaClear Aquarium            | The image shows a long, clear       | fish        | aquarium gravel vacuum | aquarium         |
    |  Gravel Vacuum                 | plastic tube with a green hose      |             | aquarium cleaning      | cleaning         |
    |                                | attached to one end. The tube...    |             | aquarium maintenance   |                  |
    |                                |                                     |             | fish tank cleaning     |                  |
    |                                |                                     |             | gravel siphon          |                  |
    +--------------------------------+-------------------------------------+-------------+------------------------+------------------+
    | ...                            | ...                                 | ...         |  ...                   | ...              |
    +--------------------------------+-------------------------------------+-------------+------------------------+------------------+
    
  4. 다음을 실행하여 각 제품 브랜드의 설명과 해당 브랜드의 제품 수를 생성합니다.

    SQL

    SELECT
      brand,
      COUNT(*) AS cnt,
      AI.GENERATE(('Use the images and text to give one concise brand description ',
                  'for a website brand page. Return the description only.',
                    ARRAY_AGG(image LIMIT 10), ARRAY_AGG(description), ARRAY_AGG(category),
                    ARRAY_AGG(subcategory)),
                  endpoint => 'gemini-2.5-pro').result AS brand_description
    FROM
      cymbal_pets.products_mm
    GROUP BY brand
    ORDER BY cnt DESC;

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df_agg = df_products_mm[
        ["image", "description", "category", "subcategory", "brand"]
    ]
    df_agg["image"] = bbq.obj.get_access_url(df_products_mm["image"], "R")
    df_agg = bbq.array_agg(df_agg.groupby(by=["brand"]))
    
    df_agg["cnt"] = bbq.array_length(df_agg["image"])
    
    df_prompt = df_agg[["image", "description", "category", "subcategory"]]
    df_prompt[
        "prompt0"
    ] = "Use the images and text to give one concise brand description for a website brand page. Return the description only. "
    
    df_agg["prompt"] = bbq.struct(
        df_prompt[["prompt0", "image", "description", "category", "subcategory"]]
    )
    
    df_agg = df_agg.reset_index()
    
    df_agg = bbq.ai.generate_table(
        gemini_model, df_agg, output_schema={"brand_description": "STRING"}
    )
    df_agg[["brand", "brand_description", "cnt"]]

    결과는 다음과 유사합니다.

    +--------------+-------------------------------------+-----+
    | brand        | brand.description                   | cnt |
    +--------------+-------------------------------------+-----+
    |  AquaClear   | AquaClear is a brand of aquarium    | 33  |
    |              | and pond care products that offer   |     |
    |              | a wide range of solutions for...    |     |
    +--------------+-------------------------------------+-----+
    |  Ocean       | Ocean Bites is a brand of cat food  | 28  |
    |  Bites       | that offers a variety of recipes    |     |
    |              | and formulas to meet the specific.. |     |
    +--------------+-------------------------------------+-----+
    |  ...         | ...                                 |...  |
    +--------------+-------------------------------------+-----+
    

이미지 데이터에서 임베딩을 생성한 다음 임베딩을 사용하여 벡터 검색을 통해 유사한 이미지를 반환합니다.

프로덕션 시나리오에서는 벡터 검색을 실행하기 전에 벡터 색인을 만드는 것이 좋습니다. 벡터 색인을 사용하면 벡터 검색을 보다 신속하게 수행하고 재현율을 줄여 더 나은 근사치의 결과를 반환합니다.

  1. 다음을 실행하여 products_embeddings 테이블을 만듭니다.

    SQL

    CREATE OR REPLACE TABLE cymbal_pets.products_embedding
    AS (
      SELECT
        product_id,
        AI.EMBED(image, endpoint => 'multimodalembedding@001').result AS embedding,
        image
      FROM cymbal_pets.products_mm
    );

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df_products_mm["content"] = bbq.obj.get_access_url(df_products_mm["image"], "R")
    df_embed = bbq.ai.generate_embedding(
        embedding_model, df_products_mm[["content", "product_id"]]
    )
    
    df_embed.to_gbq("cymbal_pets.products_embedding", if_exists="replace")
  2. 다음 명령어를 실행하여 지정된 입력 이미지와 유사한 제품 이미지를 반환하는 벡터 검색을 실행합니다.

    SQL

    SELECT *
    FROM
      VECTOR_SEARCH(
        TABLE cymbal_pets.products_embedding,
        'embedding',
        query_value => AI.EMBED(
                        OBJ.MAKE_REF('gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/images/cozy-naps-cat-scratching-post-with-condo.png'),
                        endpoint => 'multimodalembedding@001').result);

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df_image = bpd.DataFrame(
        {
            "uri": [
                "gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/images/cozy-naps-cat-scratching-post-with-condo.png"
            ]
        }
    ).cache()
    df_image["image"] = bbq.obj.make_ref(df_image["uri"], "us.cymbal_conn")
    df_search = bbq.ai.generate_embedding(
        embedding_model,
        bbq.obj.get_access_url(bbq.obj.fetch_metadata(df_image["image"]), "R"),
    )
    
    search_result = bbq.vector_search(
        "cymbal_pets.products_embedding", "embedding", df_search["embedding"]
    )
    search_result

    결과는 다음과 유사합니다.

    +-----------------+-----------------+----------------+----------------------------------------------+--------------------+-------------------------------+------------------------------------------------+----------------+
    | query.embedding | base.product_id | base.embedding | base.image.uri                               | base.image.version | base.image.authorizer         | base.image.details                             | distance       |
    +-----------------+-----------------+----------------+----------------------------------------------+--------------------+-------------------------------+------------------------------------------------+----------------+
    | -0.0112330541   | 181             | -0.0112330541  | gs://cloud-samples-data/bigquery/            | 12345678910        | myproject.region.myconnection | {"gcs_metadata":{"content_type":               | 0.0            |
    | 0.0142525584    |                 |  0.0142525584  | tutorials/cymbal-pets/images/                |                    |                               | "image/png","md5_hash":"21234567hst16555w60j", |                |
    | 0.0135886827    |                 |  0.0135886827  | cozy-naps-cat-scratching-post-with-condo.png |                    |                               | "size":828318,"updated":1742492688982000}}     |                |
    | 0.0149955815    |                 |  0.0149955815  |                                              |                    |                               |                                                |                |
    | ...             |                 |  ...           |                                              |                    |                               |                                                |                |
    |                 |                 |                |                                              |                    |                               |                                                |                |
    |                 |                 |                |                                              |                    |                               |                                                |                |
    +-----------------+-----------------+----------------+----------------------------------------------+--------------------+-------------------------------+------------------------------------------------+----------------+
    | -0.0112330541   | 187             | -0.0190353896  | gs://cloud-samples-data/bigquery/            | 23456789101        | myproject.region.myconnection | {"gcs_metadata":{"content_type":               | 0.4216330832.. |
    | 0.0142525584    |                 |  0.0116206668  | tutorials/cymbal-pets/images/                |                    |                               | "image/png","md5_hash":"7328728fhakd9937djo4", |                |
    | 0.0135886827    |                 |  0.0136198215  | cozy-naps-cat-scratching-post-with-bed.png   |                    |                               | "size":860113,"updated":1742492688774000}}     |                |
    | 0.0149955815    |                 |  0.0173457414  |                                              |                    |                               |                                                |                |
    | ...             |                 |  ...           |                                              |                    |                               |                                                |                |
    |                 |                 |                |                                              |                    |                               |                                                |                |
    |                 |                 |                |                                              |                    |                               |                                                |                |
    +-----------------+-----------------+----------------+----------------------------------------------+--------------------+-------------------------------+------------------------------------------------+----------------+
    | ...             | ...             | ...            | ...                                          | ...                | ...                           | ...                                            | ...            |
    +-----------------+-----------------+----------------+----------------------------------------------+--------------------+-------------------------------+------------------------------------------------+----------------+
    

ObjectRef 값의 배열을 사용하여 순서가 지정된 멀티모달 데이터 처리

이 섹션에서는 다음 작업을 완료하는 방법을 보여줍니다.

  1. Crittercuisine Pro 5000 제품 설명서의 PDF 파일과 해당 설명서의 각 페이지에 대한 PDF 파일을 모두 포함하도록 product_manuals 표를 만듭니다.
  2. 매뉴얼을 청크에 매핑하는 표를 만듭니다. 전체 매뉴얼과 매뉴얼 페이지는 각각 ObjectRef 열에 저장됩니다.
  3. ObjectRef 값의 배열을 함께 분석하여 생성된 단일 값을 반환합니다.
  4. ObjectRef 값 배열을 별도로 분석하고 각 배열 값에 대해 생성된 값을 반환합니다.

ObjectRef 값을 사용하여 순서가 지정된 멀티모달 데이터를 처리하려면 다음 단계를 따르세요.

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

    BigQuery로 이동

  2. 다음을 실행하여 product_manuals 테이블을 만듭니다.

    SQL

    CREATE OR REPLACE EXTERNAL TABLE `cymbal_pets.product_manuals`
      WITH CONNECTION `us.cymbal_conn`
      OPTIONS (
        object_metadata = 'SIMPLE',
        uris = [
            'gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/documents/*.pdf',
            'gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/document_chunks/*.pdf']);

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    bbq.create_external_table(
        "cymbal_pets.product_manuals_all",
        replace=True,
        connection_name="us.cymbal_conn",
        options={
            "object_metadata": "SIMPLE",
            "uris": [
                "gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/documents/*.pdf",
                "gs://cloud-samples-data/bigquery/tutorials/cymbal-pets/document_chunks/*.pdf",
            ],
        },
    )
  3. 다음을 실행하여 PDF 데이터를 map_manual_to_chunks 테이블에 씁니다.

    SQL

    -- Extract the file and chunks into a single table.
    -- Store the chunks in the chunks column as array of ObjectRefs (ordered by page number)
    CREATE OR REPLACE TABLE cymbal_pets.map_manual_to_chunks
    AS
    SELECT ARRAY_AGG(m1.ref)[0] manual, ARRAY_AGG(m2.ref ORDER BY m2.ref.uri) chunks
    FROM cymbal_pets.product_manuals m1
    JOIN cymbal_pets.product_manuals m2
      ON
        REGEXP_EXTRACT(m1.uri, r'.*/([^.]*).[^/]+')
        = REGEXP_EXTRACT(m2.uri, r'.*/([^.]*)_page[0-9]+.[^/]+')
    GROUP BY m1.uri;

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df1 = bpd.read_gbq("SELECT * FROM cymbal_pets.product_manuals_all").sort_values(
        "uri"
    )
    df2 = df1.copy()
    df1["name"] = df1["uri"].str.extract(r".*/([^.]*).[^/]+")
    df2["name"] = df2["uri"].str.extract(r".*/([^.]*)_page[0-9]+.[^/]+")
    df_manuals_all = df1.merge(df2, on="name")
    df_manuals_agg = (
        bbq.array_agg(df_manuals_all[["ref_x", "uri_x"]].groupby("uri_x"))["ref_x"]
        .str[0]
        .to_frame()
    )
    df_manuals_agg["chunks"] = bbq.array_agg(
        df_manuals_all[["ref_y", "uri_x"]].groupby("uri_x")
    )["ref_y"]
  4. 다음을 실행하여 map_manual_to_chunks 테이블에서 PDF 데이터를 확인합니다.

    SQL

    SELECT *
    FROM cymbal_pets.map_manual_to_chunks;

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df_manuals_agg

    결과는 다음과 유사합니다.

    +-------------------------------------+--------------------------------+-----------------------------------+------------------------------------------------------+-------------------------------------------+---------------------------------+------------------------------------+-------------------------------------------------------+
    | manual.uri                          | manual.version                 | manual.authorizer                 | manual.details                                       | chunks.uri                                | chunks.version                  | chunks.authorizer                  | chunks.details                                        |
    +-------------------------------------+--------------------------------+-----------------------------------+------------------------------------------------------+-------------------------------------------+---------------------------------+------------------------------------+-------------------------------------------------------+
    | gs://cloud-samples-data/bigquery/   | 1742492785900455               | myproject.region.myconnection     | {"gcs_metadata":{"content_type":"application/pef",   | gs://cloud-samples-data/bigquery/         | 1745875761227129                | myproject.region.myconnection      | {"gcs_metadata":{"content_type":"application/pdf",    |
    | tutorials/cymbal-pets/documents/    |                                |                                   | "md5_hash":"c9032b037693d15a33210d638c763d0e",       | tutorials/cymbal-pets/documents/          |                                 |                                    | "md5_hash":"5a1116cce4978ec1b094d8e8b49a1d7c",        |
    | crittercuisine_5000_user_manual.pdf |                                |                                   | "size":566105,"updated":1742492785941000}}           | crittercuisine_5000_user_manual_page1.pdf |                                 |                                    | "size":504583,"updated":1745875761266000}}            |
    |                                     |                                |                                   |                                                      +-------------------------------------------+---------------------------------+------------------------------------+-------------------------------------------------------+
    |                                     |                                |                                   |                                                      | crittercuisine_5000_user_manual_page1.pdf | 1745875760613874                | myproject.region.myconnection      | {"gcs_metadata":{"content_type":"application/pdf",    |
    |                                     |                                |                                   |                                                      | tutorials/cymbal-pets/documents/          |                                 |                                    | "md5_hash":"94d03ec65d28b173bc87eac7e587b325",        |
    |                                     |                                |                                   |                                                      | crittercuisine_5000_user_manual_page2.pdf |                                 |                                    | "size":94622,"updated":1745875760649000}}             |
    |                                     |                                |                                   |                                                      +-------------------------------------------+---------------------------------+------------------------------------+-------------------------------------------------------+
    |                                     |                                |                                   |                                                      | ...                                       | ...                             |  ...                               | ...                                                   |
    +-------------------------------------+--------------------------------+-----------------------------------+------------------------------------------------------+-------------------------------------------+---------------------------------+------------------------------------+-------------------------------------------------------+
    
  5. 다음 코드를 실행하여 ObjectRef 값 배열 분석을 기반으로 Gemini 모델에서 단일 응답을 생성합니다.

    SQL

    SELECT
      AI.GENERATE((
        '''Can you provide a page by page summary for the first 3 pages of the attached manual?
        Only write one line for each page. The pages are provided in serial order''',
        chunks),
        endpoint => 'gemini-2.5-pro').result AS Response,
    FROM cymbal_pets.map_manual_to_chunks

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    df_manuals_agg["chunks_url"] = bbq.array_agg(
        bbq.obj.get_access_url(df_manuals_agg.explode("chunks")["chunks"], "R").groupby(
            "uri_x"
        )
    )
    df_manuals_agg[
        "prompt0"
    ] = "Can you provide a page by page summary for the first 3 pages of the attached manual? Only write one line for each page. The pages are provided in serial order"
    df_manuals_agg["prompt"] = bbq.struct(df_manuals_agg[["prompt0", "chunks_url"]])
    
    result = bbq.ai.generate_text(gemini_model, df_manuals_agg["prompt"])["result"]
    result

    결과는 다음과 유사합니다.

    +---------------------------------------------------------------------------+
    | Response                                                                  |
    +---------------------------------------------------------------------------+
    | Here is a one-line summary for each of the first 3 pages:                 |
    |                                                                           |
    | Page 1 introduces the CritterCuisine Pro 5000 automatic pet feeder and    |
    | presents the initial part of the manual's Table of Contents.              |
    | Page 2 lists the items included with the feeder and details important     |
    | safety precautions for its use.                                           |
    | Page 3 describes the feeder's key features, provides assembly and initial |
    | setup instructions, and begins the programming guide with clock setting.  |
    +---------------------------------------------------------------------------+
    
  6. 다음 코드를 실행하여 ObjectRef 값 배열 분석을 기반으로 Gemini 모델에서 여러 응답을 생성합니다.

    SQL

    WITH results AS (
      SELECT
        AI.GENERATE((
          '''Can you provide a page by page summary for the first 3 pages of the attached manual?
          Only write one line for each page. The pages are provided in serial order''',
          chunks),
          endpoint => 'gemini-2.5-pro'
          output_schema =>  'page1_summary STRING, page2_summary STRING, page3_summary STRING').*
      FROM cymbal_pets.map_manual_to_chunks)
    SELECT page1_summary, page2_summary, page3_summary
    FROM results;

    BigQuery DataFrames

    이 샘플을 사용해 보기 전에 BigQuery DataFrames를 사용하여 BigQuery 빠른 시작의 BigQuery DataFrames 설정 안내를 따르세요. 자세한 내용은 BigQuery DataFrames 참고 문서를 확인하세요.

    BigQuery에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 ADC 설정을 참조하세요.

    result = bbq.ai.generate_table(
        gemini_model,
        df_manuals_agg["prompt"],
        output_schema={
            "page1_summary": "STRING",
            "page2_summary": "STRING",
            "page3_summary": "STRING",
        },
    )[["page1_summary", "page2_summary", "page3_summary"]]
    result

    결과는 다음과 유사합니다.

    +-----------------------------------------------+-------------------------------------------+----------------------------------------------------+
    | page1_summary                                 | page2_summary                             | page3_summary                                      |
    +-----------------------------------------------+-------------------------------------------+----------------------------------------------------+
    | This manual provides an overview of the       | This section explains how to program      | This page covers connecting the feeder to Wi-Fi    |
    | CritterCuisine Pro 5000 automatic pet feeder, | the feeder's clock, set feeding           | using the CritterCuisine Connect app,  remote      |
    | including its features, safety precautions,   | schedules, copy and delete meal settings, | feeding, managing feeding schedules, viewing       |
    | assembly instructions, and initial setup.     | manually feed your pet, record            | feeding logs, receiving low food alerts,           |
    |                                               | a voice message, and understand           | updating firmware, creating multiple pet profiles, |
    |                                               | the low food level indicator.             | sharing access with other users, and cleaning      |
    |                                               |                                           | and maintaining the feeder.                        |
    +-----------------------------------------------+-------------------------------------------+----------------------------------------------------+
    

삭제

  1. Google Cloud 콘솔에서 리소스 관리 페이지로 이동합니다.

    리소스 관리로 이동

  2. 프로젝트 목록에서 삭제할 프로젝트를 선택하고 삭제를 클릭합니다.
  3. 대화상자에서 프로젝트 ID를 입력한 후 종료를 클릭하여 프로젝트를 삭제합니다.