יצירת מאגר נתונים של המלצות בהתאמה אישית

כדי ליצור מאגר נתונים ולהטמיע נתונים להמלצות בהתאמה אישית, עוברים לקטע שמתאים למקור שבו אתם מתכננים להשתמש:

BigQuery

יש שתי דרכים ליצור מאגרי נתונים מטבלאות BigQuery:

  • הטמעת נתונים חד-פעמית: מייבאים נתונים מטבלה ב-BigQuery למאגר נתונים. הנתונים במאגר הנתונים לא משתנים אלא אם מרעננים את הנתונים באופן ידני.

  • הטמעה תקופתית: מייבאים נתונים מטבלה אחת או יותר ב-BigQuery ומגדירים תדירות סנכרון שקובעת כמה פעמים מאגרי הנתונים מתעדכנים בנתונים העדכניים ביותר ממערך הנתונים ב-BigQuery.

בטבלה הבאה מוצגת השוואה בין שתי הדרכים לייבוא נתונים מ-BigQuery למאגרי נתונים של חיפוש מבוסס סוכנים.

הוספה חד-פעמית הטמעה תקופתית
צריך לרענן את הנתונים באופן ידני. הנתונים מתעדכנים אוטומטית כל יום, כל 3 ימים או כל 5 ימים. אי אפשר לרענן את הנתונים באופן ידני.
חיפוש מבוסס סוכנים יוצר מאגר נתונים יחיד מטבלה אחת ב-BigQuery. התכונה 'חיפוש מבוסס סוכנים' יוצרת מחבר נתונים לקבוצת נתונים של BigQuery ומאגר נתונים (שנקרא מאגר נתונים של ישויות) לכל טבלה שצוינה. לכל מחבר נתונים, הטבלאות צריכות להיות מאותו סוג נתונים (לדוגמה, מובנה) ולהיות באותו מערך נתונים של BigQuery.
אפשר לשלב נתונים מכמה טבלאות במאגר נתונים אחד. לשם כך, קודם מייבאים נתונים מטבלה אחת ואז מייבאים עוד נתונים ממקור אחר או מטבלה ב-BigQuery. מכיוון שאין תמיכה בייבוא נתונים ידני, אפשר להשתמש בנתונים במאגר נתונים של ישות רק מטבלה אחת ב-BigQuery.
יש תמיכה בבקרת גישה למקורות נתונים. אין תמיכה בבקרת גישה למקור הנתונים. הנתונים המיובאים יכולים לכלול אמצעי בקרה לגישה, אבל המערכת לא תתחשב בהם.
אפשר ליצור מאגר נתונים באמצעותGoogle Cloud המסוף או ה-API. צריך להשתמש במסוף כדי ליצור מחברי נתונים ומאגרי נתונים של ישויות.
תואם ל-CMEK. תואם ל-CMEK.

לפני שמתחילים

כדי לייבא נתונים מ Google Cloud פרויקט מקור ששונה מהפרויקט עם מאגר הנתונים של חיפוש מבוסס סוכנים, צריך להקצות לחשבון השירות בפרויקט שמכיל את מאגר הנתונים של חיפוש מבוסס סוכנים את תפקידי ניהול הזהויות והרשאות הגישה (IAM) הבאים:service-PROJECT_NUMBER@gcp-sa-discoveryengine.iam.gserviceaccount.comGoogle Cloud

ייבוא חד-פעמי מ-BigQuery

כדי להטמיע נתונים מטבלה ב-BigQuery, צריך ליצור מאגר נתונים ולהטמיע נתונים באמצעות המסוף Google Cloud או API.

לפני שמייבאים את הנתונים, כדאי לעיין במאמר בנושא הכנת נתונים להעברה.

המסוף

