获取搜索结果

此页面介绍了如何使用 Google Cloud 控制台预览搜索结果, 搜索结果。

此外,您无需创建搜索微件并将其添加到您的网页, 您可以进行 API 调用并将这些调用集成到您的服务器中 应用。本页面包含有关如何执行搜索查询的代码示例, 将 gRPC 客户端库与服务账号搭配使用

搜索摘要因设备型号而异

如果您为查询生成搜索摘要,可能会发现控制台结果和 API 结果中的摘要有所不同。如果您 原因可能是控制台使用的是其他 LLM 模型 。本页中的 curl 和代码示例使用的是稳定的 LLM 模型。

  • 如需更改或查看界面预览页面中使用的 LLM 模型,请前往应用的配置页面 > 界面标签页。

  • 对于方法调用,如需使用除稳定模型以外的 LLM 模型,请参阅 指定汇总模型

获取包含网站数据的应用的搜索结果

控制台

使用 Google Cloud 控制台预览包含网站的应用的搜索结果 数据,请按以下步骤操作:

  1. 在 Google Cloud 控制台中,前往 Agent Builder 页面。

    Agent Builder

  2. 点击要修改的应用的名称。

  3. 点击预览

  4. 在控制台中打开预览页面。

  5. 可选:如果您已将多个数据存储区关联到您的应用,但想要 来自特定数据存储区的结果,请选择该数据存储区以获取 结果。

  6. 输入搜索查询。

    1. 如果您启用了自动补全功能,则在输入内容时,搜索栏下方会显示自动补全建议列表。
  7. 点击 Enter 键提交查询。

    1. 搜索栏下方会显示搜索结果列表。
    2. 每个结果均包含标题、摘要和网址。
    3. 点击某个结果会打开该网址。
  8. 点击结果列表下方的箭头,即可加载下一页结果。

REST

若要使用该 API 获取包含网站数据的应用的搜索结果, 使用 engines.servingConfigs.search 方法:

  1. 找到您的应用 ID。如果您已经有应用 ID,请跳至下一步。

    1. 在 Google Cloud 控制台中,前往 Agent Builder 页面。

      前往“应用”

    2. 应用页面上,找到应用的名称,并从以下位置获取应用 ID: ID 列中的值。

  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"
     },
     "dataStoreSpec": {"DATA_STORE_SPEC"}
    }'
    
    • PROJECT_ID:您的 Google Cloud 项目的 ID。
    • APP_ID:您在创建 Vertex AI Search 应用时 查询。
    • QUERY:要搜索的查询文本。
    • PAGE_SIZE:搜索返回的结果数。 允许的页面大小上限取决于数据类型。大于最大值的页面大小会强制转换为最大值。

      • 采用基本索引的网站:默认 10,上限 25
      • 启用了高级索引编制的网站:默认 25,上限 50
      • 其他:默认 50,最大 100
    • OFFSET:结果的起始索引。默认 值为 0。

      例如,如果偏移量为 2,则页面大小为 10,而其值为 15 要返回的结果,在第一个结果返回结果 2 到 12 页面。

    • ORDER_BY:结果的排列顺序。通过 属性必须具有数值解释,例如, 价格或日期。

    • USER_COUNTRY_CODE:用户所在的位置。此键值对是 params 映射字段唯一支持的条目。默认值为空。如需了解可接受的值,请参阅可编程搜索引擎 JSON API 参考文档中的国家/地区代码

    • SEARCH_TYPE:要执行的搜索类型。文档搜索的默认值为 0。图片搜索的另一个支持的值为 1。

    • FILTER:一个文本字段,用于使用 过滤条件表达式。默认值为空字符串。有关 有关使用 filter 字段的信息,请参阅过滤网站 搜索

    • BOOST_SPEC:可选。一个规范 提升或掩埋文档。值:

      • BOOST: 介于 -1 和 1 之间的浮点数。该值为 则结果会降位(在 结果)。如果值为正数,系统会升级结果 (这类广告显示在结果中靠前的位置)。
      • CONDITION: 文本过滤器表达式 以选择要应用升位的文档。过滤器必须评估 布尔值。 要了解如何对结构化搜索进行升位,请参阅对搜索结果进行升位
    • RESULT_MODE:确定是否返回搜索结果 以完整文档或分块的形式呈现。要获取数据块,数据存储区 您需要开启文档分块功能可接受的值为 documentschunks。为数据存储区启用分块时,默认值为 chunks。否则,默认值为 documents。如需了解文档分块,请参阅解析和分块文档。此字段处于公开预览阶段;如需使用它,请在 curl 命令中将 v1 更改为 v1alpha

    • DATA_STORE_SPEC:特定数据存储区的过滤条件, 搜索范围。如果您的搜索应用连接到多个数据存储区,但您希望从特定数据存储区获取结果,请使用 dataStoreSpec

C#

有关详情,请参阅 Vertex AI Agent Builder C# API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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,
        };
        // 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

有关详情,请参阅 Vertex AI Agent Builder Java API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


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

有关详情,请参阅 Vertex AI Agent Builder Node.js API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

有关详情,请参阅 Vertex AI Agent Builder PHP API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解详情,请参阅 Vertex AI Agent Builder Python API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

from typing import List

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,
) -> List[discoveryengine.SearchResponse]:
    #  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
        ),
    )

    response = client.search(request)
    print(response)

    return response

Ruby

如需了解详情,请参阅 Vertex AI Agent Builder Ruby API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

