検索結果を取得する

このページでは、 Google Cloud コンソールを使用して検索結果をプレビューし、API を使用して検索結果を取得する方法について説明します。

また、ウェブページに追加する検索ウィジェットを作成する代わりに、API 呼び出しを行って、それらの呼び出しをサーバーやアプリケーションに統合できます。このページでは、サービス アカウントで gRPC クライアント ライブラリを使用して検索クエリを作成する方法のコードサンプルを示します。

ウェブサイト データを含むアプリの検索結果を取得する

コンソール

Google Cloud コンソールを使用してウェブサイト データを含むアプリの検索結果をプレビューする手順は次のとおりです。

  1. Google Cloud コンソールで、[AI Applications] ページに移動します。

    AI Applications

  2. 編集するアプリの名前をクリックします。

  3. [プレビュー] をクリックします。

  4. コンソールで [プレビュー] ページを開きます。

  5. 省略可: 複数のデータストアをアプリに接続しているが、特定のデータストアの結果のみを取得したい場合は、結果を取得するデータストアを選択します。

  6. 検索語句を入力します。

    予測入力を有効にしている場合、入力すると検索バーの下に予測入力候補のリストが表示されます。

  7. Enter キーを押してクエリを送信します。

    • 検索バーの下に検索結果の一覧が表示されます。
    • 各検索結果には、タイトル、スニペット、URL が含まれます。
    • 検索結果をクリックすると、その URL が開きます。
    • アプリで高度な LLM 機能が有効になっている場合は、生成された回答も表示されることがあります。

REST

API を使用して、ウェブサイト データを含むアプリの検索結果を取得するには、engines.servingConfigs.search メソッドを使用します。

  1. アプリ ID を確認します。アプリ ID がすでにある場合は、次のステップに進みます。

    1. Google Cloud コンソールで、[AI Applications] ページに移動します。

      [アプリ] に移動

    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"
     },
     "userPseudoId": "USER_PSEUDO_ID",
     "dataStoreSpecs": [{"DATA_STORE_SPEC"}]
    }'
    

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

    • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
    • APP_ID: クエリする Vertex AI Search アプリの ID。
    • QUERY: 検索するクエリテキスト。
    • PAGE_SIZE: 検索によって返された結果の数。 許可される最大ページサイズは、データ型によって異なります。最大値を超えるページサイズは、最大値に強制変換されます。

      • 基本的なインデックス登録のウェブサイト: デフォルト 10、最大 25
      • 高度なインデックス登録が有効になっているウェブサイト: デフォルト 25、最大 50
      • その他: デフォルト 50、最大 100
    • OFFSET: 結果の開始インデックス。デフォルト値は 0 です。

      たとえば、オフセットが 2、ページサイズが 10、返される結果が 15 個ある場合、1 ページ目には 2 から 12 個の結果が返されます。

    • ORDER_BY: 結果が並べられる順序。並べ替えの基準となる属性は、数値として解釈できる必要があります(例: date)。詳しくは、ウェブ検索結果を並べ替えるをご覧ください。

    • USER_COUNTRY_CODE: ユーザーのロケーション。この Key-Value ペアは、params マップ フィールドでサポートされている唯一のエントリです。デフォルト値は空です。使用可能な値については、プログラマブル検索エンジンの JSON API リファレンス ドキュメントの国コードをご覧ください。

    • SEARCH_TYPE: 実行する検索のタイプ。デフォルト値は、ドキュメント検索の場合は 0 です。その他のサポートされている値は、画像検索の場合は 1 です。

    • FILTER: フィルタ式を使用して検索結果をフィルタリングするためのテキスト フィールド。デフォルト値は空文字列です。 filter フィールドの使用方法について詳しくは、ウェブサイト検索をフィルタするをご覧ください。

    • BOOST_SPEC: 省略可。ドキュメントをブーストまたは埋め込むための仕様。値:

      • BOOST: [-1,1] の範囲の浮動小数点数。値が負の場合、結果は降格されます(結果の下位に表示されます)。値が正の場合、結果は昇格されます(結果の上位に表示されます)。
      • CONDITION: ブーストを適用するドキュメントを選択するためのテキスト フィルタ式。フィルタはブール値に評価される必要があります。 構造化検索のブーストについては、検索結果をブーストするをご覧ください。
    • RESULT_MODE: 検索結果を完全なドキュメントとして返すか、チャンクで返すかを決定します。チャンクを取得するには、データストアでドキュメント チャンキングがオンになっている必要があります。指定できる値は documents および chunks です。データストアでチャンキングがオンの場合、デフォルト値は chunks です。それ以外の場合、デフォルトは documents です。ドキュメント チャンキングについては、ドキュメントの解析とチャンク処理をご覧ください。このフィールドは公開プレビュー版です。使用するには、curl コマンドで v1v1alpha に変更します。

    • USER_PSEUDO_ID: ユーザーをトラッキングする一意の仮名化 ID として機能する UTF-8 エンコード文字列。最大長は 128 文字です。このフィールドを使用すると、モデルのパフォーマンスとパーソナライズの品質が向上するため、このフィールドを使用することを強くおすすめします。このフィールドには HTTP Cookie を使用できます。これにより、1 つのデバイス上の訪問者を一意に識別できます。重要な考慮事項は次のとおりです。

      • この ID は、訪問者がウェブサイトにログインまたはログアウトしても変更されません。
      • このフィールドを複数のユーザーに対して同じ ID に設定しないでください。そうしないと、複数のユーザーに同じユーザー ID を使用すると、異なるユーザーのイベント履歴が統合され、モデルの品質が低下する可能性があります。
      • このフィールドに個人を特定できる情報(PII)を含めることはできません。
      • 特定の検索リクエストまたはブラウジング リクエストの場合、このフィールドはユーザー イベントの対応する userPseudoId フィールドにマッピングする必要があります。

      詳細については、userPseudoId をご覧ください。

    • DATA_STORE_SPEC: 検索対象の特定のデータストアのフィルタ。検索アプリが複数のデータストアに接続されているが、特定のデータストアの結果が必要な場合は、dataStoreSpecs を使用します。詳細については、DataStoreSpec をご覧ください。

