Google Cloud Retail V2 Client - Class SearchServiceClient (1.1.1)

Reference documentation and code samples for the Google Cloud Retail V2 Client class SearchServiceClient.

Service Description: Service for search.

This feature is only available for users who have Retail Search enabled. Enable Retail Search on Cloud Console before using this feature.

This class provides the ability to make remote calls to the backing service through method calls that map to API methods. Sample code to get started:

$searchServiceClient = new SearchServiceClient();
try {
    $placement = 'placement';
    $visitorId = 'visitor_id';
    // Iterate over pages of elements
    $pagedResponse = $searchServiceClient->search($placement, $visitorId);
    foreach ($pagedResponse->iteratePages() as $page) {
        foreach ($page as $element) {
            // doSomethingWith($element);
        }
    }
    // Alternatively:
    // Iterate through all elements
    $pagedResponse = $searchServiceClient->search($placement, $visitorId);
    foreach ($pagedResponse->iterateAllElements() as $element) {
        // doSomethingWith($element);
    }
} finally {
    $searchServiceClient->close();
}

Many parameters require resource names to be formatted in a particular way. To assist with these names, this class includes a format method for each type of name, and additionally a parseName method to extract the individual identifiers contained within formatted names that are returned by the API.

Methods

branchName

Formats a string containing the fully-qualified path to represent a branch resource.

Parameters
NameDescription
project string
location string
catalog string
branch string
Returns
TypeDescription
stringThe formatted branch resource.

parseName

Parses a formatted name string and returns an associative array of the components in the name.

The following name formats are supported: Template: Pattern

  • branch: projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}

The optional $template argument can be supplied to specify a particular pattern, and must match one of the templates listed above. If no $template argument is provided, or if the $template argument does not match one of the templates listed, then parseName will check each of the supported templates, and return the first match.

Parameters
NameDescription
formattedName string

The formatted name string

template string

Optional name of template to match

Returns
TypeDescription
arrayAn associative array from name component IDs to component values.

__construct

Constructor.

Parameters
NameDescription
options array

Optional. Options for configuring the service API wrapper.

↳ apiEndpoint string

The address of the API remote host. May optionally include the port, formatted as "

↳ credentials string|array|FetchAuthTokenInterface|CredentialsWrapper

The credentials to be used by the client to authorize API calls. This option accepts either a path to a credentials file, or a decoded credentials file as a PHP array. Advanced usage: In addition, this option can also accept a pre-constructed Google\Auth\FetchAuthTokenInterface object or Google\ApiCore\CredentialsWrapper object. Note that when one of these objects are provided, any settings in $credentialsConfig will be ignored.

↳ credentialsConfig array

Options used to configure credentials, including auth token caching, for the client. For a full list of supporting configuration options, see Google\ApiCore\CredentialsWrapper::build() .

↳ disableRetries bool

Determines whether or not retries defined by the client configuration should be disabled. Defaults to false.

↳ clientConfig string|array

Client method configuration, including retry settings. This option can be either a path to a JSON file, or a PHP array containing the decoded JSON data. By default this settings points to the default client config file, which is provided in the resources folder.

↳ transport string|TransportInterface

The transport used for executing network requests. May be either the string rest or grpc. Defaults to grpc if gRPC support is detected on the system. Advanced usage: Additionally, it is possible to pass in an already instantiated Google\ApiCore\Transport\TransportInterface object. Note that when this object is provided, any settings in $transportConfig, and any $apiEndpoint setting, will be ignored.

↳ transportConfig array

Configuration options that will be used to construct the transport. Options for each supported transport type should be passed in a key for that transport. For example: $transportConfig = [ 'grpc' => [...], 'rest' => [...], ]; See the Google\ApiCore\Transport\GrpcTransport::build() and Google\ApiCore\Transport\RestTransport::build() methods for the supported options.

↳ clientCertSource callable

A callable which returns the client cert as a string. This can be used to provide a certificate and private key to the transport layer for mTLS.

search

Performs a search.

This feature is only available for users who have Retail Search enabled. Enable Retail Search on Cloud Console before using this feature.

Parameters
NameDescription
placement string

