カスタム レコメンデーション データストアを作成する

データストアを作成してカスタム レコメンデーションのデータを取り込むには、使用するソースのセクションに移動します。

BigQuery

BigQuery テーブルからデータストアを作成するには、次の 2 つの方法があります。

  • 1 回限りの取り込み: BigQuery テーブルからデータストアにデータをインポートします。データストア内のデータは、手動でデータを更新しない限り変更されません。

  • 定期的な取り込み: 1 つ以上の BigQuery テーブルからデータをインポートし、BigQuery データセットの最新データでデータストアが更新される頻度を決定する同期頻度を設定します。

次の表は、BigQuery データを Vertex AI Search データストアにインポートする 2 つの方法を比較したものです。

1 回限りの取り込み 定期的な取り込み
一般提供(GA)。 公開プレビュー版。
データは手動で更新する必要があります。 データは 1 日、3 日、5 日ごとに自動的に更新されます。データを手動で更新することはできません。
Vertex AI Search は、BigQuery の 1 つのテーブルから単一のデータストアを作成します。 Vertex AI Search は、BigQuery データセットデータコネクタと、指定されたテーブルごとにデータストア(エンティティ データストア)を作成します。データ コネクタごとに、テーブルのデータ型(構造化など)が同じで、同じ BigQuery データセットに存在している必要があります。
複数のテーブルのデータを 1 つのデータストアに結合するには、まず 1 つのテーブルからデータを取り込み、次に別のソースまたは BigQuery テーブルからデータを取り込みます。 手動データ インポートはサポートされていないため、エンティティ データストアのデータは 1 つの BigQuery テーブルからのみ取得できます。
データソースへのアクセス制御がサポートされています。 データソースへのアクセス制御はサポートされていません。インポートされたデータにアクセス制御を含めることはできますが、これらの制御は適用されません。
データストアは、Google Cloud コンソールまたは API を使用して作成できます。 データ コネクタとそのエンティティ データストアは、コンソールを使用して作成する必要があります。
CMEK 準拠。 CMEK 準拠。

BigQuery から 1 回インポートする

BigQuery テーブルからデータを取り込むには、次の手順でデータストアを作成し、 Google Cloud コンソールまたは API を使用してデータを取り込みます。

データをインポートする前に、取り込むデータを準備します

コンソール

Google Cloud コンソールを使用して BigQuery からデータを取り込む手順は次のとおりです。

  1. Google Cloud コンソールで、[AI アプリケーション] ページに移動します。

    AI アプリケーション

  2. [データストア] ページに移動します。

  3. [データストアを作成] をクリックします。

  4. [ソース] ページで、[BigQuery] を選択します。

  5. [インポートするデータの種類] セクションで、インポートするデータの種類を選択します。

  6. [同期の頻度] セクションで [1 回] を選択します。

  7. [BigQuery のパス] フィールドで [参照] をクリックし、取り込み用に準備したテーブルを選択して、[選択] をクリックします。 または、[BigQuery パス] フィールドにテーブルの場所を直接入力します。

  8. [続行] をクリックします。

  9. 構造化データを 1 回限りインポートする場合:

    1. フィールドをキー プロパティにマッピングします。

    2. スキーマに重要なフィールドが欠落している場合は、[新しいフィールドを追加] を使用して追加します。

      詳細については、自動検出と編集についてをご覧ください。

    3. [続行] をクリックします。

  10. データストアのリージョンを選択します。

  11. データストアの名前を入力します。

  12. [作成] をクリックします。

  13. 取り込みのステータスを確認するには、[データストア] ページに移動し、データストア名をクリックして、[データ] ページで詳細を表示します。 [アクティビティ] タブのステータス列が [進行中] から [インポート完了] に変わると、取り込みが完了します。

    取り込みには、データのサイズに応じて、数分から数時間かかることがあります。

REST