כדי להשתמש במסוף להטמעת נתונים מ-BigQuery, פועלים לפי השלבים הבאים: Google Cloud

  1. נכנסים לדף AI Applications במסוף Google Cloud .

    אפליקציות AI

  2. עוברים לדף מאגרי נתונים.

  3. לוחצים על יצירת מאגר נתונים.

  4. בדף מקור, בוחרים באפשרות BigQuery.

  5. בקטע איזה סוג נתונים מייבאים?, בוחרים את סוג הנתונים שרוצים לייבא.

  6. בקטע תדירות הסנכרון, בוחרים באפשרות פעם אחת.

  7. בשדה BigQuery path (נתיב BigQuery), לוחצים על Browse (עיון), בוחרים טבלה שהכנתם להעברה ואז לוחצים על Select (בחירה). אפשר גם להזין את מיקום הטבלה ישירות בשדה נתיב BigQuery.

  8. לוחצים על Continue.

  9. אם אתם מבצעים ייבוא חד-פעמי של נתונים מובְנים:

    1. מיפוי שדות למאפייני מפתח.

    2. אם חסרים בסכימה שדות חשובים, משתמשים באפשרות הוספת שדה חדש כדי להוסיף אותם.

      מידע נוסף זמין במאמר מידע על זיהוי ועריכה אוטומטיים.

    3. לוחצים על Continue.

  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 .
    • DATA_STORE_ID: המזהה של מאגר הנתונים של חיפוש מבוסס סוכנים שרוצים ליצור. המזהה יכול להכיל רק אותיות קטנות, ספרות, קווים תחתונים ומקפים.
    • DATA_STORE_DISPLAY_NAME: השם המוצג של מאגר הנתונים של חיפוש מבוסס סוכנים שרוצים ליצור.
  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 .
    • DATA_STORE_ID: המזהה של מאגר הנתונים של חיפוש מבוסס סוכנים.
    • DATASET_ID: המזהה של מערך הנתונים ב-BigQuery.
    • TABLE_ID: המזהה של הטבלה ב-BigQuery.
      • אם הטבלה ב-BigQuery לא נמצאת ב-PROJECT_ID, צריך לתת לחשבון השירות service-<project number>@gcp-sa-discoveryengine.iam.gserviceaccount.com הרשאה מסוג 'BigQuery Data Viewer' לטבלה ב-BigQuery. לדוגמה, אם מייבאים טבלה מ-BigQuery מפרויקט המקור '123' לפרויקט היעד '456', צריך לתת ל-service-456@gcp-sa-discoveryengine.iam.gserviceaccount.com הרשאות לטבלה ב-BigQuery בפרויקט '123'.
    • DATA_SCHEMA: אופציונלי. הערכים הם document ו-custom. ערך ברירת המחדל הוא document.
      • document: הטבלה ב-BigQuery שבה אתם משתמשים צריכה להתאים לסכימת ברירת המחדל של BigQuery שמופיעה במאמר הכנת נתונים להוספה. אתם יכולים להגדיר את המזהה של כל מסמך בעצמכם, כשכל הנתונים עטופים במחרוזת jsonData.
      • custom: כל סכימת טבלה ב-BigQuery מתקבלת, וחיפוש מבוסס סוכנים יוצר באופן אוטומטי את המזהים לכל מסמך שמייבאים.
    • ERROR_DIRECTORY: אופציונלי. ספרייה ב-Cloud Storage למידע על שגיאות בייבוא – לדוגמה, gs://<your-gcs-bucket>/directory/import_errors. ‫Google ממליצה להשאיר את השדה הזה ריק כדי שהתכונה 'חיפוש באמצעות סוכן' תיצור באופן אוטומטי ספריה זמנית.
    • RECONCILIATION_MODE: אופציונלי. הערכים האפשריים הם FULL ו-INCREMENTAL. ערך ברירת המחדל הוא INCREMENTAL. הגדרה של INCREMENTAL גורמת לרענון מצטבר של הנתונים מ-BigQuery למאגר הנתונים. הפעולה הזו היא upsert, שמוסיפה מסמכים חדשים ומחליפה מסמכים קיימים במסמכים מעודכנים עם אותו מזהה. ציון FULL גורם לשינוי בסיס מלא של המסמכים במאגר הנתונים. במילים אחרות, מסמכים חדשים ומעודכנים מתווספים למאגר הנתונים, ומסמכים שלא נמצאים ב-BigQuery מוסרים ממנו. מצב FULL שימושי אם רוצים למחוק באופן אוטומטי מסמכים שכבר לא צריכים.
    • AUTO_GENERATE_IDS: אופציונלי. ההגדרה קובעת אם מזהי המסמכים ייווצרו באופן אוטומטי. אם הערך הוא true, מזהי המסמכים נוצרים על סמך גיבוב של מטען הייעודי (payload). שימו לב שמזהי המסמכים שנוצרו עשויים להשתנות בין ייבוא לייבוא. אם אתם יוצרים מזהים באופן אוטומטי בכמה ייבואים, מומלץ מאוד להגדיר את reconciliationMode לערך FULL כדי לשמור על מזהי מסמכים עקביים.

      מציינים את autoGenerateIds רק כשbigquerySource.dataSchema מוגדר לערך custom. אחרת, מוחזרת שגיאה INVALID_ARGUMENT. אם לא מציינים את autoGenerateIds או מגדירים אותו ל-false, צריך לציין את idField. אחרת, הייבוא של המסמכים ייכשל.

    • ID_FIELD: אופציונלי. מציין אילו שדות הם מזהי המסמכים. בקבצים של מקורות BigQuery, ‏idField מציין את שם העמודה בטבלת BigQuery שמכילה את מזהי המסמכים.

      מציינים את idField רק אם: (1) הערך של bigquerySource.dataSchema הוא custom, וגם (2) הערך של auto_generate_ids הוא false או שלא צוין ערך. אחרת, מוחזרת שגיאת INVALID_ARGUMENT.

      הערך של שם העמודה ב-BigQuery צריך להיות מסוג string, להכיל בין 1 ל-63 תווים ולעמוד בדרישות של RFC-1034. אחרת, ייבוא המסמכים ייכשל.

