קבלת תוצאות חיפוש

בדף הזה מוסבר איך לצפות בתצוגה מקדימה של תוצאות החיפוש באמצעות מסוף Google Cloud ואיך לקבל תוצאות חיפוש באמצעות ה-API.

בנוסף, במקום ליצור ווידג'ט חיפוש להוספה לדף האינטרנט, אפשר לבצע קריאות API ולשלב אותן בשרת או באפליקציה. בדף הזה יש דוגמאות קוד שמראות איך לבצע שאילתות חיפוש באמצעות ספריות לקוח של gRPC עם חשבון שירות.

התאמה מדויקת עם מירכאות כפולות

כדי לבצע התאמה מדויקת, אפשר להקיף את שאילתת החיפוש במירכאות כפולות (""). סוג כזה של חיפוש נקרא בדרך כלל חיפוש במרכאות.

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

לדוגמה, אם שאילתת החיפוש היא "query": "\"Mary had a little lamb\"", חיפוש מבוסס סוכנים יחפש את הביטוי בדיוק כמו שהוא. הוא לא יחזיר תוצאות חיפוש שמכילות את Mary had lamb, שחסרות בו מילים, או את a little lamb had Mary, שבו המילים מופיעות בסדר שונה.

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

אופרטורים לוגיים

כשמחפשים בנתונים מובְנים ובנתונים לא מובְנים עם מטא-נתונים, אפשר להוסיף אופרטורים לוגיים לחיפוש. אפשר להוסיף OR ו-AND לשאילתת החיפוש בין כמה מונחים או ביטויים. האופרטור הלוגי NOT לא נתמך

הדרך שבה מחברים את מונחי החיפוש קובעת את רמת הדיוק של התוצאות:

וגם
כל מונח בשאילתה חייב להופיע בתוצאות. לדוגמה, חיפוש של jazz AND piano יציג תוצאות שמכילות את המילים jazz ו-piano.
או
לפחות אחד מהמונחים שבשאילתה צריך להופיע בתוצאות. לדוגמה, אם מחפשים את המחרוזת rock OR pop, התוצאות יכללו את rock, את pop או את שניהם.

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

תרחישים של שאילתות חיפוש

בטבלה הבאה מפורטים כמה תרחישים שבהם אתם עשויים להיתקל כשאתם משתמשים בחיפוש בהתאמה מדויקת או בהתאמה חלקית.

תרחיש תיאור דוגמה
חיפוש בהתאמה חלקית ללא אופרטורים לוגיים אם אין מירכאות כפולות סביב מונחי החיפוש ואין אופרטורים לוגיים ביניהם, החיפוש מתבצע כאילו יש אופרטור AND בין המונחים. יכול להיות שהתוצאות יכללו גם מסמכים אחרים שחיפוש מבוסס סוכנים חושב שהם רלוונטיים לשאילתה בגלל חיפוש סמנטי.
       "query": "Mary little lamb"
      

בשאילתה הזו, המסמכים הכי רלוונטיים בתשובה מכילים את כל המונחים Mary, little ו-lamb. התשובה עשויה לכלול גם מסמכים אחרים שמכילים מונחים רלוונטיים מבחינה סמנטית.

חיפוש של התאמה מדויקת ללא אופרטורים לוגיים אם יש מירכאות כפולות סביב כמה מונחי חיפוש או ביטויים נפרדים, ואין ביניהם אופרטורים לוגיים, החיפוש יתבצע כאילו יש אופרטור AND בין הביטויים. כשמוסיפים מירכאות כפולות לפחות למונח חיפוש אחד בשאילתה, החיפוש הסמנטי מושבת בשאילתה כולה.
       "query": "\"Mary\" \"little lamb\""
      

בשאילתה הזו, החיפוש יניב תוצאות שמכילות את שני הביטויים Mary ו-little lamb.

חיפוש של התאמה מדויקת והתאמה חלקית כשמוסיפים מירכאות כפולות למונח חיפוש אחד לפחות בשאילתה, החיפוש הסמנטי מושבת בשאילתה כולה. אם מציינים אופרטורים לוגיים, המערכת מתייחסת אליהם כמו שהם מצוינים. אם לא מציינים אופרטורים לוגיים בשאילתה, החיפוש פועל כאילו יש אופרטור AND בין הביטויים.
       "query": "Mary \"little lamb\""
      

בשאילתה הזו, החיפוש מתבצע כאילו יש אופרטור AND בין הביטויים. מכיוון שהמילה Mary לא מופיעה במירכאות, היא לא תואמת בדיוק.

איך מקבלים תוצאות חיפוש לאפליקציה עם נתוני אתר

המסוף

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

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

    אפליקציות AI

  2. לוחצים על שם האפליקציה שרוצים לערוך.

  3. לוחצים על תצוגה מקדימה.

  4. פותחים את הדף Preview במסוף.

  5. אופציונלי: אם קישרתם כמה מאגרי נתונים לאפליקציה אבל אתם רוצים לקבל תוצאות רק ממאגר נתונים ספציפי, בוחרים את מאגר הנתונים שממנו רוצים לקבל תוצאות.

  6. מקלידים שאילתת חיפוש.

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

  7. מקישים על Enter כדי לשלוח את השאילתה.

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

REST