コマンドラインを使用してデータストアを作成し、BigQuery からデータをインポートする手順は次のとおりです。

  1. データストアを作成します。

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    -H "X-Goog-User-Project: PROJECT_ID" \
    "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/dataStores?dataStoreId=DATA_STORE_ID" \
    -d '{
      "displayName": "DATA_STORE_DISPLAY_NAME",
      "industryVertical": "GENERIC",
      "solutionTypes": ["SOLUTION_TYPE_RECOMMENDATION"]
    }'
    

    次のように置き換えます。

    • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
    • DATA_STORE_ID: 作成する Vertex AI Search データストアの ID。この ID に使用できるのは、小文字、数字、アンダースコア、ハイフンのみです。
    • DATA_STORE_DISPLAY_NAME: 作成する Vertex AI Search データストアの表示名。
  2. BigQuery からデータをインポートします。

    スキーマを定義した場合は、データがそのスキーマに準拠していることを確認します。

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/dataStores/DATA_STORE_ID/branches/0/documents:import" \
    -d '{
      "bigquerySource": {
        "projectId": "PROJECT_ID",
        "datasetId":"DATASET_ID",
        "tableId": "TABLE_ID",
        "dataSchema": "DATA_SCHEMA",
        "aclEnabled": "BOOLEAN"
      },
      "reconciliationMode": "RECONCILIATION_MODE",
      "autoGenerateIds": "AUTO_GENERATE_IDS",
      "idField": "ID_FIELD",
      "errorConfig": {
        "gcsPrefix": "ERROR_DIRECTORY"
      }
    }'
    

    次のように置き換えます。

    • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
    • DATA_STORE_ID: Vertex AI Search データストアの ID。
    • DATASET_ID: BigQuery データセットの ID。
    • TABLE_ID: BigQuery テーブルの ID。
      • BigQuery テーブルが PROJECT_ID にない場合は、サービス アカウント service-<project number>@gcp-sa-discoveryengine.iam.gserviceaccount.com に BigQuery テーブルに対する「BigQuery データ閲覧者」権限を付与する必要があります。たとえば、ソース プロジェクト「123」から宛先プロジェクト「456」に BigQuery テーブルをインポートする場合は、プロジェクト「123」の BigQuery テーブルに対する [email protected] 権限を付与します。
    • DATA_SCHEMA: 省略可。値は document および custom です。デフォルトは document です。
      • document: 使用する BigQuery テーブルは、取り込み用にデータを準備するで説明されているデフォルトの BigQuery スキーマに準拠している必要があります。各ドキュメントの ID を自分で定義し、すべてのデータを jsonData 文字列にラップできます。
      • custom: 任意の BigQuery テーブル スキーマが受け入れられ、Vertex AI Search はインポートされる各ドキュメントの ID を自動的に生成します。
    • ERROR_DIRECTORY: 省略可。インポートに関するエラー情報用の Cloud Storage ディレクトリ(例: gs://<your-gcs-bucket>/directory/import_errors)。Vertex AI Search に一時ディレクトリを自動的に作成させるには、この項目を空のままにすることをおすすめします。
    • RECONCILIATION_MODE: 省略可。値は FULL および INCREMENTAL です。デフォルトは INCREMENTAL です。INCREMENTAL を指定すると、BigQuery からデータストアへのデータの増分更新が行われます。これにより、アップサート オペレーションが実行され、新しいドキュメントを追加し、既存のドキュメントを更新された同じ ID のドキュメントで置き換えます。FULL を指定すると、データストア内のドキュメントが完全に再ベース化されます。つまり、新規および更新されたドキュメントがデータストアに追加され、BigQuery にないドキュメントがデータストアから削除されます。FULL モードは、不要になったドキュメントを自動的に削除する場合に便利です。
    • AUTO_GENERATE_IDS: 省略可。ドキュメント ID を自動生成するかどうかを指定します。true に設定すると、ドキュメント ID はペイロードのハッシュに基づいて生成されます。生成されたドキュメント ID は、複数のインポートで整合性が維持されない場合があります。複数のインポートで ID を自動生成する場合は、ドキュメント ID の整合性を維持するために、reconciliationModeFULL に設定することを強くおすすめします。

      autoGenerateIds は、bigquerySource.dataSchemacustom に設定されている場合にのみ指定します。それ以外の場合は、INVALID_ARGUMENT エラーが返されます。autoGenerateIds を指定しない場合、または false に設定しない場合は、idField を指定する必要があります。そうしないと、ドキュメントのインポートに失敗します。

    • ID_FIELD: 省略可。ドキュメント ID のフィールドを指定します。 BigQuery ソースファイルの場合、idField は、ドキュメント ID を含む BigQuery テーブルの列の名前を示します。

      idField は、(1)bigquerySource.dataSchemacustom に設定されている、および(2)auto_generate_idsfalse に設定されているか、未設定の場合にのみ指定します。それ以外の場合は、INVALID_ARGUMENT エラーが返されます。

      BigQuery 列名の値は文字列型で、1 から 63 文字の範囲で、RFC-1034 に準拠している必要があります。そうしないと、ドキュメントのインポートに失敗します。

C#

詳細については、AI アプリケーション C# API のリファレンス ドキュメントをご覧ください。

AI アプリケーションに対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

データストアを作成

using Google.Cloud.DiscoveryEngine.V1;
using Google.LongRunning;

public sealed partial class GeneratedDataStoreServiceClientSnippets
{
    /// <summary>Snippet for CreateDataStore</summary>
    /// <remarks>
    /// This snippet has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
    /// </remarks>
    public void CreateDataStoreRequestObject()
    {
        // Create client
        DataStoreServiceClient dataStoreServiceClient = DataStoreServiceClient.Create();
        // Initialize request argument(s)
        CreateDataStoreRequest request = new CreateDataStoreRequest
        {
            ParentAsCollectionName = CollectionName.FromProjectLocationCollection("[PROJECT]", "[LOCATION]", "[COLLECTION]"),
            DataStore = new DataStore(),
            DataStoreId = "",
            CreateAdvancedSiteSearch = false,
            CmekConfigNameAsCmekConfigName = CmekConfigName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
            SkipDefaultSchemaCreation = false,
        };
        // Make the request
        Operation<DataStore, CreateDataStoreMetadata> response = dataStoreServiceClient.CreateDataStore(request);

        // Poll until the returned long-running operation is complete
        Operation<DataStore, CreateDataStoreMetadata> completedResponse = response.PollUntilCompleted();
        // Retrieve the operation result
        DataStore result = completedResponse.Result;

        // Or get the name of the operation
        string operationName = response.Name;
        // This name can be stored, then the long-running operation retrieved later by name
        Operation<DataStore, CreateDataStoreMetadata> retrievedResponse = dataStoreServiceClient.PollOnceCreateDataStore(operationName);
        // Check if the retrieved long-running operation has completed
        if (retrievedResponse.IsCompleted)
        {
            // If it has completed, then access the result
            DataStore retrievedResult = retrievedResponse.Result;
        }
    }
}

ドキュメントのインポート

using Google.Cloud.DiscoveryEngine.V1;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;

public sealed partial class GeneratedDocumentServiceClientSnippets
{
    /// <summary>Snippet for ImportDocuments</summary>
    /// <remarks>
    /// This snippet has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
    /// </remarks>
    public void ImportDocumentsRequestObject()
    {
        // Create client
        DocumentServiceClient documentServiceClient = DocumentServiceClient.Create();
        // Initialize request argument(s)
        ImportDocumentsRequest request = new ImportDocumentsRequest
        {
            ParentAsBranchName = BranchName.FromProjectLocationDataStoreBranch("[PROJECT]", "[LOCATION]", "[DATA_STORE]", "[BRANCH]"),
            InlineSource = new ImportDocumentsRequest.Types.InlineSource(),
            ErrorConfig = new ImportErrorConfig(),
            ReconciliationMode = ImportDocumentsRequest.Types.ReconciliationMode.Unspecified,
            UpdateMask = new FieldMask(),
            AutoGenerateIds = false,
            IdField = "",
            ForceRefreshContent = false,
        };
        // Make the request
        Operation<ImportDocumentsResponse, ImportDocumentsMetadata> response = documentServiceClient.ImportDocuments(request);

        // Poll until the returned long-running operation is complete
        Operation<ImportDocumentsResponse, ImportDocumentsMetadata> completedResponse = response.PollUntilCompleted();
        // Retrieve the operation result
        ImportDocumentsResponse result = completedResponse.Result;

        // Or get the name of the operation
        string operationName = response.Name;
        // This name can be stored, then the long-running operation retrieved later by name
        Operation<ImportDocumentsResponse, ImportDocumentsMetadata> retrievedResponse = documentServiceClient.PollOnceImportDocuments(operationName);
        // Check if the retrieved long-running operation has completed
        if (retrievedResponse.IsCompleted)
        {
            // If it has completed, then access the result
            ImportDocumentsResponse retrievedResult = retrievedResponse.Result;
        }
    }
}

Go

詳細については、AI アプリケーション Go API のリファレンス ドキュメントをご覧ください。

AI アプリケーションに対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

データストアを作成


package main

import (
	"context"

	discoveryengine "cloud.google.com/go/discoveryengine/apiv1"
	discoveryenginepb "cloud.google.com/go/discoveryengine/apiv1/discoveryenginepb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := discoveryengine.NewDataStoreClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &discoveryenginepb.CreateDataStoreRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/discoveryengine/apiv1/discoveryenginepb#CreateDataStoreRequest.
	}
	op, err := c.CreateDataStore(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}

	resp, err := op.Wait(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

ドキュメントのインポート


package main

import (
	"context"

	discoveryengine "cloud.google.com/go/discoveryengine/apiv1"
	discoveryenginepb "cloud.google.com/go/discoveryengine/apiv1/discoveryenginepb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := discoveryengine.NewDocumentClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &discoveryenginepb.ImportDocumentsRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/discoveryengine/apiv1/discoveryenginepb#ImportDocumentsRequest.
	}
	op, err := c.ImportDocuments(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}

	resp, err := op.Wait(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

Java

詳細については、AI アプリケーション Java API のリファレンス ドキュメントをご覧ください。

AI アプリケーションに対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

データストアを作成

import com.google.cloud.discoveryengine.v1.CollectionName;
import com.google.cloud.discoveryengine.v1.CreateDataStoreRequest;
import com.google.cloud.discoveryengine.v1.DataStore;
import com.google.cloud.discoveryengine.v1.DataStoreServiceClient;

public class SyncCreateDataStore {

  public static void main(String[] args) throws Exception {
    syncCreateDataStore();
  }

  public static void syncCreateDataStore() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (DataStoreServiceClient dataStoreServiceClient = DataStoreServiceClient.create()) {
      CreateDataStoreRequest request =
          CreateDataStoreRequest.newBuilder()
              .setParent(CollectionName.of("[PROJECT]", "[LOCATION]", "[COLLECTION]").toString())
              .setDataStore(DataStore.newBuilder().build())
              .setDataStoreId("dataStoreId929489618")
              .setCreateAdvancedSiteSearch(true)
              .setSkipDefaultSchemaCreation(true)
              .build();
      DataStore response = dataStoreServiceClient.createDataStoreAsync(request).get();
    }
  }
}

ドキュメントのインポート

import com.google.cloud.discoveryengine.v1.BranchName;
import com.google.cloud.discoveryengine.v1.DocumentServiceClient;
import com.google.cloud.discoveryengine.v1.ImportDocumentsRequest;
import com.google.cloud.discoveryengine.v1.ImportDocumentsResponse;
import com.google.cloud.discoveryengine.v1.ImportErrorConfig;
import com.google.protobuf.FieldMask;

public class SyncImportDocuments {

  public static void main(String[] args) throws Exception {
    syncImportDocuments();
  }

  public static void syncImportDocuments() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (DocumentServiceClient documentServiceClient = DocumentServiceClient.create()) {
      ImportDocumentsRequest request =
          ImportDocumentsRequest.newBuilder()
              .setParent(
                  BranchName.ofProjectLocationDataStoreBranchName(
                          "[PROJECT]", "[LOCATION]", "[DATA_STORE]", "[BRANCH]")
                      .toString())
              .setErrorConfig(ImportErrorConfig.newBuilder().build())
              .setUpdateMask(FieldMask.newBuilder().build())
              .setAutoGenerateIds(true)
              .setIdField("idField1629396127")
              .setForceRefreshContent(true)
              .build();
      ImportDocumentsResponse response = documentServiceClient.importDocumentsAsync(request).get();
    }
  }
}

Node.js

詳細については、AI アプリケーション Node.js API のリファレンス ドキュメントをご覧ください。

AI アプリケーションに対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

データストアを作成

/**
 * This snippet has been automatically generated and should be regarded as a code template only.
 * It will require modifications to work.
 * It may require correct/in-range values for request initialization.
 * TODO(developer): Uncomment these variables before running the sample.
 */
/**
 *  Resource name of the CmekConfig to use for protecting this DataStore.
 */
// const cmekConfigName = 'abc123'
/**
 *  DataStore without CMEK protections. If a default CmekConfig is set for
 *  the project, setting this field will override the default CmekConfig as
 *  well.
 */
// const disableCmek = true
/**
 *  Required. The parent resource name, such as
 *  `projects/{project}/locations/{location}/collections/{collection}`.
 */
// const parent = 'abc123'
/**
 *  Required. The DataStore google.cloud.discoveryengine.v1.DataStore  to
 *  create.
 */
// const dataStore = {}
/**
 *  Required. The ID to use for the
 *  DataStore google.cloud.discoveryengine.v1.DataStore, which will become
 *  the final component of the
 *  DataStore google.cloud.discoveryengine.v1.DataStore's resource name.
 *  This field must conform to RFC-1034 (https://tools.ietf.org/html/rfc1034)
 *  standard with a length limit of 63 characters. Otherwise, an
 *  INVALID_ARGUMENT error is returned.
 */
// const dataStoreId = 'abc123'
/**
 *  A boolean flag indicating whether user want to directly create an advanced
 *  data store for site search.
 *  If the data store is not configured as site
 *  search (GENERIC vertical and PUBLIC_WEBSITE content_config), this flag will
 *  be ignored.
 */
// const createAdvancedSiteSearch = true
/**
 *  A boolean flag indicating whether to skip the default schema creation for
 *  the data store. Only enable this flag if you are certain that the default
 *  schema is incompatible with your use case.
 *  If set to true, you must manually create a schema for the data store before
 *  any documents can be ingested.
 *  This flag cannot be specified if `data_store.starting_schema` is specified.
 */
// const skipDefaultSchemaCreation = true

// Imports the Discoveryengine library
const {DataStoreServiceClient} = require('@google-cloud/discoveryengine').v1;

// Instantiates a client
const discoveryengineClient = new DataStoreServiceClient();

async function callCreateDataStore() {
  // Construct request
  const request = {
    parent,
    dataStore,
    dataStoreId,
  };

  // Run request
  const [operation] = await discoveryengineClient.createDataStore(request);
  const [response] = await operation.promise();
  console.log(response);
}

callCreateDataStore();

ドキュメントのインポート

/**
 * This snippet has been automatically generated and should be regarded as a code template only.
 * It will require modifications to work.
 * It may require correct/in-range values for request initialization.
 * TODO(developer): Uncomment these variables before running the sample.
 */
/**
 *  The Inline source for the input content for documents.
 */
// const inlineSource = {}
/**
 *  Cloud Storage location for the input content.
 */
// const gcsSource = {}
/**
 *  BigQuery input source.
 */
// const bigquerySource = {}
/**
 *  FhirStore input source.
 */
// const fhirStoreSource = {}
/**
 *  Spanner input source.
 */
// const spannerSource = {}
/**
 *  Cloud SQL input source.
 */
// const cloudSqlSource = {}
/**
 *  Firestore input source.
 */
// const firestoreSource = {}
/**
 *  AlloyDB input source.
 */
// const alloyDbSource = {}
/**
 *  Cloud Bigtable input source.
 */
// const bigtableSource = {}
/**
 *  Required. The parent branch resource name, such as
 *  `projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}`.
 *  Requires create/update permission.
 */
// const parent = 'abc123'
/**
 *  The desired location of errors incurred during the Import.
 */
// const errorConfig = {}
/**
 *  The mode of reconciliation between existing documents and the documents to
 *  be imported. Defaults to
 *  ReconciliationMode.INCREMENTAL google.cloud.discoveryengine.v1.ImportDocumentsRequest.ReconciliationMode.INCREMENTAL.
 */
// const reconciliationMode = {}
/**
 *  Indicates which fields in the provided imported documents to update. If
 *  not set, the default is to update all fields.
 */
// const updateMask = {}
/**
 *  Whether to automatically generate IDs for the documents if absent.
 *  If set to `true`,
 *  Document.id google.cloud.discoveryengine.v1.Document.id s are
 *  automatically generated based on the hash of the payload, where IDs may not
 *  be consistent during multiple imports. In which case
 *  ReconciliationMode.FULL google.cloud.discoveryengine.v1.ImportDocumentsRequest.ReconciliationMode.FULL 
 *  is highly recommended to avoid duplicate contents. If unset or set to
 *  `false`, Document.id google.cloud.discoveryengine.v1.Document.id s have
 *  to be specified using
 *  id_field google.cloud.discoveryengine.v1.ImportDocumentsRequest.id_field,
 *  otherwise, documents without IDs fail to be imported.
 *  Supported data sources:
 *  * GcsSource google.cloud.discoveryengine.v1.GcsSource.
 *  GcsSource.data_schema google.cloud.discoveryengine.v1.GcsSource.data_schema 
 *  must be `custom` or `csv`. Otherwise, an INVALID_ARGUMENT error is thrown.
 *  * BigQuerySource google.cloud.discoveryengine.v1.BigQuerySource.
 *  BigQuerySource.data_schema google.cloud.discoveryengine.v1.BigQuerySource.data_schema 
 *  must be `custom` or `csv`. Otherwise, an INVALID_ARGUMENT error is thrown.
 *  * SpannerSource google.cloud.discoveryengine.v1.SpannerSource.
 *  * CloudSqlSource google.cloud.discoveryengine.v1.CloudSqlSource.
 *  * FirestoreSource google.cloud.discoveryengine.v1.FirestoreSource.
 *  * BigtableSource google.cloud.discoveryengine.v1.BigtableSource.
 */
// const autoGenerateIds = true
/**
 *  The field indicates the ID field or column to be used as unique IDs of
 *  the documents.
 *  For GcsSource google.cloud.discoveryengine.v1.GcsSource  it is the key of
 *  the JSON field. For instance, `my_id` for JSON `{"my_id": "some_uuid"}`.
 *  For others, it may be the column name of the table where the unique ids are
 *  stored.
 *  The values of the JSON field or the table column are used as the
 *  Document.id google.cloud.discoveryengine.v1.Document.id s. The JSON field
 *  or the table column must be of string type, and the values must be set as
 *  valid strings conform to RFC-1034 (https://tools.ietf.org/html/rfc1034)
 *  with 1-63 characters. Otherwise, documents without valid IDs fail to be
 *  imported.
 *  Only set this field when
 *  auto_generate_ids google.cloud.discoveryengine.v1.ImportDocumentsRequest.auto_generate_ids 
 *  is unset or set as `false`. Otherwise, an INVALID_ARGUMENT error is thrown.
 *  If it is unset, a default value `_id` is used when importing from the
 *  allowed data sources.
 *  Supported data sources:
 *  * GcsSource google.cloud.discoveryengine.v1.GcsSource.
 *  GcsSource.data_schema google.cloud.discoveryengine.v1.GcsSource.data_schema 
 *  must be `custom` or `csv`. Otherwise, an INVALID_ARGUMENT error is thrown.
 *  * BigQuerySource google.cloud.discoveryengine.v1.BigQuerySource.
 *  BigQuerySource.data_schema google.cloud.discoveryengine.v1.BigQuerySource.data_schema 
 *  must be `custom` or `csv`. Otherwise, an INVALID_ARGUMENT error is thrown.
 *  * SpannerSource google.cloud.discoveryengine.v1.SpannerSource.
 *  * CloudSqlSource google.cloud.discoveryengine.v1.CloudSqlSource.
 *  * FirestoreSource google.cloud.discoveryengine.v1.FirestoreSource.
 *  * BigtableSource google.cloud.discoveryengine.v1.BigtableSource.
 */
// const idField = 'abc123'
/**
 *  Optional. Whether to force refresh the unstructured content of the
 *  documents.
 *  If set to `true`, the content part of the documents will be refreshed
 *  regardless of the update status of the referencing content.
 */
// const forceRefreshContent = true

// Imports the Discoveryengine library
const {DocumentServiceClient} = require('@google-cloud/discoveryengine').v1;

// Instantiates a client
const discoveryengineClient = new DocumentServiceClient();

async function callImportDocuments() {
  // Construct request
  const request = {
    parent,
  };

  // Run request
  const [operation] = await discoveryengineClient.importDocuments(request);
  const [response] = await operation.promise();
  console.log(response);
}

callImportDocuments();

Python

詳細については、AI アプリケーション Python API のリファレンス ドキュメントをご覧ください。

AI アプリケーションに対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

データストアを作成


from google.api_core.client_options import ClientOptions
from google.cloud import discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION" # Values: "global"
# data_store_id = "YOUR_DATA_STORE_ID"


def create_data_store_sample(
    project_id: str,
    location: str,
    data_store_id: str,
) -> str:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
    client_options = (
        ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")
        if location != "global"
        else None
    )

    # Create a client
    client = discoveryengine.DataStoreServiceClient(client_options=client_options)

    # The full resource name of the collection
    # e.g. projects/{project}/locations/{location}/collections/default_collection
    parent = client.collection_path(
        project=project_id,
        location=location,
        collection="default_collection",
    )

    data_store = discoveryengine.DataStore(
        display_name="My Data Store",
        # Options: GENERIC, MEDIA, HEALTHCARE_FHIR
        industry_vertical=discoveryengine.IndustryVertical.GENERIC,
        # Options: SOLUTION_TYPE_RECOMMENDATION, SOLUTION_TYPE_SEARCH, SOLUTION_TYPE_CHAT, SOLUTION_TYPE_GENERATIVE_CHAT
        solution_types=[discoveryengine.SolutionType.SOLUTION_TYPE_SEARCH],
        # TODO(developer): Update content_config based on data store type.
        # Options: NO_CONTENT, CONTENT_REQUIRED, PUBLIC_WEBSITE
        content_config=discoveryengine.DataStore.ContentConfig.CONTENT_REQUIRED,
    )

    request = discoveryengine.CreateDataStoreRequest(
        parent=parent,
        data_store_id=data_store_id,
        data_store=data_store,
        # Optional: For Advanced Site Search Only
        # create_advanced_site_search=True,
    )

    # Make the request
    operation = client.create_data_store(request=request)

    print(f"Waiting for operation to complete: {operation.operation.name}")
    response = operation.result()

    # After the operation is complete,
    # get information from operation metadata
    metadata = discoveryengine.CreateDataStoreMetadata(operation.metadata)

    # Handle the response
    print(response)
    print(metadata)

    return operation.operation.name

ドキュメントのインポート


from google.api_core.client_options import ClientOptions
from google.cloud import discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION" # Values: "global"
# data_store_id = "YOUR_DATA_STORE_ID"
# bigquery_dataset = "YOUR_BIGQUERY_DATASET"
# bigquery_table = "YOUR_BIGQUERY_TABLE"

#  For more information, refer to:
# https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
client_options = (
    ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")
    if location != "global"
    else None
)

# Create a client
client = discoveryengine.DocumentServiceClient(client_options=client_options)

# The full resource name of the search engine branch.
# e.g. projects/{project}/locations/{location}/dataStores/{data_store_id}/branches/{branch}
parent = client.branch_path(
    project=project_id,
    location=location,
    data_store=data_store_id,
    branch="default_branch",
)

request = discoveryengine.ImportDocumentsRequest(
    parent=parent,
    bigquery_source=discoveryengine.BigQuerySource(
        project_id=project_id,
        dataset_id=bigquery_dataset,
        table_id=bigquery_table,
        data_schema="custom",
    ),
    # Options: `FULL`, `INCREMENTAL`
    reconciliation_mode=discoveryengine.ImportDocumentsRequest.ReconciliationMode.INCREMENTAL,
)

# Make the request
operation = client.import_documents(request=request)

print(f"Waiting for operation to complete: {operation.operation.name}")
response = operation.result()

# After the operation is complete,
# get information from operation metadata
metadata = discoveryengine.ImportDocumentsMetadata(operation.metadata)

# Handle the response
print(response)
print(metadata)

Ruby

詳細については、AI アプリケーション Ruby API のリファレンス ドキュメントをご覧ください。

AI アプリケーションに対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

データストアを作成

require "google/cloud/discovery_engine/v1"

##
# Snippet for the create_data_store call in the DataStoreService service
#
# This snippet has been automatically generated and should be regarded as a code
# template only. It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in https://cloud.google.com/ruby/docs/reference.
#
# This is an auto-generated example demonstrating basic usage of
# Google::Cloud::DiscoveryEngine::V1::DataStoreService::Client#create_data_store.
#
def create_data_store
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::DiscoveryEngine::V1::DataStoreService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::DiscoveryEngine::V1::CreateDataStoreRequest.new

  # Call the create_data_store method.
  result = client.create_data_store request

  # The returned object is of type Gapic::Operation. You can use it to
  # check the status of an operation, cancel it, or wait for results.
  # Here is how to wait for a response.
  result.wait_until_done! timeout: 60
  if result.response?
    p result.response
  else
    puts "No response received."
  end
end

ドキュメントのインポート

require "google/cloud/discovery_engine/v1"

##
# Snippet for the import_documents call in the DocumentService service
#
# This snippet has been automatically generated and should be regarded as a code
# template only. It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in https://cloud.google.com/ruby/docs/reference.
#
# This is an auto-generated example demonstrating basic usage of
# Google::Cloud::DiscoveryEngine::V1::DocumentService::Client#import_documents.
#
def import_documents
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::DiscoveryEngine::V1::DocumentService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::DiscoveryEngine::V1::ImportDocumentsRequest.new

  # Call the import_documents method.
  result = client.import_documents request

  # The returned object is of type Gapic::Operation. You can use it to
  # check the status of an operation, cancel it, or wait for results.
  # Here is how to wait for a response.
  result.wait_until_done! timeout: 60
  if result.response?
    p result.response
  else
    puts "No response received."
  end
end

定期的な同期で BigQuery に接続する

データをインポートする前に、取り込むデータを準備します

次の手順では、BigQuery データセットを Vertex AI Search データ コネクタに関連付けるデータ コネクタを作成する方法と、作成するデータストアごとにデータセットのテーブルを指定する方法について説明します。データ コネクタの子データストアは、エンティティ データストアと呼ばれます。

データセットのデータは、エンティティ データストアと定期的に同期されます。同期は、毎日、3 日ごと、5 日ごとに指定できます。

コンソール

Google Cloud コンソールを使用して、BigQuery データセットから Vertex AI Search にデータを定期的に同期するコネクタを作成するには、次の操作を行います。

  1. Google Cloud コンソールで、[AI アプリケーション] ページに移動します。

    AI アプリケーション

  2. ナビゲーション メニューで [データストア] をクリックします。

  3. [データストアを作成] をクリックします。

  4. [ソース] ページで、[BigQuery] を選択します。

  5. インポートするデータの種類を選択します。

  6. [定期] をクリックします。

  7. [同期頻度] で、Vertex AI Search コネクタが BigQuery データセットと同期する頻度を選択します。頻度は後で変更できます。

  8. [BigQuery データセットのパス] フィールドで [参照] をクリックし、取り込み用に準備したテーブルを含むデータセットを選択します。または、[BigQuery パス] フィールドにテーブルの場所を直接入力します。パスの形式は projectname.datasetname です。

  9. [同期するテーブル] フィールドで [参照] をクリックし、データストアに必要なデータを含むテーブルを選択します。

  10. データストアに使用する別のテーブルがデータセット内にある場合は、[テーブルを追加] をクリックして、それらのテーブルも指定します。

  11. [続行] をクリックします。

  12. データストアのリージョンを選択し、データ コネクタの名前を入力して、[作成] をクリックします。

    これで、BigQuery データセットとデータを定期的に同期するデータコネクタが作成されました。また、1 つ以上のエンティティ データストアを作成しています。データストアの名前は BigQuery テーブルと同じです。

  13. 取り込みのステータスを確認するには、[データストア] ページに移動し、データ接続名をクリックして、[データ] ページ > [データ取り込みアクティビティ] タブで詳細を表示します。[アクティビティ] タブのステータス列が [進行中] から [成功] に変わると、最初の取り込みが完了します。

    取り込みには、データのサイズに応じて、数分から数時間かかることがあります。

データソースを設定してデータを初めてインポートすると、データストアは設定時に選択した頻度でそのソースからデータを同期します。 データコネクタの作成から約 1 時間後に、最初の同期が行われます。 次回の同期は、24 時間、72 時間、または 120 時間後に行われます。

次のステップ

Cloud Storage

Cloud Storage テーブルからデータストアを作成するには、次の 2 つの方法があります。

  • 1 回限りのデータ取り込み: Cloud Storage のフォルダまたはファイルからデータストアにデータをインポートします。データストア内のデータは、手動でデータを更新しない限り変更されません。

  • 定期的な取り込み: Cloud Storage フォルダまたはファイルからデータをインポートし、同期頻度を設定して、その Cloud Storage ロケーションの最新データでデータストアが更新される頻度を決定します。

次の表は、Cloud Storage データを Vertex AI Search データストアにインポートする 2 つの方法を比較したものです。

1 回限りの取り込み 定期的な取り込み
一般提供(GA)。 公開プレビュー版。
データは手動で更新する必要があります。 データは 1 日、3 日、5 日ごとに自動的に更新されます。データを手動で更新することはできません。
Vertex AI Search は、Cloud Storage の 1 つのフォルダまたはファイルから単一のデータストアを作成します。 Vertex AI Search はデータコネクタを作成し、指定されたファイルまたはフォルダにデータストア(エンティティ データストア)を関連付けます。各 Cloud Storage データコネクタには、単一のエンティティ データストアを設定できます。
複数のファイル、フォルダ、バケットのデータを 1 つのデータストアに結合するには、まず 1 つの Cloud Storage ロケーションからデータを取り込み、次に別のロケーションからデータを取り込みます。 手動データ インポートはサポートされていないため、エンティティ データストアのデータは 1 つの Cloud Storage ファイルまたはフォルダからのみ取得できます。
データソースへのアクセス制御がサポートされています。詳細については、データソースのアクセス制御をご覧ください。 データソースへのアクセス制御はサポートされていません。インポートされたデータにアクセス制御を含めることはできますが、これらの制御は適用されません。
データストアは、Google Cloud コンソールまたは API を使用して作成できます。 データ コネクタとそのエンティティ データストアは、コンソールを使用して作成する必要があります。
CMEK 準拠。 CMEK 準拠。

Cloud Storage から 1 回インポートする

Cloud Storage からデータを取り込むには、次の手順でデータストアを作成し、 Google Cloud コンソールまたは API を使用してデータを取り込みます。

データをインポートする前に、取り込むデータを準備します

Console

コンソールを使用して Cloud Storage バケットからデータを取り込む手順は次のとおりです。

  1. Google Cloud コンソールで、[AI アプリケーション] ページに移動します。

    AI アプリケーション

  2. [データストア] ページに移動します。

  3. [データストアを作成] をクリックします。

  4. [ソース] ページで、[Cloud Storage] を選択します。

  5. [インポートするフォルダまたはファイルを選択] セクションで、[フォルダ] または [ファイル] を選択します。

  6. [参照] をクリックして、取り込み用に準備したデータを選択し、[選択] をクリックします。 または、[gs://] フィールドにロケーションを直接入力します。

  7. インポートするデータの種類を選択します。

  8. [続行] をクリックします。

  9. 構造化データを 1 回限りインポートする場合:

    1. フィールドをキー プロパティにマッピングします。

    2. スキーマに重要なフィールドが欠落している場合は、[新しいフィールドを追加] を使用して追加します。

      詳細については、自動検出と編集についてをご覧ください。

    3. [続行] をクリックします。

  10. データストアのリージョンを選択します。

  11. データストアの名前を入力します。

  12. 省略可: 非構造化ドキュメントを選択した場合は、ドキュメントの解析とチャンキングのオプションを選択できます。パーサーを比較するには、ドキュメントを解析するをご覧ください。チャンク処理の詳細については、RAG 用にドキュメントをチャンクするをご覧ください。

    OCR パーサーとレイアウト パーサーを使用すると、追加費用が発生する場合があります。Document AI 機能の料金をご覧ください。

    パーサーを選択するには、[ドキュメント処理オプション] を開き、使用するパーサー オプションを指定します。

  13. [作成] をクリックします。

  14. 取り込みのステータスを確認するには、[データストア] ページに移動し、データストア名をクリックして、[データ] ページで詳細を表示します。 [アクティビティ] タブのステータス列が [進行中] から [インポート完了] に変わると、取り込みが完了します。

    取り込みには、データのサイズに応じて、数分から数時間かかることがあります。

REST

コマンドラインを使用してデータストアを作成し、Cloud Storage からデータを取り込む手順は次のとおりです。

  1. データストアを作成します。

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    -H "X-Goog-User-Project: PROJECT_ID" \
    "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/dataStores?dataStoreId=DATA_STORE_ID" \
    -d '{
      "displayName": "DATA_STORE_DISPLAY_NAME",
      "industryVertical": "GENERIC",
      "solutionTypes": ["SOLUTION_TYPE_RECOMMENDATION"]
    }'
    

    次のように置き換えます。

    • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
    • DATA_STORE_ID: 作成する Vertex AI Search データストアの ID。この ID に使用できるのは、小文字、数字、アンダースコア、ハイフンのみです。
    • DATA_STORE_DISPLAY_NAME: 作成する Vertex AI Search データストアの表示名。
  2. Cloud Storage からデータをインポートします。

      curl -X POST \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/dataStores/DATA_STORE_ID/branches/0/documents:import" \
      -d '{
        "gcsSource": {
          "inputUris": ["INPUT_FILE_PATTERN_1", "INPUT_FILE_PATTERN_2"],
          "dataSchema": "DATA_SCHEMA",
        },
        "reconciliationMode": "RECONCILIATION_MODE",
        "autoGenerateIds": "AUTO_GENERATE_IDS",
        "idField": "ID_FIELD",
        "errorConfig": {
          "gcsPrefix": "ERROR_DIRECTORY"
        }
      }'
    

    次のように置き換えます。

    • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
    • DATA_STORE_ID: Vertex AI Search データストアの ID。
    • INPUT_FILE_PATTERN: ドキュメントを含む Cloud Storage 内のファイル パターン。

      構造化データまたはメタデータを含む非構造化データの場合、入力ファイル パターンの例は gs://<your-gcs-bucket>/directory/object.json で、1 つ以上のファイルにパターン マッチングする例は gs://<your-gcs-bucket>/directory/*.json です。

      非構造化ドキュメントの場合、例は gs://<your-gcs-bucket>/directory/*.pdf です。パターンに一致する各ファイルがドキュメントになります。

      <your-gcs-bucket>PROJECT_ID にない場合は、サービス アカウント service-<project number>@gcp-sa-discoveryengine.iam.gserviceaccount.com に Cloud Storage バケットに対する「ストレージ オブジェクト閲覧者」権限を付与する必要があります。たとえば、ソース プロジェクト「123」から宛先プロジェクト「456」に Cloud Storage バケットをインポートする場合は、プロジェクト「123」の Cloud Storage バケットに対する [email protected] 権限を付与します。

    • DATA_SCHEMA: 省略可。値は documentcustomcsv および content です。デフォルトは document です。

      • document: 構造化されていないドキュメントのメタデータを含む非構造化データをアップロードします。ファイルの各行は、次のいずれかの形式にする必要があります。各ドキュメントの ID を定義できます。

        • { "id": "<your-id>", "jsonData": "<JSON string>", "content": { "mimeType": "<application/pdf or text/html>", "uri": "gs://<your-gcs-bucket>/directory/filename.pdf" } }
        • { "id": "<your-id>", "structData": <JSON object>, "content": { "mimeType": "<application/pdf or text/html>", "uri": "gs://<your-gcs-bucket>/directory/filename.pdf" } }
      • custom: 構造化ドキュメントの JSON をアップロードします。データはスキーマに従って編成されます。スキーマを指定することもできます。指定しない場合、スキーマは自動的に検出されます。ドキュメントの JSON 文字列を一貫した形式で各行に直接配置できます。Vertex AI Search は、インポートされた各ドキュメントの ID を自動的に生成します。

      • content: 非構造化ドキュメント(PDF、HTML、DOC、TXT、PPTX)をアップロードします。各ドキュメントの ID は、SHA256(GCS_URI) の最初の 128 ビットが 16 進数文字列としてエンコードされたものとして自動的に生成されます。一致するファイルが 10 万ファイルの制限を超えない限り、複数の入力ファイル パターンを指定できます。

      • csv: CSV ファイルにヘッダー行を含め、各ヘッダーをドキュメント フィールドにマッピングします。inputUris フィールドを使用して、CSV ファイルのパスを指定します。

    • ERROR_DIRECTORY: 省略可。インポートに関するエラー情報用の Cloud Storage ディレクトリ(例: gs://<your-gcs-bucket>/directory/import_errors)。Vertex AI Search に一時ディレクトリを自動的に作成させるには、この項目を空のままにすることをおすすめします。

    • RECONCILIATION_MODE: 省略可。値は FULL および INCREMENTAL です。デフォルトは INCREMENTAL です。INCREMENTAL を指定すると、Cloud Storage からデータストアへのデータの増分更新が行われます。これにより、アップサート オペレーションが実行され、新しいドキュメントを追加し、既存のドキュメントを更新された同じ ID のドキュメントで置き換えます。FULL を指定すると、データストア内のドキュメントが完全に再ベース化されます。つまり、新しいドキュメントと更新されたドキュメントがデータストアに追加され、Cloud Storage にないドキュメントがデータストアから削除されます。FULL モードは、不要になったドキュメントを自動的に削除する場合に便利です。

    • AUTO_GENERATE_IDS: 省略可。ドキュメント ID を自動生成するかどうかを指定します。true に設定すると、ドキュメント ID はペイロードのハッシュに基づいて生成されます。生成されたドキュメント ID は、複数のインポートで整合性が維持されない場合があります。複数のインポートで ID を自動生成する場合は、ドキュメント ID の整合性を維持するために、reconciliationModeFULL に設定することを強くおすすめします。

      autoGenerateIds は、gcsSource.dataSchemacustom または csv に設定されている場合にのみ指定します。それ以外の場合は、INVALID_ARGUMENT エラーが返されます。autoGenerateIds を指定しない場合、または false に設定しない場合は、idField を指定する必要があります。そうしないと、ドキュメントのインポートに失敗します。

    • ID_FIELD: 省略可。ドキュメント ID のフィールドを指定します。 Cloud Storage ソースドキュメントの場合、idField はドキュメント ID である JSON フィールドの名前を指定します。たとえば、{"my_id":"some_uuid"} がドキュメントの 1 つのドキュメント ID フィールドの場合は、"idField":"my_id" を指定します。これにより、"my_id" という名前のすべての JSON フィールドがドキュメント ID として識別されます。

      gcsSource.dataSchema は、(1)customcsv に設定されている、および(2)auto_generate_idsfalse に設定されているか、未設定の場合にのみ指定します。それ以外の場合は、INVALID_ARGUMENT エラーが返されます。

      Cloud Storage JSON フィールドの値は、文字列型で、1 から 63 文字の範囲で、RFC-1034 に準拠している必要があります。そうしないと、ドキュメントのインポートに失敗します。

      id_field で指定された JSON フィールド名は、文字列型で、1 から 63 文字の範囲で、RFC-1034 に準拠している必要があります。そうしないと、ドキュメントのインポートに失敗します。

C#

詳細については、AI アプリケーション C# API のリファレンス ドキュメントをご覧ください。

AI アプリケーションに対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

データストアを作成

using Google.Cloud.DiscoveryEngine.V1;
using Google.LongRunning;

public sealed partial class GeneratedDataStoreServiceClientSnippets
{
    /// <summary>Snippet for CreateDataStore</summary>
    /// <remarks>
    /// This snippet has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
    /// </remarks>
    public void CreateDataStoreRequestObject()
    {
        // Create client
        DataStoreServiceClient dataStoreServiceClient = DataStoreServiceClient.Create();
        // Initialize request argument(s)
        CreateDataStoreRequest request = new CreateDataStoreRequest
        {
            ParentAsCollectionName = CollectionName.FromProjectLocationCollection("[PROJECT]", "[LOCATION]", "[COLLECTION]"),
            DataStore = new DataStore(),
            DataStoreId = "",
            CreateAdvancedSiteSearch = false,
            CmekConfigNameAsCmekConfigName = CmekConfigName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
            SkipDefaultSchemaCreation = false,
        };
        // Make the request
        Operation<DataStore, CreateDataStoreMetadata> response = dataStoreServiceClient.CreateDataStore(request);

        // Poll until the returned long-running operation is complete
        Operation<DataStore, CreateDataStoreMetadata> completedResponse = response.PollUntilCompleted();
        // Retrieve the operation result
        DataStore result = completedResponse.Result;

        // Or get the name of the operation
        string operationName = response.Name;
        // This name can be stored, then the long-running operation retrieved later by name
        Operation<DataStore, CreateDataStoreMetadata> retrievedResponse = dataStoreServiceClient.PollOnceCreateDataStore(operationName);
        // Check if the retrieved long-running operation has completed
        if (retrievedResponse.IsCompleted)
        {
            // If it has completed, then access the result
            DataStore retrievedResult = retrievedResponse.Result;
        }
    }
}

ドキュメントのインポート

using Google.Cloud.DiscoveryEngine.V1;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;

public sealed partial class GeneratedDocumentServiceClientSnippets
{
    /// <summary>Snippet for ImportDocuments</summary>
    /// <remarks>
    /// This snippet has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
    /// </remarks>
    public void ImportDocumentsRequestObject()
    {
        // Create client
        DocumentServiceClient documentServiceClient = DocumentServiceClient.Create();
        // Initialize request argument(s)
        ImportDocumentsRequest request = new ImportDocumentsRequest
        {
            ParentAsBranchName = BranchName.FromProjectLocationDataStoreBranch("[PROJECT]", "[LOCATION]", "[DATA_STORE]", "[BRANCH]"),
            InlineSource = new ImportDocumentsRequest.Types.InlineSource(),
            ErrorConfig = new ImportErrorConfig(),
            ReconciliationMode = ImportDocumentsRequest.Types.ReconciliationMode.Unspecified,
            UpdateMask = new FieldMask(),
            AutoGenerateIds = false,
            IdField = "",
            ForceRefreshContent = false,
        };
        // Make the request
        Operation<ImportDocumentsResponse, ImportDocumentsMetadata> response = documentServiceClient.ImportDocuments(request);

        // Poll until the returned long-running operation is complete
        Operation<ImportDocumentsResponse, ImportDocumentsMetadata> completedResponse = response.PollUntilCompleted();
        // Retrieve the operation result
        ImportDocumentsResponse result = completedResponse.Result;

        // Or get the name of the operation
        string operationName = response.Name;
        // This name can be stored, then the long-running operation retrieved later by name
        Operation<ImportDocumentsResponse, ImportDocumentsMetadata> retrievedResponse = documentServiceClient.PollOnceImportDocuments(operationName);
        // Check if the retrieved long-running operation has completed
        if (retrievedResponse.IsCompleted)
        {
            // If it has completed, then access the result
            ImportDocumentsResponse retrievedResult = retrievedResponse.Result;
        }
    }
}

Go

詳細については、AI アプリケーション Go API のリファレンス ドキュメントをご覧ください。

AI アプリケーションに対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

データストアを作成


package main

import (
	"context"

	discoveryengine "cloud.google.com/go/discoveryengine/apiv1"
	discoveryenginepb "cloud.google.com/go/discoveryengine/apiv1/discoveryenginepb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := discoveryengine.NewDataStoreClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &discoveryenginepb.CreateDataStoreRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/discoveryengine/apiv1/discoveryenginepb#CreateDataStoreRequest.
	}
	op, err := c.CreateDataStore(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}

	resp, err := op.Wait(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

ドキュメントのインポート


package main

import (
	"context"

	discoveryengine "cloud.google.com/go/discoveryengine/apiv1"
	discoveryenginepb "cloud.google.com/go/discoveryengine/apiv1/discoveryenginepb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := discoveryengine.NewDocumentClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &discoveryenginepb.ImportDocumentsRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/discoveryengine/apiv1/discoveryenginepb#ImportDocumentsRequest.
	}
	op, err := c.ImportDocuments(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}

	resp, err := op.Wait(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

Java

詳細については、AI アプリケーション Java API のリファレンス ドキュメントをご覧ください。

AI アプリケーションに対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

データストアを作成

import com.google.cloud.discoveryengine.v1.CollectionName;
import com.google.cloud.discoveryengine.v1.CreateDataStoreRequest;
import com.google.cloud.discoveryengine.v1.DataStore;
import com.google.cloud.discoveryengine.v1.DataStoreServiceClient;

public class SyncCreateDataStore {

  public static void main(String[] args) throws Exception {
    syncCreateDataStore();
  }

  public static void syncCreateDataStore() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (DataStoreServiceClient dataStoreServiceClient = DataStoreServiceClient.create()) {
      CreateDataStoreRequest request =
          CreateDataStoreRequest.newBuilder()
              .setParent(CollectionName.of("[PROJECT]", "[LOCATION]", "[COLLECTION]").toString())
              .setDataStore(DataStore.newBuilder().build())
              .setDataStoreId("dataStoreId929489618")
              .setCreateAdvancedSiteSearch(true)
              .setSkipDefaultSchemaCreation(true)
              .build();
      DataStore response = dataStoreServiceClient.createDataStoreAsync(request).get();
    }
  }
}

ドキュメントのインポート

import com.google.cloud.discoveryengine.v1.BranchName;
import com.google.cloud.discoveryengine.v1.DocumentServiceClient;
import com.google.cloud.discoveryengine.v1.ImportDocumentsRequest;
import com.google.cloud.discoveryengine.v1.ImportDocumentsResponse;
import com.google.cloud.discoveryengine.v1.ImportErrorConfig;
import com.google.protobuf.FieldMask;

public class SyncImportDocuments {

  public static void main(String[] args) throws Exception {
    syncImportDocuments();
  }

  public static void syncImportDocuments() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (DocumentServiceClient documentServiceClient = DocumentServiceClient.create()) {
      ImportDocumentsRequest request =
          ImportDocumentsRequest.newBuilder()
              .setParent(
                  BranchName.ofProjectLocationDataStoreBranchName(
                          "[PROJECT]", "[LOCATION]", "[DATA_STORE]", "[BRANCH]")
                      .toString())
              .setErrorConfig(ImportErrorConfig.newBuilder().build())
              .setUpdateMask(FieldMask.newBuilder().build())
              .setAutoGenerateIds(true)
              .setIdField("idField1629396127")
              .setForceRefreshContent(true)
              .build();
      ImportDocumentsResponse response = documentServiceClient.importDocumentsAsync(request).get();
    }
  }
}

Node.js

詳細については、AI アプリケーション Node.js API のリファレンス ドキュメントをご覧ください。

AI アプリケーションに対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

データストアを作成

/**
 * This snippet has been automatically generated and should be regarded as a code template only.
 * It will require modifications to work.
 * It may require correct/in-range values for request initialization.
 * TODO(developer): Uncomment these variables before running the sample.
 */
/**
 *  Resource name of the CmekConfig to use for protecting this DataStore.
 */
// const cmekConfigName = 'abc123'
/**
 *  DataStore without CMEK protections. If a default CmekConfig is set for
 *  the project, setting this field will override the default CmekConfig as
 *  well.
 */
// const disableCmek = true
/**
 *  Required. The parent resource name, such as
 *  `projects/{project}/locations/{location}/collections/{collection}`.
 */
// const parent = 'abc123'
/**
 *  Required. The DataStore google.cloud.discoveryengine.v1.DataStore  to
 *  create.
 */
// const dataStore = {}
/**
 *  Required. The ID to use for the
 *  DataStore google.cloud.discoveryengine.v1.DataStore, which will become
 *  the final component of the
 *  DataStore google.cloud.discoveryengine.v1.DataStore's resource name.
 *  This field must conform to RFC-1034 (https://tools.ietf.org/html/rfc1034)
 *  standard with a length limit of 63 characters. Otherwise, an
 *  INVALID_ARGUMENT error is returned.
 */
// const dataStoreId = 'abc123'
/**
 *  A boolean flag indicating whether user want to directly create an advanced
 *  data store for site search.
 *  If the data store is not configured as site
 *  search (GENERIC vertical and PUBLIC_WEBSITE content_config), this flag will
 *  be ignored.
 */
// const createAdvancedSiteSearch = true
/**
 *  A boolean flag indicating whether to skip the default schema creation for
 *  the data store. Only enable this flag if you are certain that the default
 *  schema is incompatible with your use case.
 *  If set to true, you must manually create a schema for the data store before
 *  any documents can be ingested.
 *  This flag cannot be specified if `data_store.starting_schema` is specified.
 */
// const skipDefaultSchemaCreation = true

// Imports the Discoveryengine library
const {DataStoreServiceClient} = require('@google-cloud/discoveryengine').v1;

// Instantiates a client
const discoveryengineClient = new DataStoreServiceClient();

async function callCreateDataStore() {
  // Construct request
  const request = {
    parent,
    dataStore,
    dataStoreId,
  };

  // Run request
  const [operation] = await discoveryengineClient.createDataStore(request);
  const [response] = await operation.promise();
  console.log(response);
}

callCreateDataStore();

ドキュメントのインポート

/**
 * This snippet has been automatically generated and should be regarded as a code template only.
 * It will require modifications to work.
 * It may require correct/in-range values for request initialization.
 * TODO(developer): Uncomment these variables before running the sample.
 */
/**
 *  The Inline source for the input content for documents.
 */
// const inlineSource = {}
/**
 *  Cloud Storage location for the input content.
 */
// const gcsSource = {}
/**
 *  BigQuery input source.
 */
// const bigquerySource = {}
/**
 *  FhirStore input source.
 */
// const fhirStoreSource = {}
/**
 *  Spanner input source.
 */
// const spannerSource = {}
/**
 *  Cloud SQL input source.
 */
// const cloudSqlSource = {}
/**
 *  Firestore input source.
 */
// const firestoreSource = {}
/**
 *  AlloyDB input source.
 */
// const alloyDbSource = {}
/**
 *  Cloud Bigtable input source.
 */
// const bigtableSource = {}
/**
 *  Required. The parent branch resource name, such as
 *  `projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store}/branches/{branch}`.
 *  Requires create/update permission.
 */
// const parent = 'abc123'
/**
 *  The desired location of errors incurred during the Import.
 */
// const errorConfig = {}
/**
 *  The mode of reconciliation between existing documents and the documents to
 *  be imported. Defaults to
 *  ReconciliationMode.INCREMENTAL google.cloud.discoveryengine.v1.ImportDocumentsRequest.ReconciliationMode.INCREMENTAL.
 */
// const reconciliationMode = {}
/**
 *  Indicates which fields in the provided imported documents to update. If
 *  not set, the default is to update all fields.
 */
// const updateMask = {}
/**
 *  Whether to automatically generate IDs for the documents if absent.
 *  If set to `true`,
 *  Document.id google.cloud.discoveryengine.v1.Document.id s are
 *  automatically generated based on the hash of the payload, where IDs may not
 *  be consistent during multiple imports. In which case
 *  ReconciliationMode.FULL google.cloud.discoveryengine.v1.ImportDocumentsRequest.ReconciliationMode.FULL 
 *  is highly recommended to avoid duplicate contents. If unset or set to
 *  `false`, Document.id google.cloud.discoveryengine.v1.Document.id s have
 *  to be specified using
 *  id_field google.cloud.discoveryengine.v1.ImportDocumentsRequest.id_field,
 *  otherwise, documents without IDs fail to be imported.
 *  Supported data sources:
 *  * GcsSource google.cloud.discoveryengine.v1.GcsSource.
 *  GcsSource.data_schema google.cloud.discoveryengine.v1.GcsSource.data_schema 
 *  must be `custom` or `csv`. Otherwise, an INVALID_ARGUMENT error is thrown.
 *  * BigQuerySource google.cloud.discoveryengine.v1.BigQuerySource.
 *  BigQuerySource.data_schema google.cloud.discoveryengine.v1.BigQuerySource.data_schema 
 *  must be `custom` or `csv`. Otherwise, an INVALID_ARGUMENT error is thrown.
 *  * SpannerSource google.cloud.discoveryengine.v1.SpannerSource.
 *  * CloudSqlSource google.cloud.discoveryengine.v1.CloudSqlSource.
 *  * FirestoreSource google.cloud.discoveryengine.v1.FirestoreSource.
 *  * BigtableSource google.cloud.discoveryengine.v1.BigtableSource.
 */
// const autoGenerateIds = true
/**
 *  The field indicates the ID field or column to be used as unique IDs of
 *  the documents.
 *  For GcsSource google.cloud.discoveryengine.v1.GcsSource  it is the key of
 *  the JSON field. For instance, `my_id` for JSON `{"my_id": "some_uuid"}`.
 *  For others, it may be the column name of the table where the unique ids are
 *  stored.
 *  The values of the JSON field or the table column are used as the
 *  Document.id google.cloud.discoveryengine.v1.Document.id s. The JSON field
 *  or the table column must be of string type, and the values must be set as
 *  valid strings conform to RFC-1034 (https://tools.ietf.org/html/rfc1034)
 *  with 1-63 characters. Otherwise, documents without valid IDs fail to be
 *  imported.
 *  Only set this field when
 *  auto_generate_ids google.cloud.discoveryengine.v1.ImportDocumentsRequest.auto_generate_ids 
 *  is unset or set as `false`. Otherwise, an INVALID_ARGUMENT error is thrown.
 *  If it is unset, a default value `_id` is used when importing from the
 *  allowed data sources.
 *  Supported data sources:
 *  * GcsSource google.cloud.discoveryengine.v1.GcsSource.
 *  GcsSource.data_schema google.cloud.discoveryengine.v1.GcsSource.data_schema 
 *  must be `custom` or `csv`. Otherwise, an INVALID_ARGUMENT error is thrown.
 *  * BigQuerySource google.cloud.discoveryengine.v1.BigQuerySource.
 *  BigQuerySource.data_schema google.cloud.discoveryengine.v1.BigQuerySource.data_schema 
 *  must be `custom` or `csv`. Otherwise, an INVALID_ARGUMENT error is thrown.
 *  * SpannerSource google.cloud.discoveryengine.v1.SpannerSource.
 *  * CloudSqlSource google.cloud.discoveryengine.v1.CloudSqlSource.
 *  * FirestoreSource google.cloud.discoveryengine.v1.FirestoreSource.
 *  * BigtableSource google.cloud.discoveryengine.v1.BigtableSource.
 */
// const idField = 'abc123'
/**
 *  Optional. Whether to force refresh the unstructured content of the
 *  documents.
 *  If set to `true`, the content part of the documents will be refreshed
 *  regardless of the update status of the referencing content.
 */
// const forceRefreshContent = true

// Imports the Discoveryengine library
const {DocumentServiceClient} = require('@google-cloud/discoveryengine').v1;

// Instantiates a client
const discoveryengineClient = new DocumentServiceClient();

async function callImportDocuments() {
  // Construct request
  const request = {
    parent,
  };

  // Run request
  const [operation] = await discoveryengineClient.importDocuments(request);
  const [response] = await operation.promise();
  console.log(response);
}

callImportDocuments();

Python

詳細については、AI アプリケーション Python API のリファレンス ドキュメントをご覧ください。

AI アプリケーションに対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

データストアを作成


from google.api_core.client_options import ClientOptions
from google.cloud import discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION" # Values: "global"
# data_store_id = "YOUR_DATA_STORE_ID"


def create_data_store_sample(
    project_id: str,
    location: str,
    data_store_id: str,
) -> str:
    #  For more information, refer to:
    # https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
    client_options = (
        ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")
        if location != "global"
        else None
    )

    # Create a client
    client = discoveryengine.DataStoreServiceClient(client_options=client_options)

    # The full resource name of the collection
    # e.g. projects/{project}/locations/{location}/collections/default_collection
    parent = client.collection_path(
        project=project_id,
        location=location,
        collection="default_collection",
    )

    data_store = discoveryengine.DataStore(
        display_name="My Data Store",
        # Options: GENERIC, MEDIA, HEALTHCARE_FHIR
        industry_vertical=discoveryengine.IndustryVertical.GENERIC,
        # Options: SOLUTION_TYPE_RECOMMENDATION, SOLUTION_TYPE_SEARCH, SOLUTION_TYPE_CHAT, SOLUTION_TYPE_GENERATIVE_CHAT
        solution_types=[discoveryengine.SolutionType.SOLUTION_TYPE_SEARCH],
        # TODO(developer): Update content_config based on data store type.
        # Options: NO_CONTENT, CONTENT_REQUIRED, PUBLIC_WEBSITE
        content_config=discoveryengine.DataStore.ContentConfig.CONTENT_REQUIRED,
    )

    request = discoveryengine.CreateDataStoreRequest(
        parent=parent,
        data_store_id=data_store_id,
        data_store=data_store,
        # Optional: For Advanced Site Search Only
        # create_advanced_site_search=True,
    )

    # Make the request
    operation = client.create_data_store(request=request)

    print(f"Waiting for operation to complete: {operation.operation.name}")
    response = operation.result()

    # After the operation is complete,
    # get information from operation metadata
    metadata = discoveryengine.CreateDataStoreMetadata(operation.metadata)

    # Handle the response
    print(response)
    print(metadata)

    return operation.operation.name

ドキュメントのインポート

from google.api_core.client_options import ClientOptions
from google.cloud import discoveryengine

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION" # Values: "global"
# data_store_id = "YOUR_DATA_STORE_ID"

# Examples:
# - Unstructured documents
#   - `gs://bucket/directory/file.pdf`
#   - `gs://bucket/directory/*.pdf`
# - Unstructured documents with JSONL Metadata
#   - `gs://bucket/directory/file.json`
# - Unstructured documents with CSV Metadata
#   - `gs://bucket/directory/file.csv`
# gcs_uri = "YOUR_GCS_PATH"

#  For more information, refer to:
# https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
client_options = (
    ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")
    if location != "global"
    else None
)

# Create a client
client = discoveryengine.DocumentServiceClient(client_options=client_options)

# The full resource name of the search engine branch.
# e.g. projects/{project}/locations/{location}/dataStores/{data_store_id}/branches/{branch}
parent = client.branch_path(
    project=project_id,
    location=location,
    data_store=data_store_id,
    branch="default_branch",
)

request = discoveryengine.ImportDocumentsRequest(
    parent=parent,
    gcs_source=discoveryengine.GcsSource(
        # Multiple URIs are supported
        input_uris=[gcs_uri],
        # Options:
        # - `content` - Unstructured documents (PDF, HTML, DOC, TXT, PPTX)
        # - `custom` - Unstructured documents with custom JSONL metadata
        # - `document` - Structured documents in the discoveryengine.Document format.
        # - `csv` - Unstructured documents with CSV metadata
        data_schema="content",
    ),
    # Options: `FULL`, `INCREMENTAL`
    reconciliation_mode=discoveryengine.ImportDocumentsRequest.ReconciliationMode.INCREMENTAL,
)

# Make the request
operation = client.import_documents(request=request)

print(f"Waiting for operation to complete: {operation.operation.name}")
response = operation.result()

# After the operation is complete,
# get information from operation metadata
metadata = discoveryengine.ImportDocumentsMetadata(operation.metadata)

# Handle the response
print(response)
print(metadata)

Ruby

詳細については、AI アプリケーション Ruby API のリファレンス ドキュメントをご覧ください。

AI アプリケーションに対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

データストアを作成

require "google/cloud/discovery_engine/v1"

##
# Snippet for the create_data_store call in the DataStoreService service
#
# This snippet has been automatically generated and should be regarded as a code
# template only. It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in https://cloud.google.com/ruby/docs/reference.
#
# This is an auto-generated example demonstrating basic usage of
# Google::Cloud::DiscoveryEngine::V1::DataStoreService::Client#create_data_store.
#
def create_data_store
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::DiscoveryEngine::V1::DataStoreService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::DiscoveryEngine::V1::CreateDataStoreRequest.new

  # Call the create_data_store method.
  result = client.create_data_store request

  # The returned object is of type Gapic::Operation. You can use it to
  # check the status of an operation, cancel it, or wait for results.
  # Here is how to wait for a response.
  result.wait_until_done! timeout: 60
  if result.response?
    p result.response
  else
    puts "No response received."
  end
end

ドキュメントのインポート

require "google/cloud/discovery_engine/v1"

##
# Snippet for the import_documents call in the DocumentService service
#
# This snippet has been automatically generated and should be regarded as a code
# template only. It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in https://cloud.google.com/ruby/docs/reference.
#
# This is an auto-generated example demonstrating basic usage of
# Google::Cloud::DiscoveryEngine::V1::DocumentService::Client#import_documents.
#
def import_documents
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::DiscoveryEngine::V1::DocumentService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::DiscoveryEngine::V1::ImportDocumentsRequest.new

  # Call the import_documents method.
  result = client.import_documents request

  # The returned object is of type Gapic::Operation. You can use it to
  # check the status of an operation, cancel it, or wait for results.
  # Here is how to wait for a response.
  result.wait_until_done! timeout: 60
  if result.response?
    p result.response
  else
    puts "No response received."
  end
end

定期的な同期で Cloud Storage に接続する

データをインポートする前に、取り込むデータを準備します

次の手順では、Cloud Storage のロケーションを Vertex AI Search データコネクタに関連付けるデータコネクタを作成する方法と、作成するデータストアのロケーションにあるフォルダまたはファイルを指定する方法について説明します。データ コネクタの子データストアは、エンティティ データストアと呼ばれます。

データはエンティティ データストアに定期的に同期されます。同期は、毎日、3 日ごと、5 日ごとに指定できます。

コンソール

  1. Google Cloud コンソールで、[AI アプリケーション] ページに移動します。

    AI アプリケーション

  2. [データストア] ページに移動します。

  3. [データストアを作成] をクリックします。

  4. [ソース] ページで、[Cloud Storage] を選択します。

  5. インポートするデータの種類を選択します。

  6. [定期] をクリックします。

  7. [同期頻度] で、Vertex AI Search コネクタが Cloud Storage ロケーションと同期する頻度を選択します。頻度は後で変更できます。

  8. [インポートするフォルダまたはファイルを選択] セクションで、[フォルダ] または [ファイル] を選択します。

  9. [参照] をクリックして、取り込み用に準備したデータを選択し、[選択] をクリックします。 または、[gs://] フィールドにロケーションを直接入力します。

  10. [続行] をクリックします。

  11. データ コネクタのリージョンを選択します。

  12. データコネクタの名前を入力します。

  13. 省略可: 非構造化ドキュメントを選択した場合は、ドキュメントの解析とチャンキングのオプションを選択できます。パーサーを比較するには、ドキュメントを解析するをご覧ください。チャンク処理の詳細については、RAG 用にドキュメントをチャンクするをご覧ください。

    OCR パーサーとレイアウト パーサーを使用すると、追加費用が発生する場合があります。Document AI 機能の料金をご覧ください。

    パーサーを選択するには、[ドキュメント処理オプション] を開き、使用するパーサー オプションを指定します。

  14. [作成] をクリックします。

    これで、データ コネクタが作成されました。このコネクタは、Cloud Storage のロケーションとデータを定期的に同期します。また、gcs_store という名前のエンティティ データストアも作成しました。

  15. 取り込みのステータスを確認するには、[データストア] ページに移動し、データストア名をクリックして、[データ] ページで詳細を表示します。

    [データの取り込みアクティビティ] タブ。[データ取り込みアクティビティ] タブのステータス列が [進行中] から [成功] に変わると、最初の取り込みが完了します。

    取り込みには、データのサイズに応じて、数分から数時間かかることがあります。

データソースを設定してデータを初めてインポートすると、設定時に選択した頻度でそのソースからデータが同期されます。 データコネクタの作成から約 1 時間後に、最初の同期が行われます。 次回の同期は、24 時間、72 時間、または 120 時間後に行われます。

次のステップ

API を使用して構造化 JSON データをアップロードする

API を使用して JSON ドキュメントまたはオブジェクトを直接アップロードする手順は次のとおりです。

データをインポートする前に、取り込むデータを準備します

REST

コマンドラインを使用してデータストアを作成し、構造化 JSON データをインポートする手順は次のとおりです。

  1. データストアを作成します。

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    -H "X-Goog-User-Project: PROJECT_ID" \
    "https://discoveryengine.googleapis.com/v1alpha/projects/PROJECT_ID/locations/global/collections/default_collection/dataStores?dataStoreId=DATA_STORE_ID" \
    -d '{
      "displayName": "DATA_STORE_DISPLAY_NAME",
      "industryVertical": "GENERIC",
      "solutionTypes": ["SOLUTION_TYPE_RECOMMENDATION"]
    }'
    

    次のように置き換えます。

    • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
    • DATA_STORE_ID: 作成するレコメンデーション データストアの ID。この ID に使用できるのは、小文字、数字、アンダースコア、ハイフンのみです。
    • DATA_STORE_DISPLAY_NAME: 作成するレコメンデーション データストアの表示名。
  2. 省略可: 独自のスキーマを指定します。通常、スキーマを指定すると、より良い結果が得られます。詳細については、スキーマを指定する、または自動検出するをご覧ください。

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1beta/projects/PROJECT_ID/locations/global/collections/default_collection/dataStores/DATA_STORE_ID/schemas/default_schema" \
    -d '{
      "structSchema": JSON_SCHEMA_OBJECT
    }'
    

    次のように置き換えます。

    • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
    • DATA_STORE_ID: レコメンデーション データストアの ID。
    • JSON_SCHEMA_OBJECT: JSON オブジェクトとしての JSON スキーマ。次に例を示します。

      {
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "type": "object",
        "properties": {
          "title": {
            "type": "string",
            "keyPropertyMapping": "title"
          },
          "categories": {
            "type": "array",
            "items": {
              "type": "string",
              "keyPropertyMapping": "category"
            }
          },
          "uri": {
            "type": "string",
            "keyPropertyMapping": "uri"
          }
        }
      }
      
  3. 定義されたスキーマに準拠する構造化データをインポートします。

    データのアップロードには、次のような方法があります。

    • JSON ドキュメントをアップロードします。

      curl -X POST \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1beta/projects/PROJECT_ID/locations/global/collections/default_collection/dataStores/DATA_STORE_ID/branches/0/documents?documentId=DOCUMENT_ID" \
      -d '{
        "jsonData": "JSON_DOCUMENT_STRING"
      }'
      

      JSON_DOCUMENT_STRING は、単一の文字列として JSON ドキュメントを置き換えます。これは、前の手順で指定した JSON スキーマに準拠している必要があります。次に例を示します。

      ```none
      { \"title\": \"test title\", \"categories\": [\"cat_1\", \"cat_2\"], \"uri\": \"test uri\"}
      ```
      
    • JSON オブジェクトをアップロードします。

      curl -X POST \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1beta/projects/PROJECT_ID/locations/global/collections/default_collection/dataStores/DATA_STORE_ID/branches/0/documents?documentId=DOCUMENT_ID" \
      -d '{
        "structData": JSON_DOCUMENT_OBJECT
      }'
      

      JSON_DOCUMENT_OBJECT は、JSON オブジェクトとして JSON ドキュメントを置き換えます。これは、前の手順で指定した JSON スキーマに準拠している必要があります。次に例を示します。

      ```json
      {
        "title": "test title",
        "categories": [
          "cat_1",
          "cat_2"
        ],
        "uri": "test uri"
      }
      ```
      
    • JSON ドキュメントで更新します。

      curl -X PATCH \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1beta/projects/PROJECT_ID/locations/global/collections/default_collection/dataStores/DATA_STORE_ID/branches/0/documents/DOCUMENT_ID" \
      -d '{
        "jsonData": "JSON_DOCUMENT_STRING"
      }'
      
    • JSON オブジェクトで更新します。

      curl -X PATCH \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://discoveryengine.googleapis.com/v1beta/projects/PROJECT_ID/locations/global/collections/default_collection/dataStores/DATA_STORE_ID/branches/0/documents/DOCUMENT_ID" \
      -d '{
        "structData": JSON_DOCUMENT_OBJECT
      }'
      

次のステップ

Terraform を使用してデータストアを作成する

Terraform を使用して空のデータストアを作成できます。空のデータストアが作成されたら、 Google Cloud コンソールまたは API コマンドを使用してデータストアにデータを取り込むことができます。

Terraform 構成を適用または削除する方法については、基本的な Terraform コマンドをご覧ください。

Terraform を使用して空のデータストアを作成するには、 google_discovery_engine_data_store をご覧ください。