Stay organized with collectionsSave and categorize content based on your preferences.
This page shows how to preview search results using the Google Cloud console and get
search results using the API.
Also, instead of creating asearch widgetto add to your web page,
you can make API calls and integrate those calls into your server or
application. This page includes code samples for how to make search queries
using the gRPC client libraries with a service account.
Get search results for an app with website data
Console
To use the Google Cloud console to preview search results for an app with website
data, follow these steps:
In the Google Cloud console, go to theAI Applicationspage.
Optional: If you connected multiple data stores to your app but want
results only from a specific data store, select the data store to get
results from.
Type a search query.
If you enabled autocomplete, a list of autocomplete
suggestions appears below the search bar as you type.
PressEnterto submit the query.
A list of search results appears below the search bar.
Each result contains a title, a snippet, and a URL.
Clicking a result opens that URL.
If Advanced LLM features are enabled for the app, a generated answer
might also appear.
APP_ID: the ID of the Vertex AI Search app that you
want to query.
QUERY: the query text to search.
PAGE_SIZE: the number of results returned by the search.
The maximum allowed page size depends on the data type. Page sizes above the
maximum value are coerced to the maximum value.
Websites with basic indexing: Default10, Maximum25
Websites with advanced indexing: Default25, Maximum50
Other: Default50, Maximum100
OFFSET: the starting index of the results. The default
value is 0.
For example, if the offset is 2, the page size is 10, and there are 15
results to return, results 2 through 12 are returned on the first
page.
ORDER_BY: the order in which the results are arranged. The
attribute to sort on must have a numerical interpretation—for example,date. For more information, seeOrder web search
results.
USER_COUNTRY_CODE: the location of the user. This key-value
pair is the only supported entry for theparamsmap field. The
default value is empty. For acceptable values, seeCountry
Codesin the Programmable Search Engine
JSON API reference documentation.
SEARCH_TYPE: the type of search to be performed. The
default value is 0 for document search. The other supported value is 1
for image search.
FILTER: a text field for filtering your search using a
filter expression. The default value is an empty string. For more
information about using thefilterfield, seeFilter website
search.
BOOST_SPEC: optional. A specification to
boost or bury documents. Values:
BOOST:
a floating point number in the range [-1,1]. When the value is
negative, results are demoted (they appear lower down in the
results). When the value is positive, results are promoted
(they appear higher up in the results).
CONDITION:
atext filter expressionto select the documents to which boost is applied. The filter must evaluate
to a boolean value.
To learn about boost for structured search, seeBoost search results.
RESULT_MODE: determines whether search results are returned
as full documents or in chunks. To get chunks, the data store must
have document chunking turned on. Accepted values aredocumentsandchunks. When chunking is turned on for a data store, the default
value ischunks. Otherwise, the default isdocuments. For
information about document chunking, seeParse and chunk
documents. This field is in Public preview; to
use it, changev1tov1alphain the curl command.
USER_PSEUDO_ID: a UTF-8 encoded
string, which acts as a unique pseudonymized identifier that tracks the
users. It can have a maximum length of 128 characters.
Google strongly recommends using this field because it improves
model performance and personalization quality. You can use an HTTP
cookie for this field, which uniquely identifies a visitor on a single
device. Some important considerations are as follows:
This identifier doesn't change when the visitor signs in or out of a
website.
This field must not be set to the same identifier for multiple users.
Otherwise, same user ID can combine event histories of different users and
degrade model quality.
This field must not include personally identifiable information (PII).
For a given search or browse request, this field must map to the
correspondinguserPseudoIdfield in
the user events.
DATA_STORE_SPEC: filters for a specific data
store to search across. UsedataStoreSpecsif your search app is
connected to multiple data stores but you want results from a specific
data store. For more information, seeDataStoreSpec.
usingGoogle.Api.Gax;usingGoogle.Cloud.DiscoveryEngine.V1Beta;usingGoogle.Protobuf.WellKnownTypes;usingSystem;publicsealedpartialclassGeneratedSearchServiceClientSnippets{/// <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>publicvoidSearchRequestObject(){// Create clientSearchServiceClientsearchServiceClient=SearchServiceClient.Create();// Initialize request argument(s)SearchRequestrequest=newSearchRequest{ServingConfigAsServingConfigName=ServingConfigName.FromProjectLocationDataStoreServingConfig("[PROJECT]","[LOCATION]","[DATA_STORE]","[SERVING_CONFIG]"),BranchAsBranchName=BranchName.FromProjectLocationDataStoreBranch("[PROJECT]","[LOCATION]","[DATA_STORE]","[BRANCH]"),Query="",Offset=0,Filter="",OrderBy="",FacetSpecs={newSearchRequest.Types.FacetSpec(),},BoostSpec=newSearchRequest.Types.BoostSpec(),Params={{"",newValue()},},QueryExpansionSpec=newSearchRequest.Types.QueryExpansionSpec(),SpellCorrectionSpec=newSearchRequest.Types.SpellCorrectionSpec(),UserPseudoId="",ImageQuery=newSearchRequest.Types.ImageQuery(),SafeSearch=false,UserInfo=newUserInfo(),UserLabels={{"",""},},EmbeddingSpec=newSearchRequest.Types.EmbeddingSpec(),ContentSearchSpec=newSearchRequest.Types.ContentSearchSpec(),RankingExpression="",NaturalLanguageQueryUnderstandingSpec=newSearchRequest.Types.NaturalLanguageQueryUnderstandingSpec(),CanonicalFilter="",SearchAsYouTypeSpec=newSearchRequest.Types.SearchAsYouTypeSpec(),DataStoreSpecs={newSearchRequest.Types.DataStoreSpec(),},LanguageCode="",RegionCode="",SessionAsSessionName=SessionName.FromProjectLocationDataStoreSession("[PROJECT]","[LOCATION]","[DATA_STORE]","[SESSION]"),SessionSpec=newSearchRequest.Types.SessionSpec(),RelevanceThreshold=SearchRequest.Types.RelevanceThreshold.Unspecified,PersonalizationSpec=newSearchRequest.Types.PersonalizationSpec(),OneBoxPageSize=0,};// Make the requestPagedEnumerable<SearchResponse,SearchResponse.Types.SearchResult>response=searchServiceClient.Search(request);// Iterate over all response items, lazily performing RPCs as requiredforeach(SearchResponse.Types.SearchResultiteminresponse){// Do something with each itemConsole.WriteLine(item);}// Or iterate over pages (of server-defined size), performing one RPC per pageforeach(SearchResponsepageinresponse.AsRawResponses()){// Do something with each page of itemsConsole.WriteLine("A page of results:");foreach(SearchResponse.Types.SearchResultiteminpage){// Do something with each itemConsole.WriteLine(item);}}// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as requiredintpageSize=10;Page<SearchResponse.Types.SearchResult>singlePage=response.ReadPage(pageSize);// Do something with the page of itemsConsole.WriteLine($"A page of {pageSize} results (unless it's the final page):");foreach(SearchResponse.Types.SearchResultiteminsinglePage){// Do something with each itemConsole.WriteLine(item);}// Store the pageToken, for when the next page is required.stringnextPageToken=singlePage.NextPageToken;}}
importcom.google.cloud.discoveryengine.v1.SearchRequest;importcom.google.cloud.discoveryengine.v1.SearchResponse;importcom.google.cloud.discoveryengine.v1.SearchServiceClient;importcom.google.cloud.discoveryengine.v1.SearchServiceSettings;importcom.google.cloud.discoveryengine.v1.ServingConfigName;importjava.io.IOException;importjava.util.concurrent.ExecutionException;publicclassSearch{publicstaticvoidmain()throwsIOException,ExecutionException{// TODO(developer): Replace these variables before running the sample.// Project ID or project number of the Cloud project you want to use.StringprojectId="PROJECT_ID";// Location of the data store. Options: "global", "us", "eu"Stringlocation="global";// Collection containing the data store.StringcollectionId="default_collection";// Data store ID.StringdataStoreId="DATA_STORE_ID";// Serving configuration. Options: "default_search"StringservingConfigId="default_search";// Search Query for the data store.StringsearchQuery="Google";search(projectId,location,collectionId,dataStoreId,servingConfigId,searchQuery);}/** Performs a search on a given datastore. */publicstaticvoidsearch(StringprojectId,Stringlocation,StringcollectionId,StringdataStoreId,StringservingConfigId,StringsearchQuery)throwsIOException,ExecutionException{// For more information, refer to:// https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_storeStringendpoint=(location.equals("global"))?String.format("discoveryengine.googleapis.com:443",location):String.format("%s-discoveryengine.googleapis.com:443",location);SearchServiceSettingssettings=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(SearchServiceClientsearchServiceClient=SearchServiceClient.create(settings)){SearchRequestrequest=SearchRequest.newBuilder().setServingConfig(ServingConfigName.formatProjectLocationCollectionDataStoreServingConfigName(projectId,location,collectionId,dataStoreId,servingConfigId)).setQuery(searchQuery).setPageSize(10).build();SearchResponseresponse=searchServiceClient.search(request).getPage().getResponse();for(SearchResponse.SearchResultelement:response.getResultsList()){System.out.println("Response content: "+element);}}}}
/*** 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_storeconstapiEndpoint=location==='global'?'discoveryengine.googleapis.com':`${location}-discoveryengine.googleapis.com`;// Instantiates a clientconstclient=newSearchServiceClient({apiEndpoint:apiEndpoint});asyncfunctionsearch(){// 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.constname=client.projectLocationCollectionDataStoreServingConfigPath(projectId,location,collectionId,dataStoreId,servingConfigId);constrequest={pageSize:10,query:searchQuery,servingConfig:name,};constIResponseParams={ISearchResult:0,ISearchRequest:1,ISearchResponse:2,};// Perform search requestconstresponse=awaitclient.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,});constresults=response[IResponseParams.ISearchResponse].results;for(constresultofresults){console.log(result);}}
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/*/locations/global/collections/default_collection/engines/*/servingConfigs/default_serving_config`,* or* `projects/*/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);}
fromgoogle.api_core.client_optionsimportClientOptionsfromgoogle.cloudimportdiscoveryengine_v1asdiscoveryengine# 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"defsearch_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_storeclient_options=(ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")iflocation!="global"elseNone)# Create a clientclient=discoveryengine.SearchServiceClient(client_options=client_options)# The full resource name of the search app serving configserving_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.ContentSearchSpeccontent_search_spec=discoveryengine.SearchRequest.ContentSearchSpec(# For information about snippets, refer to:# https://cloud.google.com/generative-ai-app-builder/docs/snippetssnippet_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-summariessummary_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.SearchRequestrequest=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 responseforresponseinpage_result:print(response)returnpage_result
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.#defsearch# 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.searchrequest# 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.eachdo|item|# Each element is of type ::Google::Cloud::DiscoveryEngine::V1beta::SearchResponse::SearchResult.pitemendend
Get search results for an app with website data (API key)
If you want to authenticate the search method call with an API key instead of
using OAuth 2.0 through a service account or a user account, then follow this
procedure, which uses thesearchLitemethod.
ThesearchLitemethod has the same features as thesearchmethod except that
it can only be used to search public websites.
ThesearchLitemethod is particularly suitable under the following conditions:
You have a static website for which
setting up OAuth 2.0 through a service account or a user account is not
practical.
To use the API to get search results for an app with public website data
authenticated with an API key,
use theengines.servingConfigs.searchLitemethod:
Find your app ID. If you already have your app ID, skip to the next step.
In the Google Cloud console, go to theAI Applicationspage.
APP_ID: the ID of the Vertex AI Search app that you
want to query.
QUERY: the query text to search.
USER_PSEUDO_ID: a UTF-8 encoded
string, which acts as a unique pseudonymized identifier that tracks the
users. It can have a maximum length of 128 characters.
Google strongly recommends using this field because it improves
model performance and personalization quality. You can use an HTTP
cookie for this field, which uniquely identifies a visitor on a single
device. Some important considerations are as follows:
This identifier doesn't change when the visitor signs in or out of a
website.
This field must not be set to the same identifier for multiple users.
Otherwise, same user ID can combine event histories of different users and
degrade model quality.
This field must not include personally identifiable information (PII).
For a given search or browse request, this field must map to the
correspondinguserPseudoIdfield in
the user events.
fromgoogle.api_core.client_optionsimportClientOptionsfromgoogle.cloudimportdiscoveryengine_v1asdiscoveryengine# 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"defsearch_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-deployapi_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_storeapi_endpoint=(f"{location}-discoveryengine.googleapis.com"iflocation!="global"elseNone),)# Create a clientclient=discoveryengine.SearchServiceClient(client_options=client_options)# The full resource name of the search app serving configserving_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.SearchRequestrequest=discoveryengine.SearchRequest(serving_config=serving_config,query=search_query,)page_result=client.search_lite(request)# Handle the responseforresponseinpage_result:print(response)returnpage_result
Get search results for an app with structured or unstructured data
You can preview search results from the Google Cloud console or get search results
using the API.
Console
To use the Google Cloud console to preview search results for an app with structured
or unstructured data, follow these steps:
Open thePreviewpage in the console.
Type a search query.
If you enabled autocomplete, a list of autocomplete
suggestions appears below the search bar as you type.
(Optional) If you connected multiple data stores to your app but want
results only from a specific data store, select the data store to get
results from.
PressEnterto submit the query.
A list of search results appears below the search bar.
For structured data, the following apply:
If attribute mappings are not defined inConfigurations>Configure fields in results, then search results
are displayed as a list of raw attribute names and values.
If any attribute mappings were saved inConfigurations>Configure fields in results, then the search
results display the same way as you see in theConfigurationspage
preview.
If any facets were specified inConfigurations>Facet settings,
then they are displayed in the same way.
REST
To use the API to get search results for an app with structured or unstructured
data, use theengines.servingConfigs.searchmethod:
Find your app ID. If you already have your app ID, skip to the next step.
In the Google Cloud console, go to theAI Applicationspage.
APP_ID: the ID of the Vertex AI Search app that you
want to query.
QUERY: the query text to search.
USER_PSEUDO_ID: a UTF-8 encoded
string, which acts as a unique pseudonymized identifier that tracks the
users. It can have a maximum length of 128 characters.
Google strongly recommends using this field because it improves
model performance and personalization quality. You can use an HTTP
cookie for this field, which uniquely identifies a visitor on a single
device. Some important considerations are as follows:
This identifier doesn't change when the visitor signs in or out of a
website.
This field must not be set to the same identifier for multiple users.
Otherwise, same user ID can combine event histories of different users and
degrade model quality.
This field must not include personally identifiable information (PII).
For a given search or browse request, this field must map to the
correspondinguserPseudoIdfield in
the user events.
PAGE_SIZE: the number of results returned by
the search. The maximum allowed page size depends on the data type. Page
sizes above the maximum value are coerced to the maximum value.
Websites with basic indexing: Default10, Maximum25
Websites with advanced indexing: Default25, Maximum50
Other: Default50, Maximum100
OFFSET: optional. The starting index of the results.
The default value is 0.
For example, if the offset is 2, the page size is 10,
and there are 15 results to return, results 2 through 11 are
returned on the first page.
ORDER_BY: optional. The order in which the results are
arranged.
FILTER: optional. A text field for filtering your search
using a filter expression. The default value is an empty string, which
means no filter is applied.
Example:color: ANY("red", "blue") AND score: IN(*, 100.0e)
BOOST_SPEC: optional. A specification to
boost or bury documents. Values:
BOOST:
a floating point number in the range [-1,1]. When the value is
negative, results are demoted (they appear lower down in the
results). When the value is positive, results are promoted
(they appear higher up in the results).
CONDITION:
atext filter expressionto select the documents to which boost is applied. The filter must evaluate
to a boolean value.
FACET_SPEC: optional. A facet specification to perform
faceted search.
QUERY_EXPANSION_SPEC: optional. A specification to
determine under which conditions query expansion should occur. Default
isDISABLED.
SPELL_CORRECTION_SPEC: optional. A specification to
determine under which conditions spell correction should occur. Default
isAUTO.
CONTENT_SEARCH_SPEC: optional. For getting snippets,
extractive answers, extractive segments, and search summaries. For
unstructured data only. For more information, see:
DATA_STORE_SPEC: filters for a specific data store to
search across. This can be used if your search app is connected to
multiple data stores.
Viewing guided search results in the search response:
Guided search results are returned with search responses for structured
and unstructured search. The guided search result contains a list of
extracted attribute key-value pairs based on search result documents. This
allows users to refine their search results by using some attribute keys
and values as filters.
In this example response, the color green was used to refine search
results by issuing a new search request with the filter field specified as_gs.color: ANY("green"):
usingGoogle.Api.Gax;usingGoogle.Cloud.DiscoveryEngine.V1Beta;usingGoogle.Protobuf.WellKnownTypes;usingSystem;publicsealedpartialclassGeneratedSearchServiceClientSnippets{/// <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>publicvoidSearchRequestObject(){// Create clientSearchServiceClientsearchServiceClient=SearchServiceClient.Create();// Initialize request argument(s)SearchRequestrequest=newSearchRequest{ServingConfigAsServingConfigName=ServingConfigName.FromProjectLocationDataStoreServingConfig("[PROJECT]","[LOCATION]","[DATA_STORE]","[SERVING_CONFIG]"),BranchAsBranchName=BranchName.FromProjectLocationDataStoreBranch("[PROJECT]","[LOCATION]","[DATA_STORE]","[BRANCH]"),Query="",Offset=0,Filter="",OrderBy="",FacetSpecs={newSearchRequest.Types.FacetSpec(),},BoostSpec=newSearchRequest.Types.BoostSpec(),Params={{"",newValue()},},QueryExpansionSpec=newSearchRequest.Types.QueryExpansionSpec(),SpellCorrectionSpec=newSearchRequest.Types.SpellCorrectionSpec(),UserPseudoId="",ImageQuery=newSearchRequest.Types.ImageQuery(),SafeSearch=false,UserInfo=newUserInfo(),UserLabels={{"",""},},EmbeddingSpec=newSearchRequest.Types.EmbeddingSpec(),ContentSearchSpec=newSearchRequest.Types.ContentSearchSpec(),RankingExpression="",NaturalLanguageQueryUnderstandingSpec=newSearchRequest.Types.NaturalLanguageQueryUnderstandingSpec(),CanonicalFilter="",SearchAsYouTypeSpec=newSearchRequest.Types.SearchAsYouTypeSpec(),DataStoreSpecs={newSearchRequest.Types.DataStoreSpec(),},LanguageCode="",RegionCode="",SessionAsSessionName=SessionName.FromProjectLocationDataStoreSession("[PROJECT]","[LOCATION]","[DATA_STORE]","[SESSION]"),SessionSpec=newSearchRequest.Types.SessionSpec(),RelevanceThreshold=SearchRequest.Types.RelevanceThreshold.Unspecified,PersonalizationSpec=newSearchRequest.Types.PersonalizationSpec(),OneBoxPageSize=0,};// Make the requestPagedEnumerable<SearchResponse,SearchResponse.Types.SearchResult>response=searchServiceClient.Search(request);// Iterate over all response items, lazily performing RPCs as requiredforeach(SearchResponse.Types.SearchResultiteminresponse){// Do something with each itemConsole.WriteLine(item);}// Or iterate over pages (of server-defined size), performing one RPC per pageforeach(SearchResponsepageinresponse.AsRawResponses()){// Do something with each page of itemsConsole.WriteLine("A page of results:");foreach(SearchResponse.Types.SearchResultiteminpage){// Do something with each itemConsole.WriteLine(item);}}// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as requiredintpageSize=10;Page<SearchResponse.Types.SearchResult>singlePage=response.ReadPage(pageSize);// Do something with the page of itemsConsole.WriteLine($"A page of {pageSize} results (unless it's the final page):");foreach(SearchResponse.Types.SearchResultiteminsinglePage){// Do something with each itemConsole.WriteLine(item);}// Store the pageToken, for when the next page is required.stringnextPageToken=singlePage.NextPageToken;}}
importcom.google.cloud.discoveryengine.v1.SearchRequest;importcom.google.cloud.discoveryengine.v1.SearchResponse;importcom.google.cloud.discoveryengine.v1.SearchServiceClient;importcom.google.cloud.discoveryengine.v1.SearchServiceSettings;importcom.google.cloud.discoveryengine.v1.ServingConfigName;importjava.io.IOException;importjava.util.concurrent.ExecutionException;publicclassSearch{publicstaticvoidmain()throwsIOException,ExecutionException{// TODO(developer): Replace these variables before running the sample.// Project ID or project number of the Cloud project you want to use.StringprojectId="PROJECT_ID";// Location of the data store. Options: "global", "us", "eu"Stringlocation="global";// Collection containing the data store.StringcollectionId="default_collection";// Data store ID.StringdataStoreId="DATA_STORE_ID";// Serving configuration. Options: "default_search"StringservingConfigId="default_search";// Search Query for the data store.StringsearchQuery="Google";search(projectId,location,collectionId,dataStoreId,servingConfigId,searchQuery);}/** Performs a search on a given datastore. */publicstaticvoidsearch(StringprojectId,Stringlocation,StringcollectionId,StringdataStoreId,StringservingConfigId,StringsearchQuery)throwsIOException,ExecutionException{// For more information, refer to:// https://cloud.google.com/generative-ai-app-builder/docs/locations#specify_a_multi-region_for_your_data_storeStringendpoint=(location.equals("global"))?String.format("discoveryengine.googleapis.com:443",location):String.format("%s-discoveryengine.googleapis.com:443",location);SearchServiceSettingssettings=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(SearchServiceClientsearchServiceClient=SearchServiceClient.create(settings)){SearchRequestrequest=SearchRequest.newBuilder().setServingConfig(ServingConfigName.formatProjectLocationCollectionDataStoreServingConfigName(projectId,location,collectionId,dataStoreId,servingConfigId)).setQuery(searchQuery).setPageSize(10).build();SearchResponseresponse=searchServiceClient.search(request).getPage().getResponse();for(SearchResponse.SearchResultelement:response.getResultsList()){System.out.println("Response content: "+element);}}}}
/*** 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_storeconstapiEndpoint=location==='global'?'discoveryengine.googleapis.com':`${location}-discoveryengine.googleapis.com`;// Instantiates a clientconstclient=newSearchServiceClient({apiEndpoint:apiEndpoint});asyncfunctionsearch(){// 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.constname=client.projectLocationCollectionDataStoreServingConfigPath(projectId,location,collectionId,dataStoreId,servingConfigId);constrequest={pageSize:10,query:searchQuery,servingConfig:name,};constIResponseParams={ISearchResult:0,ISearchRequest:1,ISearchResponse:2,};// Perform search requestconstresponse=awaitclient.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,});constresults=response[IResponseParams.ISearchResponse].results;for(constresultofresults){console.log(result);}}
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/*/locations/global/collections/default_collection/engines/*/servingConfigs/default_serving_config`,* or* `projects/*/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);}
fromgoogle.api_core.client_optionsimportClientOptionsfromgoogle.cloudimportdiscoveryengine_v1asdiscoveryengine# 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"defsearch_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_storeclient_options=(ClientOptions(api_endpoint=f"{location}-discoveryengine.googleapis.com")iflocation!="global"elseNone)# Create a clientclient=discoveryengine.SearchServiceClient(client_options=client_options)# The full resource name of the search app serving configserving_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.ContentSearchSpeccontent_search_spec=discoveryengine.SearchRequest.ContentSearchSpec(# For information about snippets, refer to:# https://cloud.google.com/generative-ai-app-builder/docs/snippetssnippet_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-summariessummary_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.SearchRequestrequest=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 responseforresponseinpage_result:print(response)returnpage_result
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.#defsearch# 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.searchrequest# 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.eachdo|item|# Each element is of type ::Google::Cloud::DiscoveryEngine::V1beta::SearchResponse::SearchResult.pitemendend
Get document-relevance scores with search results
Document-relevance scores are based on the similarity of the query to the
document. Scores are put into 11 buckets in the range: 0, 0.1, 0.2, … to 1.0.
The higher the score, the more relevant the document.
Consider document-relevance scores for these use cases:
Post-search filtering based on the relevance score to remove
irrelevant results
Post-search ranking or as input to other applications
Debugging: relevance scores can provide insight into why some search
results are returned
For each search result, a relevance score can be returned:
Also see the example command in the procedure below.
Before you begin:Make sure that the search app is associated with a
structured or unstructured data store. That is, document-relevance scores can't
be returned for website search app.
REST
To request that document-relevance scores be returned with search results, use
theengines.servingConfigs.searchmethod as
follows:
Find your app ID. If you already have your app ID, skip to the next step.
In the Google Cloud console, go to theAI Applicationspage.
APP_ID: the ID of the Vertex AI Search app that you
want to query.
QUERY: the query text to search.
Example command and partial result
curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
"https://discoveryengine.googleapis.com/v1/projects/my-project-123/locations/global/collections/default_collection/engines/my-app/servingConfigs/default_search:search" \
-d '{
"servingConfig": "projects/my-project-123/locations/global/collections/default_collection/engines/my-app/servingConfigs/default_search",
"query": "When was Verily founded and what is its mission?","relevanceScoreSpec": {
"returnRelevanceScore": true}
}'{
"results": [
{
"id": "f1b0d98bd2a078a6dfb4f809c3028565",
"document": {
"name": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/f1b0d98bd2a078a6dfb4f809c3028565",
"id": "f1b0d98bd2a078a6dfb4f809c3028565",
"derivedStructData": {
"link": "gs://cloud-samples-data/gen-app-builder/search/alphabet-investor-pdfs/2019_alphabet_annual_report.pdf",
"extractive_answers": [
{
"pageNumber": "70",
"content": "VERILY Verily is a life science and healthcare company with a mission to make the world's health data useful so that people enjoy healthier lives. In December 2018, Verily received $900 million in cash from a $1.0 billion investment round. The remaining $100 million was received in the first quarter of 2019."
}
],
"title": "2019_alphabet_annual_report"
}
},"modelScores": {
"relevance_score": {
"values": [
0.7
]
}
}},
{
"id": "0371b29bfa18ac43896b86a7b63d00b0",
"document": {
"name": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/0371b29bfa18ac43896b86a7b63d00b0",
"id": "0371b29bfa18ac43896b86a7b63d00b0",
"derivedStructData": {
"link": "gs://cloud-samples-data/gen-app-builder/search/alphabet-investor-pdfs/20190429_alphabet_10Q.pdf",
"title": "GOOG 10-Q Q1 2019",
"extractive_answers": [
{
"content": "Verily Verily is a life science company with a mission to make the world's health data useful so that people enjoy healthier lives. In December 2018, Verily received $900 million in cash from a $1.0 billion investment round. The remaining $100 million was received in the first quarter of 2019.",
"pageNumber": "21"
}
]
}
},"modelScores": {
"relevance_score": {
"values": [
0.5
]
}
}},
...
{
"id": "e6bbd0d82dc2a2fc7ccf1bd82ac6334f",
"document": {
"name": "projects/123456/locations/global/collections/default_collection/dataStores/my-data-store/branches/0/documents/e6bbd0d82dc2a2fc7ccf1bd82ac6334f",
"id": "e6bbd0d82dc2a2fc7ccf1bd82ac6334f",
"derivedStructData": {
"title": "2021_Q1_Earnings_Transcript",
"link": "gs://cloud-samples-data/gen-app-builder/search/alphabet-investor-pdfs/2021_Q1_Earnings_Transcript.pdf",
"extractive_answers": [
{
"pageNumber": "2",
"content": "Our strength in AI and ML is also helping Financial Services customers improve efficiency of payments, reduce fraud and risk, and deliver faster payment solutions."
}
]
}
},"modelScores": {
"relevance_score": {
"values": [
0
]
}
}}
],
"totalSize": 76,
"attributionToken": "8QHw8AoLCIW4_b0GELHd3lgSJDY3YmU1ZGMwLTAwMDAtMmM1OC04NzcyLTc0NzQ0NjNiOGMyNSIHR0VORVJJQyqcAcb77TDHy_MX8tntMI6-nRWK4uQwwvCeFYX77TDvifIwq8SKLauR3zCq-LMt0IrIMNSynRWc1rctv_7kML7l3zDZveQwkPeyMMP77TD12e0wpd_hMIfi5DCRv9owgvvtMJWSxTCOkckwu-XfMK7Eii3sifIwqJHfMKjf4TCt-LMtlL_aMJ_Wty23t4wto4CXIs2KyDDcveQwwv7kMDABShIweDU3MGFkYWI4MzQ4NmY0MGE",
"nextPageToken": "UjMjhjYzYDN0cDN30iM3cDOtgTNjJTLwADMw0iZiRWNlJ2N2QiGBUd0gWLEG4bjhWICMIBM1IgC",
"summary": {},
"queryExpansionInfo": {}
}
Search summarization differs by model
If you generate search summaries for your queries, you might notice that
the summaries differ between the console results and the API results. If you
see this, the likely reason is that the console is using a different LLM model
from the API. The curl and code examples on this page use the stable LLM model.
To change or view the LLM model used in thePreviewpage of the UI
(only supported for advanced search applications and healthcare
applications.)
Go to your app'sConfigurationspage >UItab.
Select aSearch Type:
SelectSearch with an answerto display a generative
summary above the search results.
SelectSearch with follow-upsto enable conversation search with
generative summaries and follow up questions.
In theLarge language models for summarizationsection, select a
model.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-09-04 UTC."],[[["\u003cp\u003eThis page outlines methods to preview and retrieve search results using the Google Cloud console and the API, supporting different types of data such as website data, structured data, and unstructured data.\u003c/p\u003e\n"],["\u003cp\u003eYou can retrieve search results through direct API calls instead of using a search widget, using gRPC client libraries with a service account for authentication or using API keys for public websites.\u003c/p\u003e\n"],["\u003cp\u003eThe Google Cloud console offers a "Preview" feature to test search results, with options to select specific data stores and view autocomplete suggestions.\u003c/p\u003e\n"],["\u003cp\u003eThe API allows for detailed control over search parameters, including filtering, ordering, boosting, faceting, query expansion, and spell correction, with support for different data types and the option to return document-relevance scores.\u003c/p\u003e\n"],["\u003cp\u003eFor media apps, search-as-you-type functionality is available, providing updated search results with each keystroke, and it can be configured both in the console and via API.\u003c/p\u003e\n"]]],[],null,[]]