获取包含结构化或非结构化数据的应用的搜索结果

您可以通过 Google Cloud 控制台预览搜索结果或获取搜索结果 使用 API

控制台

使用 Google Cloud 控制台预览采用结构化规则的应用的搜索结果 或非结构化数据,请按以下步骤操作:

  1. 在控制台中打开预览页面。
  2. 输入搜索查询。
    1. 如果您在第 1 步中启用了自动补全功能,则在输入内容时,搜索栏下方会显示自动补全建议列表。
  3. (可选)如果您已将多个数据存储区连接到您的应用,但只希望从特定数据存储区获取结果,请选择要从中获取结果的数据存储区。
  4. 点击 Enter 提交查询。
    1. 搜索栏下方会显示搜索结果列表。
    2. 如果配置中未定义属性映射 页面上,每个搜索结果都显示为一个包含原始属性名称和值的列表。
    3. 是否在 Configurations 中保存了任何属性映射 页面上,搜索结果会显示您在 配置页面预览。
  5. 如果您在配置页面中指定了任何切面,它们也会以相同的方式显示。
  6. 点击结果列表下方的箭头以加载下一页结果。

REST

使用 API 获取结构化或非结构化应用的搜索结果 数据,请使用 engines.servingConfigs.search 方法:

  1. 找到您的应用 ID。如果您已经有应用 ID,请跳至下一步。

    1. 在 Google Cloud 控制台中,前往 Agent Builder 页面。

      前往“应用”页面

    2. 应用页面上,找到应用的名称,然后从 ID 列中获取应用的 ID。

  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",
    "dataStoreSpec": {"DATA_STORE_SPEC"},
    }'
    
    • PROJECT_ID:您的 Google Cloud 项目的 ID。
    • APP_ID:您在创建 Vertex AI Search 应用时 查询。
    • QUERY:要搜索的查询文本。
    • USER_PSEUDO_ID:可选。这是一个经过假名化处理的标识符,用于跟踪搜索访问者。Google 强烈建议您使用 从而提升模型性能和个性化 质量。您可以为此字段使用 HTTP Cookie,该 Cookie 可唯一标识单个设备上的访问者。此标识符不会改变 当访问者登录或退出网站时触发。请勿为多名用户将此字段设置为相同的标识符,否则系统会合并其事件历史记录,从而降低模型质量。不包含个人 个人身份信息 (PII)。
    • 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#

有关详情,请参阅 Vertex AI Agent Builder C# API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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,
        };
        // 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

有关详情,请参阅 Vertex AI Agent Builder Java API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


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

有关详情,请参阅 Vertex AI Agent Builder Node.js API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

如需了解详情,请参阅 Vertex AI Agent Builder PHP API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

有关详情,请参阅 Vertex AI Agent Builder Python API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

from typing import List

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,
) -> List[discoveryengine.SearchResponse]:
    #  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
        ),
    )

    response = client.search(request)
    print(response)

    return response

Ruby

如需了解详情,请参阅 Vertex AI Agent Builder Ruby API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

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

对于媒体搜索,Vertex AI Agent Builder 提供两种搜索行为:

  • 用户输入搜索查询,然后按 Enter 键。这是默认行为,与在微件中搜索和搜索非媒体(通用)应用的行为相同。请参阅获取结构化或非结构化应用的搜索结果 数据

  • 用户输入的每个字母后都会返回一个新的搜索结果。这称为“边输入边搜索”,对于通过电视遥控器等不太方便的界面输入搜索查询的用户而言,此功能尤为有用。

如需为媒体应用获取“边输入边搜索”结果,请执行以下操作:

控制台

如需使用 Google Cloud 控制台为 widget 应用启用“边输入边搜索”功能,请执行以下操作:

  1. 在 Google Cloud 控制台中,前往 Agent Builder 页面。

    Agent Builder

  2. 点击您要使用的媒体搜索应用的名称 即输即搜

  3. 点击配置

  4. 点击界面标签页。

  5. 点击启用即输即搜功能切换开关。

  6. 预览窗格中,开始输入查询。

    每次按键之后,搜索结果都会更新。

  7. 如要保留“边输入边搜索”设置,请点击保存并发布

REST

使用 dataStores.servingConfigs.search 方法获取 搜索结果:

  1. 找到您的应用 ID。如果您已经有应用 ID,请跳至下一步。

    1. 在 Google Cloud 控制台中,前往 Agent Builder 页面。

      前往“应用”

    2. 应用页面上,找到应用的名称,然后从 ID 列中获取应用的 ID。

  2. 运行以下 curl 命令以获取即输即搜结果。

    contentSearchSpec 之外的所有字段都可以与以下字段结合使用 searchAsYouTypeSpec 字段中的值。为清楚起见,我们已从 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 '{
    "query": "QUERY",
    "searchAsYouTypeSpec": {"condition": "ENABLED"}
    }'
    
    • PROJECT_ID:您的 Google Cloud 项目的 ID。
    • APP_ID:您在创建 Vertex AI Search 应用时 查询。
    • QUERY:要搜索的查询文本。

    点击此处查看 curl 命令示例。

    curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)"
    -H "Content-Type: application/json"
    "https://discoveryengine.googleapis.com/v1/projects/12345/locations/global/collections/default_collection/engines/my-app_4321/servingConfigs/default_search:search"
    -d '{
         "query": "midsummer night",
         "searchAsYouTypeSpec": {"condition": "ENABLED"}
        }'

后续步骤