כדי להשתמש ב-API כדי לקבל תוצאות חיפוש של אפליקציה עם נתונים של אתר, משתמשים ב-method‏ engines.servingConfigs.search:

  1. מאתרים את מזהה האפליקציה. אם כבר יש לכם מזהה אפליקציה, דלגו לשלב הבא.

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

      מעבר אל 'אפליקציות'

    2. בדף אפליקציות, מאתרים את שם האפליקציה ומעתיקים את המזהה שלה מהעמודה מזהה.

  2. מקבלים תוצאות חיפוש.

    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/engines/APP_ID/servingConfigs/default_search:search" \
    -d '{
    "servingConfig": "projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search",
    "query": "QUERY",
    "pageSize": "PAGE_SIZE",
    "offset": "OFFSET",
    "orderBy": "ORDER_BY",
    "params": {"user_country_code": "USER_COUNTRY_CODE",
    "searchType": "SEARCH_TYPE"},
    "filter": "FILTER",
    "boostSpec": "BOOST_SPEC",
    "contentSearchSpec": {
       "searchResultMode": "RESULT_MODE"
     },
     "userPseudoId": "USER_PSEUDO_ID",
     "dataStoreSpecs": [{"DATA_STORE_SPEC"}]
    }'
    

    מחליפים את מה שכתוב בשדות הבאים:

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים שרוצים לשלוח אליה שאילתה.
    • QUERY: טקסט השאילתה לחיפוש.
    • PAGE_SIZE: מספר התוצאות שהוחזרו מהחיפוש. הגודל המקסימלי המותר של הדף תלוי בסוג הנתונים. אם גודל הדף גבוה מהערך המקסימלי, הוא ישתנה לערך המקסימלי.

      • אתרים עם הוספה בסיסית לאינדקס: ברירת מחדל 10, מקסימום 25
      • אתרים עם הוספה מתקדמת לאינדקס: ברירת מחדל 25, מקסימום 50
      • אחר: ברירת מחדל 50, מקסימום 100
    • OFFSET: אינדקס ההתחלה של התוצאות. ערך ברירת המחדל הוא 0.

      לדוגמה, אם ההיסט הוא 2, גודל הדף הוא 10 ויש 15 תוצאות להחזרה, התוצאות 2 עד 12 מוחזרות בדף הראשון.

    • ORDER_BY: הסדר שבו התוצאות מסודרות. למאפיין שלפיו רוצים למיין צריך להיות ערך מספרי, למשל date. מידע נוסף מופיע במאמר בנושא הזמנת תוצאות חיפוש באינטרנט.

    • USER_COUNTRY_CODE: מיקום המשתמש. צמד המפתח/ערך הזה הוא הרשומה היחידה שנתמכת בשדה המפה params. ערך ברירת המחדל הוא ריק. ערכים קבילים מפורטים במאמר בנושא קודי מדינות במסמכי העיון של Programmable Search Engine JSON API.

    • SEARCH_TYPE: סוג החיפוש שרוצים לבצע. ערך ברירת המחדל הוא 0 לחיפוש במסמך. הערך הנתמך השני הוא 1 לחיפוש תמונות.

    • FILTER: שדה טקסט לסינון החיפוש באמצעות ביטוי סינון. ערך ברירת המחדל הוא מחרוזת ריקה. מידע נוסף על השימוש בשדה filter זמין במאמר בנושא סינון חיפוש באתר.

    • BOOST_SPEC: אופציונלי. מפרט להדגשה או להסתרת מסמכים. ערכים:

      • BOOST: מספר בשיטת נקודה צפה בטווח [‎-1,1]. אם הערך שלילי, התוצאות יורדות בדירוג (הן יופיעו בחלק התחתון של התוצאות). אם הערך חיובי, התוצאות מקודמות (מופיעות גבוה יותר בתוצאות).
      • CONDITION: ביטוי של מסנן טקסט לבחירת המסמכים שיוחלו עליהם הגדלות. המסנן צריך להחזיר ערך בוליאני. דוגמאות לביטויי סינון מופיעות במאמרים תחביר של ביטויי סינון ותחביר של הוספה מתקדמת לאינדקס. מידע על שיפור תוצאות חיפוש מובנה זמין במאמר שיפור תוצאות חיפוש.
    • RESULT_MODE: קובע אם תוצאות החיפוש יוחזרו כמסמכים מלאים או בחלקים. כדי לקבל נתחים, צריך להפעיל את האפשרות 'חלוקת מסמכים לנתחים' במאגר הנתונים. הערכים הקבילים הם documents ו-chunks. כשחיתוך לחלקים מופעל במאגר נתונים, ערך ברירת המחדל הוא chunks. אחרת, ברירת המחדל היא documents. מידע על חלוקת מסמכים לחלקים זמין במאמר ניתוח מסמכים וחלוקה שלהם לחלקים. השדה הזה נמצא בגרסת Public Preview. כדי להשתמש בו, צריך לשנות את v1 ל-v1alpha בפקודת curl.

    • USER_PSEUDO_ID: מחרוזת בקידוד UTF-8, שמשמשת כמזהה ייחודי פסאודונימי למעקב אחרי המשתמשים. האורך המקסימלי הוא 128 תווים. ‫Google ממליצה מאוד להשתמש בשדה הזה כי הוא משפר את הביצועים של המודל ואת איכות ההתאמה האישית. אפשר להשתמש בקובץ Cookie של HTTP בשדה הזה, כדי לזהות באופן ייחודי מבקר במכשיר יחיד. הנה כמה דברים חשובים שכדאי לזכור:

      • המזהה הזה לא משתנה כשהמבקר נכנס לאתר או יוצא ממנו.
      • אסור להגדיר את אותו מזהה למשתמשים שונים בשדה הזה. במקרים אחרים, שימוש באותו מזהה משתמש לכמה משתמשים עלול לשלב היסטוריית אירועים של משתמשים שונים ולהפחית את איכות המודל.
      • השדה הזה לא יכול לכלול פרטים אישיים מזהים (PII).
      • לכל בקשת חיפוש או בקשת עיון, השדה הזה צריך להיות ממופה לשדה userPseudoId המתאים באירועי המשתמש.

      מידע נוסף זמין במאמר userPseudoId.

    • DATA_STORE_SPEC: מסננים של מאגר נתונים ספציפי לחיפוש. משתמשים ב-dataStoreSpecs אם אפליקציית החיפוש מקושרת לכמה מאגרי נתונים, אבל רוצים לקבל תוצאות ממאגר נתונים ספציפי. מידע נוסף זמין במאמר בנושא DataStoreSpec.

C#

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

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

using Google.Api.Gax;
using Google.Cloud.DiscoveryEngine.V1Beta;
using Google.Protobuf.WellKnownTypes;
using System;