C#

詳細については、Vertex AI Search C# API のリファレンス ドキュメントをご覧ください。

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

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

詳細については、Vertex AI Search Java API のリファレンス ドキュメントをご覧ください。

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


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 Search Node.js API のリファレンス ドキュメントをご覧ください。

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

/**
 * 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 Search PHP API のリファレンス ドキュメントをご覧ください。

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

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 Search Python API のリファレンス ドキュメントをご覧ください。

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

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

詳細については、Vertex AI Search Ruby API のリファレンス ドキュメントをご覧ください。

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

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 キー)

サービス アカウントまたはユーザー アカウントを介して OAuth 2.0 を使用する代わりに、API キーを使用して検索メソッド呼び出しを認証する場合は、searchLite メソッドを使用する次の手順を行います。searchLite メソッドは、一般公開ウェブサイトの検索にのみ使用できる点を除き、search メソッドと同じ機能を備えています。

searchLite メソッドは、次のような条件で特に適しています。

  • サービス アカウントまたはユーザー アカウントを介して OAuth 2.0 を設定することが現実的ではない静的ウェブサイトがある。

  • プログラム可能検索エンジンのカスタム検索サイト制限付き JSON API から Vertex AI Search に移行した。

  • 検索ウィジェットを使用しない。

始める前に

servingConfigs.searchLite メソッドを呼び出すには、API キーが必要です。API キーがない場合は、検索アプリをデプロイする(API キー)の手順 1 を完了します。

手順

REST

API を使用して、API キーで認証された一般公開ウェブサイト データを含むアプリの検索結果を取得するには、engines.servingConfigs.searchLite メソッドを使用します。

  1. アプリ ID を確認します。アプリ ID がすでにある場合は、次のステップに進みます。

    1. Google Cloud コンソールで、[AI Applications] ページに移動します。

      [アプリ] に移動

    2. [アプリ] ページで、アプリの名前を見つけ、[ID] 列からアプリの ID を取得します。

  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 プロジェクト ID。

    • API_KEY: API キー文字列。

    • PROJECT_ID: 実際の Google Cloud プロジェクト ID。

    • APP_ID: クエリする Vertex AI Search アプリの ID。

    • QUERY: 検索するクエリテキスト。

    • USER_PSEUDO_ID: ユーザーをトラッキングする一意の仮名化 ID として機能する UTF-8 エンコード文字列。最大長は 128 文字です。このフィールドを使用すると、モデルのパフォーマンスとパーソナライズの品質が向上するため、このフィールドを使用することを強くおすすめします。このフィールドには HTTP Cookie を使用できます。これにより、1 つのデバイス上の訪問者を一意に識別できます。重要な考慮事項は次のとおりです。

      • この ID は、訪問者がウェブサイトにログインまたはログアウトしても変更されません。
      • このフィールドを複数のユーザーに対して同じ ID に設定しないでください。そうしないと、複数のユーザーに同じユーザー ID を使用すると、異なるユーザーのイベント履歴が統合され、モデルの品質が低下する可能性があります。
      • このフィールドに個人を特定できる情報(PII)を含めることはできません。
      • 特定の検索リクエストまたはブラウジング リクエストの場合、このフィールドはユーザー イベントの対応する userPseudoId フィールドにマッピングする必要があります。

      詳細については、userPseudoId をご覧ください。

Python

詳細については、Vertex AI Search Python API のリファレンス ドキュメントをご覧ください。

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


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. コンソールで [プレビュー] ページを開きます。
  2. 検索語句を入力します。

    予測入力を有効にしている場合、入力すると検索バーの下に予測入力候補のリストが表示されます。

  3. (省略可)複数のデータストアをアプリに接続しているが、特定のデータストアの結果のみが必要な場合は、結果を取得するデータストアを選択します。

  4. Enter キーを押してクエリを送信します。

    検索バーの下に検索結果の一覧が表示されます。

    構造化データの場合、次の点が適用されます。

    • [設定] > [結果のフィールドの構成] で属性のマッピングが定義されていない場合、検索結果は属性名と値のリストとして表示されます。

    • [設定] > [結果のフィールドの構成] で属性マッピングが保存されている場合、検索結果は [設定] ページのプレビューと同じように表示されます。

    • [構成] > [ファセット設定] でファセットが指定されている場合は、同じように表示されます。

REST

API を使用して、構造化データまたは非構造化データを含むアプリの検索結果を取得するには、engines.servingConfigs.search メソッドを使用します。

  1. アプリ ID を確認します。アプリ ID がすでにある場合は、次のステップに進みます。

    1. Google Cloud コンソールで、[AI Applications] ページに移動します。

      [アプリ] に移動

    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",
    "dataStoreSpecs": [{"DATA_STORE_SPEC"}],
    }'
    

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

    • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
    • APP_ID: クエリする Vertex AI Search アプリの ID。
    • QUERY: 検索するクエリテキスト。
    • USER_PSEUDO_ID: ユーザーをトラッキングする一意の仮名化 ID として機能する UTF-8 エンコード文字列。最大長は 128 文字です。このフィールドを使用すると、モデルのパフォーマンスとパーソナライズの品質が向上するため、このフィールドを使用することを強くおすすめします。このフィールドには HTTP Cookie を使用できます。これにより、1 つのデバイス上の訪問者を一意に識別できます。重要な考慮事項は次のとおりです。

      • この ID は、訪問者がウェブサイトにログインまたはログアウトしても変更されません。
      • このフィールドを複数のユーザーに対して同じ ID に設定しないでください。そうしないと、複数のユーザーに同じユーザー ID を使用すると、異なるユーザーのイベント履歴が統合され、モデルの品質が低下する可能性があります。
      • このフィールドに個人を特定できる情報(PII)を含めることはできません。
      • 特定の検索リクエストまたはブラウジング リクエストの場合、このフィールドはユーザー イベントの対応する userPseudoId フィールドにマッピングする必要があります。

      詳細については、userPseudoId をご覧ください。

    • PAGE_SIZE: 検索によって返された結果の数。許可される最大ページサイズは、データ型によって異なります。最大値を超えるページサイズは、最大値に強制変換されます。

      • 基本的なインデックス登録のウェブサイト: デフォルト 10、最大 25
      • 高度なインデックス登録が有効になっているウェブサイト: デフォルト 25、最大 50
      • その他: デフォルト 50、最大 100
    • OFFSET: 省略可。結果の開始インデックス。 デフォルト値は 0 です。

      たとえば、オフセットが 2、ページサイズが 10、返される結果が 15 個ある場合、1 ページ目には 2 から 12 個の結果が返されます。

    • 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: 検索対象の特定のデータストアのフィルタ。検索アプリが複数のデータストアに接続されている場合に使用できます。

    • 検索レスポンスでガイド付きの検索結果を表示する:

      ガイド付きの検索結果は、構造化検索と非構造化検索の検索レスポンスとともに返されます。ガイド付きの検索結果には、検索結果ドキュメントに基づいて抽出された属性の Key-Value ペアのリストが含まれます。これにより、ユーザーは一部の属性キーと値をフィルタとして使用して、検索結果を絞り込むことができます。

      このレスポンス例では、緑色を使用して検索結果を絞り込むため、フィルタ フィールドを _gs.color: ANY("green") として指定した新しい検索リクエストを発行しています。

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

C#

詳細については、Vertex AI Search C# API のリファレンス ドキュメントをご覧ください。

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

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

詳細については、Vertex AI Search Java API のリファレンス ドキュメントをご覧ください。

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


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 Search Node.js API のリファレンス ドキュメントをご覧ください。

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

/**
 * 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 Search PHP API のリファレンス ドキュメントをご覧ください。

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

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 Search Python API のリファレンス ドキュメントをご覧ください。

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

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

詳細については、Vertex AI Search Ruby API のリファレンス ドキュメントをご覧ください。

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

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

検索結果でドキュメントの関連性スコアを取得する

ドキュメントの関連性スコアは、クエリとドキュメントの類似性に基づいています。スコアは 0、0.1、0.2、...、1.0 の範囲の 11 個のバケットに分類されます。スコアが高いほど、ドキュメントの関連性が高くなります。

次のユースケースのドキュメント関連性スコアについて考えてみましょう。

  • 関連性スコアに基づく検索後のフィルタリングにより、関連性の低い結果を削除する

  • 検索後のランキング、または他のアプリケーションへの入力として使用

  • デバッグ: 関連性スコアを使用すると、一部の検索結果が返される理由を把握できます

検索結果ごとに、関連性スコアを返すことができます。

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

以下の手順のコマンド例もご覧ください。

始める前に: 検索アプリが構造化データストアまたは非構造化データストアに関連付けられていることを確認します。つまり、ウェブサイト検索アプリではドキュメントの関連性スコアを返すことはできません。

REST

検索結果とともにドキュメントの関連性スコアを返すようにリクエストするには、次のように engines.servingConfigs.search メソッドを使用します。

  1. アプリ ID を確認します。アプリ ID がすでにある場合は、次のステップに進みます。

    1. Google Cloud コンソールで、[AI Applications] ページに移動します。

      [アプリ] に移動

    2. [アプリ] ページで、アプリの名前を見つけ、[ID] 列からアプリの ID を取得します。

  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 プロジェクト ID。
    • APP_ID: クエリする Vertex AI Search アプリの ID。
    • QUERY: 検索するクエリテキスト。

検索のサマリーはモデルによって異なる

クエリの検索のサマリーを生成すると、コンソールの結果と API の結果でサマリーが異なる場合があります。このような場合は、コンソールが API とは異なる LLM モデルを使用している可能性があります。このページの curl とコードの例では、安定版の LLM モデルを使用しています。

  • UI の [プレビュー] ページで使用されている LLM モデルを変更または表示します(高度な検索アプリケーションと医療アプリケーションでのみサポートされています)。

    1. アプリの [構成] ページ > [UI] タブに移動します。
    2. [検索タイプ] を選択します。

      • [回答付きの検索] を選択すると、検索結果の上に生成 AI によるサマリーが表示されます。
      • [フォローアップ付きの検索] を選択して、生成された要約とフォローアップの質問を含む会話型検索を有効にします。
    3. [要約のための大規模言語モデル] セクションで、モデルを選択します。

  • メソッド呼び出しの場合、安定版モデルがデフォルトのモデルです。安定版モデル以外の LLM モデルを使用するには、要約モデルを指定する回答モデルを指定するをご覧ください。

    次のステップ

  • 検索ウィジェットをウェブページに追加する

  • 検索 API を使用して、汎用検索アプリのデータを閲覧します。