C#

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים C#.

כדי לבצע אימות ב-חיפוש מבוסס סוכנים, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

יצירת מאגר נתונים

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

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Go.

כדי לבצע אימות ב-חיפוש מבוסס סוכנים, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

יצירת מאגר נתונים


//go:build examples

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
}

ייבוא מסמכים


//go:build examples

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

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Java.

כדי לבצע אימות ב-חיפוש מבוסס סוכנים, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

יצירת מאגר נתונים

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

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Node.js.

כדי לבצע אימות ב-חיפוש מבוסס סוכנים, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

יצירת מאגר נתונים

/**
 * 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

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Python.

כדי לבצע אימות ב-חיפוש מבוסס סוכנים, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

יצירת מאגר נתונים


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

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Ruby.

כדי לבצע אימות ב-חיפוש מבוסס סוכנים, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

יצירת מאגר נתונים

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 למחבר נתונים של חיפוש בעזרת סוכן, ואיך מציינים טבלה במערך הנתונים לכל מאגר נתונים שרוצים ליצור. מאגרי נתונים שהם צאצאים של מחברי נתונים נקראים מאגרי נתונים של ישויות.

הנתונים ממערך הנתונים מסונכרנים מעת לעת עם מאגרי הנתונים של הישויות. אפשר לציין סנכרון יומי, כל שלושה ימים או כל חמישה ימים.

המסוף

כדי להשתמש במסוף Google Cloud כדי ליצור מחבר שמסנכרן נתונים ממערך נתונים ב-BigQuery לחיפוש מבוסס סוכנים באופן תקופתי, פועלים לפי השלבים הבאים:

  1. נכנסים לדף AI Applications במסוף Google Cloud .

    אפליקציות AI

  2. בתפריט הניווט, לוחצים על מאגרי נתונים.

  3. לוחצים על יצירת מאגר נתונים.

  4. בדף מקור, בוחרים באפשרות BigQuery.

  5. בוחרים את סוג הנתונים שמייבאים.

  6. לוחצים על תקופתי.

  7. בוחרים את תדירות הסנכרון, כלומר כמה פעמים רוצים שמחבר Agent Search יסנכרן עם מערך הנתונים של BigQuery. אפשר לשנות את התדירות בהמשך.

  8. בשדה נתיב למערך הנתונים ב-BigQuery, לוחצים על עיון, בוחרים את מערך הנתונים שמכיל את הטבלאות שהכנתם להעלאה. אפשרות אחרת היא להזין את מיקום הטבלה ישירות בשדה נתיב BigQuery. הפורמט של הנתיב הוא projectname.datasetname.

  9. בשדה Tables to sync, לוחצים על Browse ובוחרים טבלה שמכילה את הנתונים שרוצים לאחסן במאגר הנתונים.

  10. אם יש עוד טבלאות במערך הנתונים שרוצים להשתמש בהן במאגרי נתונים, לוחצים על הוספת טבלה ומציינים גם את הטבלאות האלה.

  11. לוחצים על Continue.

  12. בוחרים אזור לאחסון הנתונים, מזינים שם למחבר הנתונים ולוחצים על יצירה.

    יצרתם מחבר נתונים שיסנכרן את הנתונים עם מערך הנתונים ב-BigQuery באופן תקופתי. בנוסף, יצרתם מאגרי נתונים של ישויות. למאגרי הנתונים יש את אותם שמות כמו לטבלאות ב-BigQuery.

  13. כדי לבדוק את סטטוס ההטמעה, עוברים לדף מאגרי נתונים ולוחצים על השם של מחבר הנתונים כדי לראות את הפרטים שלו בדף נתונים > הכרטיסייה פעילות של הטמעת נתונים. כשהסטטוס בעמודה סטטוס בכרטיסייה פעילות משתנה מבתהליך להושלם, סימן שההטמעה הראשונה הסתיימה.

    בהתאם לגודל הנתונים, תהליך ההטמעה יכול להימשך כמה דקות עד כמה שעות.

אחרי שמגדירים את מקור הנתונים ומייבאים נתונים בפעם הראשונה, מאגר הנתונים מסנכרן נתונים מהמקור הזה בתדירות שבוחרים במהלך ההגדרה. כשעה אחרי שיוצרים את מחבר הנתונים, מתבצע הסנכרון הראשון. הסנכרון הבא מתרחש כ-24 שעות, 72 שעות או 120 שעות לאחר מכן.

השלבים הבאים

  • כדי לצרף את מאגר הנתונים לאפליקציה, יוצרים אפליקציה ובוחרים את מאגר הנתונים לפי השלבים במאמר יצירת אפליקציה מותאמת אישית להמלצות.

  • כדי לראות תצוגה מקדימה או לקבל המלצות אחרי שמגדירים את האפליקציה ואת מאגר הנתונים, אפשר לעיין במאמר קבלת המלצות.

Cloud Storage

יש שתי דרכים ליצור מאגרי נתונים מטבלאות ב-Cloud Storage:

  • העברה חד-פעמית: מייבאים נתונים מתיקייה או מקובץ ב-Cloud Storage למאגר נתונים. הנתונים במאגר הנתונים לא משתנים אלא אם מרעננים את הנתונים באופן ידני.

  • הטמעה תקופתית: אתם מייבאים נתונים מתיקייה או מקובץ ב-Cloud Storage, ומגדירים תדירות סנכרון שקובעת כמה פעמים מאגר הנתונים מתעדכן בנתונים העדכניים ביותר ממיקום Cloud Storage הזה.

בטבלה הבאה מוצגות שתי הדרכים שבהן אפשר לייבא נתונים מ-Cloud Storage למאגרי נתונים של חיפוש מבוסס סוכנים.

הוספה חד-פעמית הטמעה תקופתית
צריך לרענן את הנתונים באופן ידני. הנתונים מתעדכנים אוטומטית כל יום, כל שלושה ימים או כל חמישה ימים. אי אפשר לרענן את הנתונים באופן ידני.
חיפוש מבוסס סוכנים יוצר מאגר נתונים יחיד מתיקייה או מקובץ אחד ב-Cloud Storage. התכונה 'חיפוש מבוסס סוכנים' יוצרת מחבר נתונים, ומקשרת אליו מאגר נתונים (שנקרא מאגר נתונים של ישויות) עבור הקובץ או התיקייה שצוינו. לכל מחבר נתונים של Cloud Storage יכול להיות מאגר נתונים של ישות אחת.
אפשר לשלב נתונים מכמה קבצים, תיקיות וקטגוריות במאגר נתונים אחד. לשם כך, קודם צריך להטמיע נתונים ממיקום אחד ב-Cloud Storage, ואז להטמיע עוד נתונים ממיקום אחר. מכיוון שייבוא נתונים ידני לא אפשרי, אפשר להשתמש בנתונים במאגר נתונים של ישות רק מקובץ או מתיקייה אחת ב-Cloud Storage.
יש תמיכה בבקרת גישה למקורות נתונים. מידע נוסף מופיע במאמר בנושא בקרת גישה למקורות נתונים. אין תמיכה בבקרת גישה למקור הנתונים. הנתונים המיובאים יכולים לכלול אמצעי בקרה לגישה, אבל המערכת לא תתחשב בהם.
אפשר ליצור מאגר נתונים באמצעותGoogle Cloud המסוף או ה-API. צריך להשתמש במסוף כדי ליצור מחברי נתונים ומאגרי נתונים של ישויות.
תואם ל-CMEK. תואם ל-CMEK.

לפני שמתחילים

כדי לייבא נתונים מ Google Cloud פרויקט מקור ששונה מהפרויקט עם מאגר הנתונים של חיפוש מבוסס סוכנים, צריך להקצות לחשבון השירות בפרויקט שמכיל את מאגר הנתונים של חיפוש מבוסס סוכנים את תפקידי ניהול הזהויות והרשאות הגישה (IAM) הבאים:service-PROJECT_NUMBER@gcp-sa-discoveryengine.iam.gserviceaccount.comGoogle Cloud

ייבוא חד-פעמי מ-Cloud Storage

כדי להטמיע נתונים מ-Cloud Storage, צריך ליצור מאגר נתונים ולהטמיע נתונים באמצעות Google Cloud המסוף או ה-API.

לפני שמייבאים את הנתונים, כדאי לעיין במאמר בנושא הכנת נתונים להעברה.

המסוף

כדי להשתמש במסוף להטמעת נתונים מקטגוריה של Cloud Storage, פועלים לפי השלבים הבאים:

  1. נכנסים לדף AI Applications במסוף Google Cloud .

    אפליקציות AI

  2. עוברים לדף מאגרי נתונים.

  3. לוחצים על יצירת מאגר נתונים.

  4. בדף מקור, בוחרים באפשרות Cloud Storage.

  5. בקטע בחירת תיקייה או קובץ לייבוא, בוחרים באפשרות תיקייה או קובץ.

  6. לוחצים על עיון, בוחרים את הנתונים שהכנתם להעלאה ולוחצים על בחירה. אפשר גם להזין את המיקום ישירות בשדה gs://.

  7. בוחרים את סוג הנתונים שמייבאים.

  8. לוחצים על Continue.

  9. אם אתם מבצעים ייבוא חד-פעמי של נתונים מובְנים:

    1. מיפוי שדות למאפייני מפתח.

    2. אם חסרים בסכימה שדות חשובים, משתמשים באפשרות הוספת שדה חדש כדי להוסיף אותם.

      מידע נוסף זמין במאמר מידע על זיהוי ועריכה אוטומטיים.

    3. לוחצים על Continue.

  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 .
    • DATA_STORE_ID: המזהה של מאגר הנתונים של חיפוש מבוסס סוכנים שרוצים ליצור. המזהה יכול להכיל רק אותיות קטנות, ספרות, קווים תחתונים ומקפים.
    • DATA_STORE_DISPLAY_NAME: השם המוצג של מאגר הנתונים של חיפוש מבוסס סוכנים שרוצים ליצור.
  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 .
    • DATA_STORE_ID: המזהה של מאגר הנתונים של חיפוש מבוסס סוכנים.
    • INPUT_FILE_PATTERN: תבנית קובץ ב-Cloud Storage שמכילה את המסמכים שלכם.

      לנתונים מובְנים או לנתונים לא מובְנים עם מטא-נתונים, דוגמה לתבנית של קובץ קלט היא gs://<your-gcs-bucket>/directory/object.jsonודוגמה להתאמת תבנית לקובץ אחד או יותר היא 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. לדוגמה, אם מייבאים קטגוריה של Cloud Storage מפרויקט המקור '123' לפרויקט היעד '456', צריך לתת הרשאות service-456@gcp-sa-discoveryengine.iam.gserviceaccount.com בקטגוריה של Cloud Storage בפרויקט '123'.

    • DATA_SCHEMA: אופציונלי. הערכים הם document,‏ custom,‏ csv ו-content. ערך ברירת המחדל הוא document.

      • document: העלאת נתונים לא מובנים עם מטא-נתונים עבור מסמכים לא מובנים. כל שורה בקובץ צריכה להיות באחד מהפורמטים הבאים. אפשר להגדיר את המזהה של כל מסמך:

        • { "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 של המסמך בפורמט עקבי ישירות בכל שורה, ו'חיפוש מבוסס סוכנים' ייצור באופן אוטומטי את המזהים לכל מסמך שיובא.

      • content: העלאת מסמכים לא מובנים (PDF, ‏ HTML, ‏ DOC, ‏ TXT,‏ PPTX). המזהה של כל מסמך נוצר אוטומטית בתור 128 הביטים הראשונים של SHA256(GCS_URI) שמקודדים כמחרוזת הקסדצימלית. אפשר לציין כמה תבניות של קובצי קלט, כל עוד מספר הקבצים התואמים לא חורג מהמגבלה של 100,000 קבצים.

      • csv: כוללים שורת כותרת בקובץ ה-CSV, כשכל כותרת ממופה לשדה במסמך. מציינים את הנתיב לקובץ ה-CSV באמצעות השדה inputUris.

    • ERROR_DIRECTORY: אופציונלי. ספרייה ב-Cloud Storage למידע על שגיאות בייבוא – לדוגמה, gs://<your-gcs-bucket>/directory/import_errors. ‫Google ממליצה להשאיר את השדה הזה ריק כדי ש'חיפוש מבוסס סוכנים' ייצור באופן אוטומטי ספרייה זמנית.

    • RECONCILIATION_MODE: אופציונלי. הערכים הם FULL ו-INCREMENTAL. ערך ברירת המחדל הוא INCREMENTAL. הגדרה של INCREMENTAL גורמת לרענון מצטבר של נתונים מ-Cloud Storage למאגר הנתונים. הפעולה הזו מבצעת upsert, שמוסיף מסמכים חדשים ומחליף מסמכים קיימים במסמכים מעודכנים עם אותו מזהה. הגדרת FULL גורמת לשינוי בסיס מלא של המסמכים במאגר הנתונים. כלומר, מסמכים חדשים ומעודכנים מתווספים למאגר הנתונים, ומסמכים שלא נמצאים ב-Cloud Storage מוסרים ממנו. מצב FULL שימושי אם רוצים למחוק באופן אוטומטי מסמכים שכבר לא צריכים.

    • AUTO_GENERATE_IDS: אופציונלי. ההגדרה קובעת אם מזהי המסמכים ייווצרו באופן אוטומטי. אם המדיניות מוגדרת לערך true, מזהי המסמכים נוצרים על סמך גיבוב (hash) של מטען הייעודי. חשוב לדעת שמזהי מסמכים שנוצרו יכולים להשתנות בין ייבוא לייבוא. אם אתם יוצרים מזהים באופן אוטומטי בכמה ייבואים, מומלץ מאוד להגדיר את reconciliationMode ל-FULL כדי לשמור על מזהי מסמכים עקביים.

      מציינים את autoGenerateIds רק אם הערך של gcsSource.dataSchema הוא custom או csv. אחרת, מוחזרת שגיאת INVALID_ARGUMENT. אם לא מציינים את autoGenerateIds או מגדירים אותו ל-false, צריך לציין את idField. אחרת, ייבוא המסמכים ייכשל.

    • ID_FIELD: אופציונלי. מציינים אילו שדות הם מזהי המסמכים. במסמכי מקור של Cloud Storage, ‏ idField מציין את השם בשדות ה-JSON שהם מזהי מסמכים. לדוגמה, אם {"my_id":"some_uuid"} הוא שדה מזהה המסמך באחד מהמסמכים, מציינים "idField":"my_id". השדה הזה מזהה את כל שדות ה-JSON עם השם "my_id" כמזהי מסמכים.

      מציינים את השדה הזה רק אם: (1) הערך של gcsSource.dataSchema הוא custom או csv, ו-(2) הערך של auto_generate_ids הוא false או שלא צוין ערך. אחרת, מוחזרת שגיאת INVALID_ARGUMENT.

      שימו לב: הערך של שדה ה-JSON ב-Cloud Storage חייב להיות מסוג מחרוזת, להכיל בין 1 ל-63 תווים ולעמוד בדרישות של RFC-1034. אחרת, ייבוא המסמכים ייכשל.

      שימו לב ששם השדה ב-JSON שצוין על ידי id_field חייב להיות מסוג מחרוזת, להכיל בין 1 ל-63 תווים ולעמוד בדרישות של RFC-1034. אחרת, ייבוא המסמכים ייכשל.

C#

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים C#.

כדי לבצע אימות ב-חיפוש מבוסס סוכנים, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

יצירת מאגר נתונים

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

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Go.

כדי לבצע אימות ב-חיפוש מבוסס סוכנים, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

יצירת מאגר נתונים


//go:build examples

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
}

ייבוא מסמכים


//go:build examples

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

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Java.

כדי לבצע אימות ב-חיפוש מבוסס סוכנים, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

יצירת מאגר נתונים

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

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Node.js.

כדי לבצע אימות ב-חיפוש מבוסס סוכנים, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

יצירת מאגר נתונים

/**
 * 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

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Python.

כדי לבצע אימות ב-חיפוש מבוסס סוכנים, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

יצירת מאגר נתונים


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

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Ruby.

כדי לבצע אימות ב-חיפוש מבוסס סוכנים, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

יצירת מאגר נתונים

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 לבין מחבר נתונים של Agent Search, ואיך לציין תיקייה או קובץ במיקום הזה בשביל מאגר הנתונים שרוצים ליצור. מאגרי נתונים שהם צאצאים של מחברי נתונים נקראים מאגרי נתונים של ישויות.

הנתונים מסתנכרנים מעת לעת עם מאגר נתוני הישות. אפשר לציין סנכרון יומי, כל שלושה ימים או כל חמישה ימים.

המסוף

  1. נכנסים לדף AI Applications במסוף Google Cloud .

    אפליקציות AI

  2. עוברים לדף מאגרי נתונים.

  3. לוחצים על יצירת מאגר נתונים.

  4. בדף מקור, בוחרים באפשרות Cloud Storage.

  5. בוחרים את סוג הנתונים שמייבאים.

  6. לוחצים על תקופתי.

  7. בוחרים את תדירות הסנכרון, כלומר באיזו תדירות מחבר Agent Search יסנכרן עם המיקום ב-Cloud Storage. אפשר לשנות את התדירות בהמשך.

  8. בקטע בחירת תיקייה או קובץ לייבוא, בוחרים באפשרות תיקייה או קובץ.

  9. לוחצים על עיון, בוחרים את הנתונים שהכנתם להעלאה ולוחצים על בחירה. אפשר גם להזין את המיקום ישירות בשדה gs://.

  10. לוחצים על Continue.

  11. בוחרים אזור למחבר הנתונים.

  12. מזינים שם למחבר הנתונים.

  13. אופציונלי: אם בחרתם מסמכים לא מובנים, אתם יכולים לבחור אפשרויות ניתוח וחלוקה למקטעים של המסמכים. כדי להשוות בין מנתחי נתונים, אפשר לעיין במאמר בנושא ניתוח מסמכים. מידע על חלוקה לחלקים זמין במאמר חלוקת מסמכים לחלקים לצורך RAG.

    כדי לבחור מנתח, מרחיבים את אפשרויות לעיבוד מסמכים ומציינים את אפשרויות המנתח שרוצים להשתמש בהן.

    שימוש בכלי לניתוח OCR ובכלי לניתוח פריסה עלול לגרור עלויות נוספות. מידע על התמחור של התכונות ב-Document AI

  14. לוחצים על יצירה.

    יצרתם עכשיו מחבר נתונים, שיסנכרן נתונים באופן תקופתי עם המיקום ב-Cloud Storage. יצרתם גם מאגר נתוני ישויות בשם gcs_store.

  15. כדי לבדוק את סטטוס ההטמעה, עוברים לדף מאגרי נתונים ולוחצים על השם של מחבר הנתונים כדי לראות את הפרטים שלו בדף נתונים.

    הכרטיסייה פעילות של הטמעת נתונים. כשהסטטוס בעמודה Data ingestion activity (פעילות של הכנסת נתונים) משתנה מ-In progress (בתהליך) ל-succeeded (הושלם), ההכנסה הראשונה של הנתונים מסתיימת.

    בהתאם לגודל הנתונים, תהליך ההטמעה יכול להימשך כמה דקות עד כמה שעות.

אחרי שמגדירים את מקור הנתונים ומייבאים נתונים בפעם הראשונה, הנתונים מסונכרנים מהמקור בתדירות שבוחרים במהלך ההגדרה. כשעה אחרי שיוצרים את מחבר הנתונים, מתבצע הסנכרון הראשון. הסנכרון הבא מתרחש כ-24 שעות, 72 שעות או 120 שעות לאחר מכן.

השלבים הבאים

  • כדי לצרף את מאגר הנתונים לאפליקציה, יוצרים אפליקציה ובוחרים את מאגר הנתונים לפי השלבים במאמר יצירת אפליקציה מותאמת אישית להמלצות.

  • כדי לראות תצוגה מקדימה או לקבל המלצות אחרי שמגדירים את האפליקציה ואת מאגר הנתונים, אפשר לעיין במאמר קבלת המלצות.

העלאת נתונים מובְנים בפורמט JSON באמצעות ה-API

כדי להעלות ישירות מסמך או אובייקט בפורמט JSON באמצעות ה-API, פועלים לפי השלבים הבאים.

לפני שמייבאים את הנתונים, צריך להכין את הנתונים להעברה.

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 .
    • DATA_STORE_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 .
    • DATA_STORE_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.