Required. The resource name of the Retail Search serving config, such as projects/*/locations/global/catalogs/default_catalog/servingConfigs/default_serving_config or the name of the legacy placement resource, such as projects/*/locations/global/catalogs/default_catalog/placements/default_search. This field is used to identify the serving config name and the set of models that will be used to make the search.

visitorId string

Required. A unique identifier for tracking visitors. For example, this could be implemented with an HTTP cookie, which should be able to uniquely identify a visitor on a single device. This unique identifier should not change if the visitor logs in or out of the website.

This should be the same identifier as UserEvent.visitor_id.

The field must be a UTF-8 encoded string with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned.

optionalArgs array

Optional.

↳ branch string

The branch resource name, such as projects/*/locations/global/catalogs/default_catalog/branches/0. Use "default_branch" as the branch ID or leave this field empty, to search products under the default branch.

↳ query string

Raw search query. If this field is empty, the request is considered a category browsing request and returned results are based on filter and page_categories.

↳ userInfo UserInfo

User information.

↳ pageSize int

The maximum number of resources contained in the underlying API response. The API may return fewer values in a page, even if there are additional values to be retrieved.

↳ pageToken string

A page token is used to specify a page of values to be returned. If no page token is specified (the default), the first page of values will be returned. Any page token used here must have been generated by a previous call to the API.

↳ offset int

A 0-indexed integer that specifies the current offset (that is, starting result location, amongst the Products deemed by the API as relevant) in search results. This field is only considered if page_token is unset. If this field is negative, an INVALID_ARGUMENT is returned.

↳ filter string

The filter syntax consists of an expression language for constructing a predicate from one or more fields of the products being filtered. Filter expression is case-sensitive. See more details at this user guide. If this field is unrecognizable, an INVALID_ARGUMENT is returned.

↳ canonicalFilter string

The default filter that is applied when a user performs a search without checking any filters on the search page. The filter applied to every search request when quality improvement such as query expansion is needed. For example, if a query does not have enough results, an expanded query with SearchRequest.canonical_filter will be returned as a supplement of the original query. This field is strongly recommended to achieve high search quality. See SearchRequest.filter for more details about filter syntax.

↳ orderBy string

The order in which products are returned. Products can be ordered by a field in an Product object. Leave it unset if ordered by relevance. OrderBy expression is case-sensitive. See more details at this user guide. If this field is unrecognizable, an INVALID_ARGUMENT is returned.

↳ facetSpecs FacetSpec[]

Facet specifications for faceted search. If empty, no facets are returned. A maximum of 100 values are allowed. Otherwise, an INVALID_ARGUMENT error is returned.

↳ dynamicFacetSpec DynamicFacetSpec

Deprecated. Refer to https://cloud.google.com/retail/docs/configs#dynamic to enable dynamic facets. Do not set this field. The specification for dynamically generated facets. Notice that only textual facets can be dynamically generated.

↳ boostSpec BoostSpec

Boost specification to boost certain products. See more details at this user guide. Notice that if both ServingConfig.boost_control_ids and SearchRequest.boost_spec are set, the boost conditions from both places are evaluated. If a search request matches multiple boost conditions, the final boost score is equal to the sum of the boost scores from all matched boost conditions.

↳ queryExpansionSpec QueryExpansionSpec

The query expansion specification that specifies the conditions under which query expansion will occur. See more details at this user guide.

↳ variantRollupKeys string[]

The keys to fetch and rollup the matching variant Products attributes, FulfillmentInfo or LocalInventorys attributes. The attributes from all the matching variant Products or LocalInventorys are merged and de-duplicated. Notice that rollup attributes will lead to extra query latency. Maximum number of keys is 30. For FulfillmentInfo, a fulfillment type and a fulfillment ID must be provided in the format of "fulfillmentType.fulfillmentId". E.g., in "pickupInStore.store123", "pickupInStore" is fulfillment type and "store123" is the store ID. Supported keys are: * colorFamilies * price * originalPrice * discount * variantId * inventory(place_id,price) * inventory(place_id,original_price) * inventory(place_id,attributes.key), where key is any key in the Product.local_inventories.attributes map. * attributes.key, where key is any key in the Product.attributes map. * pickupInStore.id, where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "pickup-in-store". * shipToStore.id, where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "ship-to-store". * sameDayDelivery.id, where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "same-day-delivery". * nextDayDelivery.id, where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "next-day-delivery". * customFulfillment1.id, where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "custom-type-1". * customFulfillment2.id, where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "custom-type-2". * customFulfillment3.id, where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "custom-type-3". * customFulfillment4.id, where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "custom-type-4". * customFulfillment5.id, where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "custom-type-5". If this field is set to an invalid value other than these, an INVALID_ARGUMENT error is returned.

↳ pageCategories string[]

The categories associated with a category page. Required for category navigation queries to achieve good search quality. The format should be the same as UserEvent.page_categories; To represent full path of category, use '>' sign to separate different hierarchies. If '>' is part of the category name, replace it with other character(s). Category pages include special pages such as sales or promotions. For instance, a special sale page may have the category hierarchy: "pageCategories" : ["Sales > 2017 Black Friday Deals"].

↳ searchMode int

The search mode of the search request. If not specified, a single search request triggers both product search and faceted search. For allowed values, use constants defined on Google\Cloud\Retail\V2\SearchRequest\SearchMode

↳ personalizationSpec PersonalizationSpec

The specification for personalization. Notice that if both ServingConfig.personalization_spec and SearchRequest.personalization_spec are set. SearchRequest.personalization_spec will override ServingConfig.personalization_spec.

↳ labels array

The labels applied to a resource must meet the following requirements: * Each resource can have multiple labels, up to a maximum of 64. * Each label must be a key-value pair. * Keys have a minimum length of 1 character and a maximum length of 63 characters and cannot be empty. Values can be empty and have a maximum length of 63 characters. * Keys and values can contain only lowercase letters, numeric characters, underscores, and dashes. All characters must use UTF-8 encoding, and international characters are allowed. * The key portion of a label must be unique. However, you can use the same key with multiple resources. * Keys must start with a lowercase letter or international character. See Google Cloud Document for more details.

↳ spellCorrectionSpec SpellCorrectionSpec

The spell correction specification that specifies the mode under which spell correction will take effect.

↳ retrySettings RetrySettings|array

Retry settings to use for this call. Can be a Google\ApiCore\RetrySettings object, or an associative array of retry settings parameters. See the documentation on Google\ApiCore\RetrySettings for example usage.

Returns
TypeDescription
Google\ApiCore\PagedListResponse
Example
use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;
use Google\Cloud\Retail\V2\SearchResponse\SearchResult;
use Google\Cloud\Retail\V2\SearchServiceClient;

/**
 * @param string $placement The resource name of the Retail Search serving config, such as
 *                          `projects/*/locations/global/catalogs/default_catalog/servingConfigs/default_serving_config`
 *                          or the name of the legacy placement resource, such as
 *                          `projects/*/locations/global/catalogs/default_catalog/placements/default_search`.
 *                          This field is used to identify the serving config name and the set
 *                          of models that will be used to make the search.
 * @param string $visitorId A unique identifier for tracking visitors. For example, this
 *                          could be implemented with an HTTP cookie, which should be able to uniquely
 *                          identify a visitor on a single device. This unique identifier should not
 *                          change if the visitor logs in or out of the website.
 *
 *                          This should be the same identifier as
 *                          [UserEvent.visitor_id][google.cloud.retail.v2.UserEvent.visitor_id].
 *
 *                          The field must be a UTF-8 encoded string with a length limit of 128
 *                          characters. Otherwise, an INVALID_ARGUMENT error is returned.
 */
function search_sample(string $placement, string $visitorId): void
{
    // Create a client.
    $searchServiceClient = new SearchServiceClient();

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

        /** @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());
    }
}

/**
 * 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
{
    $placement = '[PLACEMENT]';
    $visitorId = '[VISITOR_ID]';

    search_sample($placement, $visitorId);
}

Constants

SERVICE_NAME

Value: 'google.cloud.retail.v2.SearchService'

The name of the service.

SERVICE_ADDRESS

Value: 'retail.googleapis.com'

The default address of the service.

DEFAULT_SERVICE_PORT

Value: 443

The default port of the service.

CODEGEN_NAME

Value: 'gapic'

The name of the code generator, to be included in the agent header.