public sealed partial class GeneratedSearchServiceClientSnippets
{
    /// <summary>Snippet for Search</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 SearchRequestObject()
    {
        // Create client
        SearchServiceClient searchServiceClient = SearchServiceClient.Create();
        // Initialize request argument(s)
        SearchRequest request = new SearchRequest
        {
            ServingConfigAsServingConfigName = ServingConfigName.FromProjectLocationDataStoreServingConfig("[PROJECT]", "[LOCATION]", "[DATA_STORE]", "[SERVING_CONFIG]"),
            BranchAsBranchName = BranchName.FromProjectLocationDataStoreBranch("[PROJECT]", "[LOCATION]", "[DATA_STORE]", "[BRANCH]"),
            Query = "",
            Offset = 0,
            Filter = "",
            OrderBy = "",
            FacetSpecs =
            {
                new SearchRequest.Types.FacetSpec(),
            },
            BoostSpec = new SearchRequest.Types.BoostSpec(),
            Params = { { "", new Value() }, },
            QueryExpansionSpec = new SearchRequest.Types.QueryExpansionSpec(),
            SpellCorrectionSpec = new SearchRequest.Types.SpellCorrectionSpec(),
            UserPseudoId = "",
            ImageQuery = new SearchRequest.Types.ImageQuery(),
            SafeSearch = false,
            UserInfo = new UserInfo(),
            UserLabels = { { "", "" }, },
            EmbeddingSpec = new SearchRequest.Types.EmbeddingSpec(),
            ContentSearchSpec = new SearchRequest.Types.ContentSearchSpec(),
            RankingExpression = "",
            NaturalLanguageQueryUnderstandingSpec = new SearchRequest.Types.NaturalLanguageQueryUnderstandingSpec(),
            CanonicalFilter = "",
            SearchAsYouTypeSpec = new SearchRequest.Types.SearchAsYouTypeSpec(),
            DataStoreSpecs =
            {
                new SearchRequest.Types.DataStoreSpec(),
            },
            LanguageCode = "",
            RegionCode = "",
            SessionAsSessionName = SessionName.FromProjectLocationDataStoreSession("[PROJECT]", "[LOCATION]", "[DATA_STORE]", "[SESSION]"),
            SessionSpec = new SearchRequest.Types.SessionSpec(),
            RelevanceThreshold = SearchRequest.Types.RelevanceThreshold.Unspecified,
            PersonalizationSpec = new SearchRequest.Types.PersonalizationSpec(),
            OneBoxPageSize = 0,
            RankingExpressionBackend = SearchRequest.Types.RankingExpressionBackend.Unspecified,
        };
        // Make the request
        PagedEnumerable<SearchResponse, SearchResponse.Types.SearchResult> response = searchServiceClient.Search(request);

        // Iterate over all response items, lazily performing RPCs as required
        foreach (SearchResponse.Types.SearchResult item in response)
        {
            // Do something with each item
            Console.WriteLine(item);
        }

        // Or iterate over pages (of server-defined size), performing one RPC per page
        foreach (SearchResponse page in response.AsRawResponses())
        {
            // Do something with each page of items
            Console.WriteLine("A page of results:");
            foreach (SearchResponse.Types.SearchResult item in page)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
        }

        // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
        int pageSize = 10;
        Page<SearchResponse.Types.SearchResult> singlePage = response.ReadPage(pageSize);
        // Do something with the page of items
        Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
        foreach (SearchResponse.Types.SearchResult item in singlePage)
        {
            // Do something with each item
            Console.WriteLine(item);
        }
        // Store the pageToken, for when the next page is required.
        string nextPageToken = singlePage.NextPageToken;
    }
}

Java

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

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


import com.google.cloud.discoveryengine.v1.SearchRequest;
import com.google.cloud.discoveryengine.v1.SearchResponse;
import com.google.cloud.discoveryengine.v1.SearchServiceClient;
import com.google.cloud.discoveryengine.v1.SearchServiceSettings;
import com.google.cloud.discoveryengine.v1.ServingConfigName;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class Search {
  public static void main() throws IOException, ExecutionException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "PROJECT_ID";
    // Location of the data store. Options: "global", "us", "eu"
    String location = "global";
    // Collection containing the data store.
    String collectionId = "default_collection";
    // Data store ID.
    String dataStoreId = "DATA_STORE_ID";
    // Serving configuration. Options: "default_search"
    String servingConfigId = "default_search";
    // Search Query for the data store.
    String searchQuery = "Google";
    search(projectId, location, collectionId, dataStoreId, servingConfigId, searchQuery);
  }

  /** Performs a search on a given datastore. */
  public static void search(
      String projectId,
      String location,
      String collectionId,
      String dataStoreId,
      String servingConfigId,
      String searchQuery)
      throws IOException, ExecutionException {
    // For more information, refer to:
    // https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
    String endpoint = (location.equals("global")) 
        ? String.format("discoveryengine.googleapis.com:443", location) 
        : String.format("%s-discoveryengine.googleapis.com:443", location);
    SearchServiceSettings settings =
        SearchServiceSettings.newBuilder().setEndpoint(endpoint).build();
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `searchServiceClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (SearchServiceClient searchServiceClient = SearchServiceClient.create(settings)) {
      SearchRequest request =
          SearchRequest.newBuilder()
              .setServingConfig(
                  ServingConfigName.formatProjectLocationCollectionDataStoreServingConfigName(
                      projectId, location, collectionId, dataStoreId, servingConfigId))
              .setQuery(searchQuery)
              .setPageSize(10)
              .build();
      SearchResponse response = searchServiceClient.search(request).getPage().getResponse();
      for (SearchResponse.SearchResult element : response.getResultsList()) {
        System.out.println("Response content: " + element);
      }
    }
  }
}

Node.js

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

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'YOUR_LOCATION';              // Options: 'global', 'us', 'eu'
// const collectionId = 'default_collection';     // Options: 'default_collection'
// const dataStoreId = 'YOUR_DATA_STORE_ID'       // Create in Cloud Console
// const servingConfigId = 'default_config';      // Options: 'default_config'
// const searchQuery = 'Google';

const {SearchServiceClient} = require('@google-cloud/discoveryengine').v1beta;

// For more information, refer to:
// https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
const apiEndpoint =
  location === 'global'
    ? 'discoveryengine.googleapis.com'
    : `${location}-discoveryengine.googleapis.com`;

// Instantiates a client
const client = new SearchServiceClient({apiEndpoint: apiEndpoint});

async function search() {
  // The full resource name of the search engine serving configuration.
  // Example: projects/{projectId}/locations/{location}/collections/{collectionId}/dataStores/{dataStoreId}/servingConfigs/{servingConfigId}
  // You must create a search engine in the Cloud Console first.
  const name = client.projectLocationCollectionDataStoreServingConfigPath(
    projectId,
    location,
    collectionId,
    dataStoreId,
    servingConfigId
  );

  const request = {
    pageSize: 10,
    query: searchQuery,
    servingConfig: name,
  };

  const IResponseParams = {
    ISearchResult: 0,
    ISearchRequest: 1,
    ISearchResponse: 2,
  };

  // Perform search request
  const response = await client.search(request, {
    // Warning: Should always disable autoPaginate to avoid iterate through all pages.
    //
    // By default NodeJS SDK returns an iterable where you can iterate through all
    // search results instead of only the limited number of results requested on
    // pageSize, by sending multiple sequential search requests page-by-page while
    // iterating, until it exhausts all the search results. This will be unexpected and
    // may cause high Search API usage and long wait time, especially when the matched
    // document numbers are huge.
    autoPaginate: false,
  });
  const results = response[IResponseParams.ISearchResponse].results;

  for (const result of results) {
    console.log(result);
  }
}

PHP

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

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

use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;
use Google\Cloud\DiscoveryEngine\V1beta\Client\SearchServiceClient;
use Google\Cloud\DiscoveryEngine\V1beta\SearchRequest;
use Google\Cloud\DiscoveryEngine\V1beta\SearchResponse\SearchResult;

/**
 * Performs a search.
 *
 * @param string $formattedServingConfig The resource name of the Search serving config, such as
 *                                       `projects/&#42;/locations/global/collections/default_collection/engines/&#42;/servingConfigs/default_serving_config`,
 *                                       or
 *                                       `projects/&#42;/locations/global/collections/default_collection/dataStores/default_data_store/servingConfigs/default_serving_config`.
 *                                       This field is used to identify the serving configuration name, set
 *                                       of models used to make the search. Please see
 *                                       {@see SearchServiceClient::servingConfigName()} for help formatting this field.
 */
function search_sample(string $formattedServingConfig): void
{
    // Create a client.
    $searchServiceClient = new SearchServiceClient();

    // Prepare the request message.
    $request = (new SearchRequest())
        ->setServingConfig($formattedServingConfig);

    // Call the API and handle any network failures.
    try {
        /** @var PagedListResponse $response */
        $response = $searchServiceClient->search($request);

        /** @var SearchResult $element */
        foreach ($response as $element) {
            printf('Element data: %s' . PHP_EOL, $element->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample 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,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedServingConfig = SearchServiceClient::servingConfigName(
        '[PROJECT]',
        '[LOCATION]',
        '[DATA_STORE]',
        '[SERVING_CONFIG]'
    );

    search_sample($formattedServingConfig);
}

Python

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

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

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

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"          # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"
# search_query = "YOUR_SEARCH_QUERY"


def search_sample(
    project_id: str,
    location: str,
    engine_id: str,
    search_query: str,
) -> discoveryengine.services.search_service.pagers.SearchPager:
    #  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.SearchServiceClient(client_options=client_options)

    # The full resource name of the search app serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_config"

    # Optional - only supported for unstructured data: Configuration options for search.
    # Refer to the `ContentSearchSpec` reference for all supported fields:
    # https://cloud.google.com/python/docs/reference/discoveryengine/latest/google.cloud.discoveryengine_v1.types.SearchRequest.ContentSearchSpec
    content_search_spec = discoveryengine.SearchRequest.ContentSearchSpec(
        # For information about snippets, refer to:
        # https://cloud.google.com/generative-ai-app-builder/docs/snippets
        snippet_spec=discoveryengine.SearchRequest.ContentSearchSpec.SnippetSpec(
            return_snippet=True
        ),
        # For information about search summaries, refer to:
        # https://cloud.google.com/generative-ai-app-builder/docs/get-search-summaries
        summary_spec=discoveryengine.SearchRequest.ContentSearchSpec.SummarySpec(
            summary_result_count=5,
            include_citations=True,
            ignore_adversarial_query=True,
            ignore_non_summary_seeking_query=True,
            model_prompt_spec=discoveryengine.SearchRequest.ContentSearchSpec.SummarySpec.ModelPromptSpec(
                preamble="YOUR_CUSTOM_PROMPT"
            ),
            model_spec=discoveryengine.SearchRequest.ContentSearchSpec.SummarySpec.ModelSpec(
                version="stable",
            ),
        ),
    )

    # Refer to the `SearchRequest` reference for all supported fields:
    # https://cloud.google.com/python/docs/reference/discoveryengine/latest/google.cloud.discoveryengine_v1.types.SearchRequest
    request = discoveryengine.SearchRequest(
        serving_config=serving_config,
        query=search_query,
        page_size=10,
        content_search_spec=content_search_spec,
        query_expansion_spec=discoveryengine.SearchRequest.QueryExpansionSpec(
            condition=discoveryengine.SearchRequest.QueryExpansionSpec.Condition.AUTO,
        ),
        spell_correction_spec=discoveryengine.SearchRequest.SpellCorrectionSpec(
            mode=discoveryengine.SearchRequest.SpellCorrectionSpec.Mode.AUTO
        ),
        # Optional: Use fine-tuned model for this request
        # custom_fine_tuning_spec=discoveryengine.CustomFineTuningSpec(
        #     enable_search_adaptor=True
        # ),
    )

    page_result = client.search(request)

    # Handle the response
    for response in page_result:
        print(response)

    return page_result

Ruby

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

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

require "google/cloud/discovery_engine/v1beta"

##
# Snippet for the search call in the SearchService 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::V1beta::SearchService::Client#search.
#
def search
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::DiscoveryEngine::V1beta::SearchService::Client.new

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

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

  # The returned object is of type Gapic::PagedEnumerable. You can iterate
  # over elements, and API calls will be issued to fetch pages as needed.
  result.each do |item|
    # Each element is of type ::Google::Cloud::DiscoveryEngine::V1beta::SearchResponse::SearchResult.
    p item
  end
end

קבלת תוצאות חיפוש לאפליקציה עם נתוני אתר (מפתח API)

אם רוצים לאמת את הפעלת method החיפוש באמצעות מפתח API במקום להשתמש ב-OAuth 2.0 דרך חשבון שירות או חשבון משתמש, צריך לפעול לפי ההליך הזה, שבו משתמשים בשיטה searchLite. לשיטה searchLite יש את אותן תכונות כמו לשיטה search, אבל אפשר להשתמש בה רק כדי לחפש באתרים ציבוריים.

השיטה searchLite מתאימה במיוחד בתנאים הבאים:

  • יש לכם אתר סטטי שאי אפשר להגדיר בו OAuth 2.0 דרך חשבון שירות או חשבון משתמש.

  • עברתם לחיפוש מבוסס סוכנים מ-Custom Search Site Restricted API בפורמט JSON של Programmable Search Engine.

  • לא רוצים להשתמש בווידג'ט החיפוש.

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

כדי להפעיל את ה-method ‏servingConfigs.searchLite, אתם צריכים מפתח API. אם אין לכם מפתח API, צריך להשלים את שלב 1 במאמר פריסת אפליקציית החיפוש (מפתח API).

התהליך

REST

כדי להשתמש ב-API כדי לקבל תוצאות חיפוש של אפליקציה עם נתונים של אתר ציבורי שאומתו באמצעות מפתח API, משתמשים ב-method‏ engines.servingConfigs.searchLite:

  1. מאתרים את מזהה האפליקציה. אם כבר יש לכם מזהה אפליקציה, דלגו לשלב הבא.

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

      מעבר אל 'אפליקציות'

    2. בדף אפליקציות, מאתרים את שם האפליקציה ומעתיקים את המזהה שלה מהעמודה מזהה.

  2. מריצים את פקודת ה-Curl הבאה כדי לקבל תוצאות חיפוש:

    curl -X POST -H "Content-Type: application/json" \
    "https://discoveryengine.googleapis.com/v1/projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search:searchLite?key=API_KEY" \
    -d '{
    "servingConfig": "projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search",
    "query": "QUERY",
    "userPseudoId": "USER_PSEUDO_ID"
    }'
    

    מחליפים את מה שכתוב בשדות הבאים:

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .

    • API_KEY: מחרוזת מפתח ה-API.

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .

    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים שרוצים לשלוח אליה שאילתה.

    • QUERY: טקסט השאילתה לחיפוש.

    • USER_PSEUDO_ID: מחרוזת בקידוד UTF-8, שמשמשת כמזהה ייחודי פסאודונימי למעקב אחרי המשתמשים. האורך המקסימלי הוא 128 תווים. ‫Google ממליצה מאוד להשתמש בשדה הזה כי הוא משפר את הביצועים של המודל ואת איכות ההתאמה האישית. אפשר להשתמש בקובץ Cookie של HTTP בשדה הזה, כדי לזהות באופן ייחודי מבקר במכשיר יחיד. הנה כמה דברים חשובים שכדאי לזכור:

      • המזהה הזה לא משתנה כשהמבקר נכנס לאתר או יוצא ממנו.
      • אסור להגדיר את אותו מזהה למשתמשים שונים בשדה הזה. במקרים אחרים, שימוש באותו מזהה משתמש לכמה משתמשים עלול לשלב היסטוריית אירועים של משתמשים שונים ולהפחית את איכות המודל.
      • השדה הזה לא יכול לכלול פרטים אישיים מזהים (PII).
      • לכל בקשת חיפוש או בקשת עיון, השדה הזה צריך להיות ממופה לשדה userPseudoId המתאים באירועי המשתמש.

      מידע נוסף זמין במאמר userPseudoId.

Python

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

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


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

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"          # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"
# api_key = "YOUR_API_KEY"
# search_query = "YOUR_SEARCH_QUERY"


def search_lite_sample(
    project_id: str,
    location: str,
    engine_id: str,
    api_key: str,
    search_query: str,
) -> discoveryengine.services.search_service.pagers.SearchLitePager:

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

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

    # The full resource name of the search app serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_config"

    # Refer to the `SearchRequest` reference for all supported fields:
    # https://cloud.google.com/python/docs/reference/discoveryengine/latest/google.cloud.discoveryengine_v1.types.SearchRequest
    request = discoveryengine.SearchRequest(
        serving_config=serving_config,
        query=search_query,
    )

    page_result = client.search_lite(request)

    # Handle the response
    for response in page_result:
        print(response)

    return page_result

קבלת תוצאות חיפוש לאפליקציה עם נתונים מובְנים או לא מובְנים

אפשר לראות תצוגה מקדימה של תוצאות החיפוש במסוף Google Cloud או לקבל תוצאות חיפוש באמצעות ה-API.

המסוף

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

  1. פותחים את הדף Preview במסוף.
  2. מקלידים שאילתת חיפוש.

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

  3. (אופציונלי) אם קישרתם כמה מאגרי נתונים לאפליקציה אבל אתם רוצים לקבל תוצאות רק ממאגר נתונים ספציפי, בוחרים את מאגר הנתונים שממנו רוצים לקבל תוצאות.

  4. מקישים על Enter כדי לשלוח את השאילתה.

    רשימה של תוצאות החיפוש מופיעה מתחת לסרגל החיפוש.

    לנתונים מובְנים, חלים התנאים הבאים:

    • אם מיפויי המאפיינים לא מוגדרים בConfigurations (הגדרות) > Configure fields in results (הגדרת שדות בתוצאות), תוצאות החיפוש מוצגות כרשימה של שמות וערכים של מאפיינים גולמיים.

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

    • אם צוינו היבטים כלשהם בהגדרות > הגדרות היבטים, הם יוצגו באותו אופן.

REST

כדי להשתמש ב-API כדי לקבל תוצאות חיפוש של אפליקציה עם נתונים מובנים או לא מובנים, משתמשים ב-method‏ engines.servingConfigs.search:

  1. מאתרים את מזהה האפליקציה. אם כבר יש לכם מזהה אפליקציה, דלגו לשלב הבא.

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

      מעבר אל 'אפליקציות'

    2. בדף אפליקציות, מאתרים את שם האפליקציה ומעתיקים את המזהה שלה מהעמודה מזהה.

  2. מקבלים תוצאות חיפוש.

    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/engines/APP_ID/servingConfigs/default_search:search" \
    -d '{
    "query": "QUERY",
    "userPseudoId": "USER_PSEUDO_ID",
    "pageSize": "PAGE_SIZE",
    "offset": "OFFSET",
    "orderBy": "ORDER_BY",
    "filter": "FILTER",
    "boostSpec": "BOOST_SPEC",
    "facetSpec": "FACET_SPEC",
    "queryExpansionSpec": "QUERY_EXPANSION_SPEC",
    "spellCorrectionSpec": "SPELL_CORRECTION_SPEC",
    "contentSearchSpec": "CONTENT_SEARCH_SPEC",
    "dataStoreSpecs": [{"DATA_STORE_SPEC"}],
    }'
    

    מחליפים את מה שכתוב בשדות הבאים:

    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים שרוצים לשלוח אליה שאילתה.
    • QUERY: טקסט השאילתה לחיפוש.
    • USER_PSEUDO_ID: מחרוזת בקידוד UTF-8, שמשמשת כמזהה ייחודי פסאודונימי למעקב אחרי המשתמשים. האורך המקסימלי הוא 128 תווים. ‫Google ממליצה מאוד להשתמש בשדה הזה כי הוא משפר את הביצועים של המודל ואת איכות ההתאמה האישית. אפשר להשתמש בקובץ Cookie של HTTP בשדה הזה, כדי לזהות באופן ייחודי מבקר במכשיר יחיד. הנה כמה דברים חשובים שכדאי לזכור:

      • המזהה הזה לא משתנה כשהמבקר נכנס לאתר או יוצא ממנו.
      • אסור להגדיר את אותו מזהה למשתמשים שונים בשדה הזה. במקרים אחרים, שימוש באותו מזהה משתמש לכמה משתמשים עלול לשלב היסטוריית אירועים של משתמשים שונים ולהפחית את איכות המודל.
      • השדה הזה לא יכול לכלול פרטים אישיים מזהים (PII).
      • לכל בקשת חיפוש או בקשת עיון, השדה הזה צריך להיות ממופה לשדה userPseudoId המתאים באירועי המשתמש.

      מידע נוסף זמין במאמר userPseudoId.

    • PAGE_SIZE: מספר התוצאות שמוחזרות על ידי החיפוש. הגודל המקסימלי המותר של הדף תלוי בסוג הנתונים. אם גודל הדף גדול מהערך המקסימלי, הוא ישתנה לערך המקסימלי.

      • אתרים עם הוספה בסיסית לאינדקס: ברירת מחדל 10, מקסימום 25
      • אתרים עם הוספה מתקדמת לאינדקס: ברירת מחדל 25, מקסימום 50
      • אחר: ברירת מחדל 50, מקסימום 100
    • OFFSET: אופציונלי. האינדקס ההתחלתי של התוצאות. ערך ברירת המחדל הוא 0.

      לדוגמה, אם ההיסט הוא 2, גודל הדף הוא 10 ויש 15 תוצאות להחזרה, התוצאות 2 עד 11 מוחזרות בדף הראשון.

    • ORDER_BY: אופציונלי. הסדר שבו התוצאות מסודרות.

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

      לדוגמה: color: ANY("red", "blue") AND score: IN(*, 100.0e)

      מידע נוסף מופיע במאמר בנושא סינון חיפוש של נתונים מובְנים או לא מובְנים.

    • BOOST_SPEC: אופציונלי. מפרט להדגשת מסמכים או להסתרתם. ערכים:

      • BOOST: מספר בשיטת נקודה צפה בטווח [‎-1,1]. אם הערך שלילי, התוצאות יורדות בדירוג (הן יופיעו בחלק התחתון של התוצאות). אם הערך חיובי, התוצאות מקודמות (מופיעות גבוה יותר בתוצאות).
      • CONDITION: ביטוי של מסנן טקסט לבחירת המסמכים שיוחלו עליהם הגדלות. המסנן צריך להחזיר ערך בוליאני. דוגמאות לביטויי סינון מופיעות במאמרים תחביר של ביטויי סינון ותחביר של הוספה מתקדמת לאינדקס.

      מידע על שיפור תוצאות חיפוש מובנה זמין במאמר שיפור תוצאות חיפוש.

    • FACET_SPEC: אופציונלי. מפרט של היבט לביצוע חיפוש עם היבטים.

    • QUERY_EXPANSION_SPEC: אופציונלי. הגדרה שקובעת באילו תנאים יתבצע הרחבת שאילתה. ערך ברירת המחדל הוא DISABLED.

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

    • CONTENT_SEARCH_SPEC: אופציונלי. לקבלת תקצירים, תשובות חילוץ, פלחים חילוץ וסיכומי חיפוש. לנתונים לא מובנים בלבד. למידע נוסף:

    • DATA_STORE_SPEC: מסננים של מאגר נתונים ספציפי לחיפוש. אפשר להשתמש באפשרות הזו אם אפליקציית החיפוש שלכם מקושרת לכמה מאגרי נתונים.

    • צפייה בתוצאות חיפוש מודרך בתגובה לחיפוש:

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

      בדוגמה הזו לתגובה, נעשה שימוש בצבע ירוק כדי לצמצם את תוצאות החיפוש על ידי שליחת בקשת חיפוש חדשה עם שדה הסינון שצוין כ-_gs.color: ANY("green"):

      {
      "guidedSearchResult": {
        "refinementAttributes": [
          {
            "attributeKey": "_gs.color",
            "attributeValue": "green"
          },
          {
            "attributeKey": "_gs.category",
            "attributeValue": "shoe"
          }
        ]
      }
      }
      

C#

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

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

using Google.Api.Gax;
using Google.Cloud.DiscoveryEngine.V1Beta;
using Google.Protobuf.WellKnownTypes;
using System;

public sealed partial class GeneratedSearchServiceClientSnippets
{
    /// <summary>Snippet for Search</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 SearchRequestObject()
    {
        // Create client
        SearchServiceClient searchServiceClient = SearchServiceClient.Create();
        // Initialize request argument(s)
        SearchRequest request = new SearchRequest
        {
            ServingConfigAsServingConfigName = ServingConfigName.FromProjectLocationDataStoreServingConfig("[PROJECT]", "[LOCATION]", "[DATA_STORE]", "[SERVING_CONFIG]"),
            BranchAsBranchName = BranchName.FromProjectLocationDataStoreBranch("[PROJECT]", "[LOCATION]", "[DATA_STORE]", "[BRANCH]"),
            Query = "",
            Offset = 0,
            Filter = "",
            OrderBy = "",
            FacetSpecs =
            {
                new SearchRequest.Types.FacetSpec(),
            },
            BoostSpec = new SearchRequest.Types.BoostSpec(),
            Params = { { "", new Value() }, },
            QueryExpansionSpec = new SearchRequest.Types.QueryExpansionSpec(),
            SpellCorrectionSpec = new SearchRequest.Types.SpellCorrectionSpec(),
            UserPseudoId = "",
            ImageQuery = new SearchRequest.Types.ImageQuery(),
            SafeSearch = false,
            UserInfo = new UserInfo(),
            UserLabels = { { "", "" }, },
            EmbeddingSpec = new SearchRequest.Types.EmbeddingSpec(),
            ContentSearchSpec = new SearchRequest.Types.ContentSearchSpec(),
            RankingExpression = "",
            NaturalLanguageQueryUnderstandingSpec = new SearchRequest.Types.NaturalLanguageQueryUnderstandingSpec(),
            CanonicalFilter = "",
            SearchAsYouTypeSpec = new SearchRequest.Types.SearchAsYouTypeSpec(),
            DataStoreSpecs =
            {
                new SearchRequest.Types.DataStoreSpec(),
            },
            LanguageCode = "",
            RegionCode = "",
            SessionAsSessionName = SessionName.FromProjectLocationDataStoreSession("[PROJECT]", "[LOCATION]", "[DATA_STORE]", "[SESSION]"),
            SessionSpec = new SearchRequest.Types.SessionSpec(),
            RelevanceThreshold = SearchRequest.Types.RelevanceThreshold.Unspecified,
            PersonalizationSpec = new SearchRequest.Types.PersonalizationSpec(),
            OneBoxPageSize = 0,
            RankingExpressionBackend = SearchRequest.Types.RankingExpressionBackend.Unspecified,
        };
        // Make the request
        PagedEnumerable<SearchResponse, SearchResponse.Types.SearchResult> response = searchServiceClient.Search(request);

        // Iterate over all response items, lazily performing RPCs as required
        foreach (SearchResponse.Types.SearchResult item in response)
        {
            // Do something with each item
            Console.WriteLine(item);
        }

        // Or iterate over pages (of server-defined size), performing one RPC per page
        foreach (SearchResponse page in response.AsRawResponses())
        {
            // Do something with each page of items
            Console.WriteLine("A page of results:");
            foreach (SearchResponse.Types.SearchResult item in page)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
        }

        // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
        int pageSize = 10;
        Page<SearchResponse.Types.SearchResult> singlePage = response.ReadPage(pageSize);
        // Do something with the page of items
        Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
        foreach (SearchResponse.Types.SearchResult item in singlePage)
        {
            // Do something with each item
            Console.WriteLine(item);
        }
        // Store the pageToken, for when the next page is required.
        string nextPageToken = singlePage.NextPageToken;
    }
}

Java

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

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


import com.google.cloud.discoveryengine.v1.SearchRequest;
import com.google.cloud.discoveryengine.v1.SearchResponse;
import com.google.cloud.discoveryengine.v1.SearchServiceClient;
import com.google.cloud.discoveryengine.v1.SearchServiceSettings;
import com.google.cloud.discoveryengine.v1.ServingConfigName;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class Search {
  public static void main() throws IOException, ExecutionException {
    // TODO(developer): Replace these variables before running the sample.
    // Project ID or project number of the Cloud project you want to use.
    String projectId = "PROJECT_ID";
    // Location of the data store. Options: "global", "us", "eu"
    String location = "global";
    // Collection containing the data store.
    String collectionId = "default_collection";
    // Data store ID.
    String dataStoreId = "DATA_STORE_ID";
    // Serving configuration. Options: "default_search"
    String servingConfigId = "default_search";
    // Search Query for the data store.
    String searchQuery = "Google";
    search(projectId, location, collectionId, dataStoreId, servingConfigId, searchQuery);
  }

  /** Performs a search on a given datastore. */
  public static void search(
      String projectId,
      String location,
      String collectionId,
      String dataStoreId,
      String servingConfigId,
      String searchQuery)
      throws IOException, ExecutionException {
    // For more information, refer to:
    // https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
    String endpoint = (location.equals("global")) 
        ? String.format("discoveryengine.googleapis.com:443", location) 
        : String.format("%s-discoveryengine.googleapis.com:443", location);
    SearchServiceSettings settings =
        SearchServiceSettings.newBuilder().setEndpoint(endpoint).build();
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `searchServiceClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (SearchServiceClient searchServiceClient = SearchServiceClient.create(settings)) {
      SearchRequest request =
          SearchRequest.newBuilder()
              .setServingConfig(
                  ServingConfigName.formatProjectLocationCollectionDataStoreServingConfigName(
                      projectId, location, collectionId, dataStoreId, servingConfigId))
              .setQuery(searchQuery)
              .setPageSize(10)
              .build();
      SearchResponse response = searchServiceClient.search(request).getPage().getResponse();
      for (SearchResponse.SearchResult element : response.getResultsList()) {
        System.out.println("Response content: " + element);
      }
    }
  }
}

Node.js

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

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'YOUR_LOCATION';              // Options: 'global', 'us', 'eu'
// const collectionId = 'default_collection';     // Options: 'default_collection'
// const dataStoreId = 'YOUR_DATA_STORE_ID'       // Create in Cloud Console
// const servingConfigId = 'default_config';      // Options: 'default_config'
// const searchQuery = 'Google';

const {SearchServiceClient} = require('@google-cloud/discoveryengine').v1beta;

// For more information, refer to:
// https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_store
const apiEndpoint =
  location === 'global'
    ? 'discoveryengine.googleapis.com'
    : `${location}-discoveryengine.googleapis.com`;

// Instantiates a client
const client = new SearchServiceClient({apiEndpoint: apiEndpoint});

async function search() {
  // The full resource name of the search engine serving configuration.
  // Example: projects/{projectId}/locations/{location}/collections/{collectionId}/dataStores/{dataStoreId}/servingConfigs/{servingConfigId}
  // You must create a search engine in the Cloud Console first.
  const name = client.projectLocationCollectionDataStoreServingConfigPath(
    projectId,
    location,
    collectionId,
    dataStoreId,
    servingConfigId
  );

  const request = {
    pageSize: 10,
    query: searchQuery,
    servingConfig: name,
  };

  const IResponseParams = {
    ISearchResult: 0,
    ISearchRequest: 1,
    ISearchResponse: 2,
  };

  // Perform search request
  const response = await client.search(request, {
    // Warning: Should always disable autoPaginate to avoid iterate through all pages.
    //
    // By default NodeJS SDK returns an iterable where you can iterate through all
    // search results instead of only the limited number of results requested on
    // pageSize, by sending multiple sequential search requests page-by-page while
    // iterating, until it exhausts all the search results. This will be unexpected and
    // may cause high Search API usage and long wait time, especially when the matched
    // document numbers are huge.
    autoPaginate: false,
  });
  const results = response[IResponseParams.ISearchResponse].results;

  for (const result of results) {
    console.log(result);
  }
}

PHP

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

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

use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;
use Google\Cloud\DiscoveryEngine\V1beta\Client\SearchServiceClient;
use Google\Cloud\DiscoveryEngine\V1beta\SearchRequest;
use Google\Cloud\DiscoveryEngine\V1beta\SearchResponse\SearchResult;

/**
 * Performs a search.
 *
 * @param string $formattedServingConfig The resource name of the Search serving config, such as
 *                                       `projects/&#42;/locations/global/collections/default_collection/engines/&#42;/servingConfigs/default_serving_config`,
 *                                       or
 *                                       `projects/&#42;/locations/global/collections/default_collection/dataStores/default_data_store/servingConfigs/default_serving_config`.
 *                                       This field is used to identify the serving configuration name, set
 *                                       of models used to make the search. Please see
 *                                       {@see SearchServiceClient::servingConfigName()} for help formatting this field.
 */
function search_sample(string $formattedServingConfig): void
{
    // Create a client.
    $searchServiceClient = new SearchServiceClient();

    // Prepare the request message.
    $request = (new SearchRequest())
        ->setServingConfig($formattedServingConfig);

    // Call the API and handle any network failures.
    try {
        /** @var PagedListResponse $response */
        $response = $searchServiceClient->search($request);

        /** @var SearchResult $element */
        foreach ($response as $element) {
            printf('Element data: %s' . PHP_EOL, $element->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample 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,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedServingConfig = SearchServiceClient::servingConfigName(
        '[PROJECT]',
        '[LOCATION]',
        '[DATA_STORE]',
        '[SERVING_CONFIG]'
    );

    search_sample($formattedServingConfig);
}

Python

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

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

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

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_LOCATION"          # Values: "global", "us", "eu"
# engine_id = "YOUR_APP_ID"
# search_query = "YOUR_SEARCH_QUERY"


def search_sample(
    project_id: str,
    location: str,
    engine_id: str,
    search_query: str,
) -> discoveryengine.services.search_service.pagers.SearchPager:
    #  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.SearchServiceClient(client_options=client_options)

    # The full resource name of the search app serving config
    serving_config = f"projects/{project_id}/locations/{location}/collections/default_collection/engines/{engine_id}/servingConfigs/default_config"

    # Optional - only supported for unstructured data: Configuration options for search.
    # Refer to the `ContentSearchSpec` reference for all supported fields:
    # https://cloud.google.com/python/docs/reference/discoveryengine/latest/google.cloud.discoveryengine_v1.types.SearchRequest.ContentSearchSpec
    content_search_spec = discoveryengine.SearchRequest.ContentSearchSpec(
        # For information about snippets, refer to:
        # https://cloud.google.com/generative-ai-app-builder/docs/snippets
        snippet_spec=discoveryengine.SearchRequest.ContentSearchSpec.SnippetSpec(
            return_snippet=True
        ),
        # For information about search summaries, refer to:
        # https://cloud.google.com/generative-ai-app-builder/docs/get-search-summaries
        summary_spec=discoveryengine.SearchRequest.ContentSearchSpec.SummarySpec(
            summary_result_count=5,
            include_citations=True,
            ignore_adversarial_query=True,
            ignore_non_summary_seeking_query=True,
            model_prompt_spec=discoveryengine.SearchRequest.ContentSearchSpec.SummarySpec.ModelPromptSpec(
                preamble="YOUR_CUSTOM_PROMPT"
            ),
            model_spec=discoveryengine.SearchRequest.ContentSearchSpec.SummarySpec.ModelSpec(
                version="stable",
            ),
        ),
    )

    # Refer to the `SearchRequest` reference for all supported fields:
    # https://cloud.google.com/python/docs/reference/discoveryengine/latest/google.cloud.discoveryengine_v1.types.SearchRequest
    request = discoveryengine.SearchRequest(
        serving_config=serving_config,
        query=search_query,
        page_size=10,
        content_search_spec=content_search_spec,
        query_expansion_spec=discoveryengine.SearchRequest.QueryExpansionSpec(
            condition=discoveryengine.SearchRequest.QueryExpansionSpec.Condition.AUTO,
        ),
        spell_correction_spec=discoveryengine.SearchRequest.SpellCorrectionSpec(
            mode=discoveryengine.SearchRequest.SpellCorrectionSpec.Mode.AUTO
        ),
        # Optional: Use fine-tuned model for this request
        # custom_fine_tuning_spec=discoveryengine.CustomFineTuningSpec(
        #     enable_search_adaptor=True
        # ),
    )

    page_result = client.search(request)

    # Handle the response
    for response in page_result:
        print(response)

    return page_result

Ruby

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

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

require "google/cloud/discovery_engine/v1beta"

##
# Snippet for the search call in the SearchService 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::V1beta::SearchService::Client#search.
#
def search
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::DiscoveryEngine::V1beta::SearchService::Client.new

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

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

  # The returned object is of type Gapic::PagedEnumerable. You can iterate
  # over elements, and API calls will be issued to fetch pages as needed.
  result.each do |item|
    # Each element is of type ::Google::Cloud::DiscoveryEngine::V1beta::SearchResponse::SearchResult.
    p item
  end
end

קבלת ציוני רלוונטיות של מסמכים עם תוצאות החיפוש

ציוני הרלוונטיות של המסמכים מבוססים על הדמיון בין השאילתה לבין המסמך. הציונים מחולקים ל-11 קטגוריות בטווח: 0, 0.1, 0.2 ועד 1.0. ככל שהציון גבוה יותר, כך המסמך רלוונטי יותר.

כדאי להשתמש בציוני הרלוונטיות של המסמכים בתרחישי השימוש הבאים:

  • סינון אחרי החיפוש על סמך ציון הרלוונטיות כדי להסיר תוצאות לא רלוונטיות

  • דירוג אחרי החיפוש או כקלט לאפליקציות אחרות

  • ניפוי באגים: ציוני הרלוונטיות יכולים לספק תובנות לגבי הסיבות להחזרת תוצאות חיפוש מסוימות

לכל תוצאת חיפוש אפשר להחזיר ציון רלוונטיות:

  "results": [
    {
      "id": "DOCUMENT_ID",
      "document": {
      ...
      },
      "modelScores": {
        "relevance_score": {
          "values": [
            DOCUMENT-RELEVANCE-SCORE
          ]
        }
      }
    },
  ...
  ]

אפשר גם לעיין בדוגמה לפקודה שמופיעה בהמשך.

לפני שמתחילים: מוודאים שאפליקציית החיפוש משויכת למאגר נתונים מובְנים או לא מובְנים. כלומר, אי אפשר להחזיר ציוני רלוונטיות של מסמכים באפליקציה לחיפוש באתר.

REST

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

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

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

      מעבר אל 'אפליקציות'

    2. בדף אפליקציות, מאתרים את שם האפליקציה ומעתיקים את המזהה שלה מהעמודה מזהה.

  2. מריצים את פקודת ה-Curl הבאה כדי לקבל את הציונים שמוחזרים עם תוצאות החיפוש.

    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/engines/APP_ID/servingConfigs/default_search:search" \
    -d '{
         "servingConfig": "projects/PROJECT_ID/locations/global/collections/default_collection/engines/APP_ID/servingConfigs/default_search",
         "query": "QUERY",
         "relevanceScoreSpec": {
           "returnRelevanceScore": true
         }
    }'
    
    • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
    • APP_ID: המזהה של אפליקציית חיפוש מבוסס סוכנים שרוצים לשלוח אליה שאילתה.
    • QUERY: טקסט השאילתה לחיפוש.

סיכום החיפוש משתנה בהתאם למודל

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

  • כדי לשנות או להציג את מודל ה-LLM שבו נעשה שימוש בדף תצוגה מקדימה בממשק המשתמש (נתמך רק באפליקציות לחיפוש מתקדם ובאפליקציות בתחום הבריאות).

    1. עוברים לדף Configurations (הגדרות) של האפליקציה > הכרטיסייה UI (ממשק משתמש).
    2. בוחרים סוג חיפוש:

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

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

    השלבים הבאים

  • הוספת ווידג'ט החיפוש לדף אינטרנט

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