Skip to content
26 changes: 26 additions & 0 deletions retail/snippets/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Vertex AI Search for commerce Samples

This directory contains Java samples for [Vertex AI Search for commerce](https://cloud.google.com/retail/docs/search-basic#search).

## Prerequisites

To run these samples, you must have:

1. **A Google Cloud Project** with the [Vertex AI Search for commerce API](https://console.cloud.google.com/apis/library/retail.googleapis.com) enabled.
2. **Vertex AI Search for commerce** set up with a valid catalog and serving configuration (placement).
3. **Authentication**: These samples use [Application Default Credentials (ADC)](https://cloud.google.com/docs/authentication/provide-credentials-adc).
- If running locally, you can set up ADC by running:
```bash
gcloud auth application-default login
```
4. **IAM Roles**: The service account or user running the samples needs the `roles/retail.viewer` (Retail Viewer) role or higher.

## Samples

- **[Search.java](src/main/java/com/example/search/Search.java)**: Basic search request showing both text search and browse search (using categories).
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The description for Search.java is inaccurate. It states that the sample shows "both text search and browse search (using categories)", but the implementation in Search.java only demonstrates a basic text search using the query parameter. It does not include any category-based filtering or browsing logic.

- **[SearchPagination.java](src/main/java/com/example/search/SearchPagination.java)**: Shows how to use `next_page_token` to paginate through search results.
- **[SearchOffset.java](src/main/java/com/example/search/SearchOffset.java)**: Shows how to use `offset` to skip a specified number of results.

## Documentation

For more information, see the [Vertex AI Search for commerce documentation](https://docs.cloud.google.com/retail/docs/search-basic#search).
72 changes: 72 additions & 0 deletions retail/snippets/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2026 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.retail</groupId>
<artifactId>retail-samples</artifactId>
<version>1.0-SNAPSHOT</version>

<!--
The parent pom defines common style checks and testing strategies for our samples.
Removing or replacing it should not affect the execution of the samples in anyway.
-->
<parent>
<artifactId>shared-configuration</artifactId>
<groupId>com.google.cloud.samples</groupId>
<version>1.2.2</version>
</parent>

<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<artifactId>libraries-bom</artifactId>
<groupId>com.google.cloud</groupId>
<scope>import</scope>
<type>pom</type>
<version>26.80.0</version>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-retail</artifactId>
</dependency>
Comment on lines +53 to +56
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Since you are using the libraries-bom in the dependencyManagement section, you should omit the explicit version for google-cloud-retail. This allows the BOM to manage the version, ensuring compatibility across different Google Cloud libraries and avoiding potential dependency conflicts.

    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-retail</artifactId>
    </dependency>


<!-- Test dependencies -->
<dependency>
<artifactId>truth</artifactId>
<groupId>com.google.truth</groupId>
<scope>test</scope>
<version>1.4.5</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.14.3</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
84 changes: 84 additions & 0 deletions retail/snippets/src/main/java/com/example/search/Search.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
* Copyright 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.search;

// [START retail_v2_search_request]

import com.google.cloud.retail.v2.BranchName;
import com.google.cloud.retail.v2.Product;
import com.google.cloud.retail.v2.SearchRequest;
import com.google.cloud.retail.v2.SearchResponse;
import com.google.cloud.retail.v2.SearchResponse.SearchResult;
import com.google.cloud.retail.v2.SearchServiceClient;
import com.google.cloud.retail.v2.SearchServiceClient.SearchPagedResponse;
import com.google.cloud.retail.v2.ServingConfigName;
import java.io.IOException;
import java.util.List;

public class Search {
Comment thread
XrossFox marked this conversation as resolved.
public static void main(String[] args) throws IOException {
String projectId = "my-project-id";
String visitorId = "my-visitor-id";
String query = "my search query";
List<String> categories = List.of("category");

search(projectId, visitorId, query, categories);
}

/**
* Search for products using Vertex AI Search for commerce.
*
* Performs a search request for a specific placement. Handles both text search (using query)
* and browse search (using page_categories).
*
* @param projectId The Google Cloud project ID.
* @param visitorId A unique identifier for the user.
* @param query The search term for text search.
* @param categories The categories for browse search.
* @throws IOException
*/
public static void search(
String projectId, String visitorId, String query, List<String> categories)
throws IOException {
try (SearchServiceClient searchServiceClient = SearchServiceClient.create()) {
ServingConfigName servingConfigName =
ServingConfigName.of(projectId, "global", "default_catalog", "default_search");
BranchName branchName =
BranchName.of(projectId, "global", "default_catalog", "default_branch");
SearchRequest searchRequest =
SearchRequest.newBuilder()
.setPlacement(servingConfigName.toString())
.setBranch(branchName.toString())
.setVisitorId(visitorId)
.setQuery(query)
.addAllPageCategories(categories)
.setPageSize(10)
.build();
SearchPagedResponse response = searchServiceClient.search(searchRequest);

SearchResponse searchResponse = response.getPage().getResponse();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The expression response.getPage().getResponse() can be simplified to response.getResponse(). The SearchPagedResponse object provides direct access to the underlying SearchResponse message.

Suggested change
SearchResponse searchResponse = response.getPage().getResponse();
SearchResponse searchResponse = response.getResponse();
References
  1. For code samples, conventions may allow for practices that favor simplicity and clarity.


System.out.println("Found " + searchResponse.getResultsCount() + " results in current page");
for (SearchResult searchResult : searchResponse.getResultsList()) {
Product product = searchResult.getProduct();
System.out.println("---- Search Result ----");
System.out.println("Product Name: " + product.getName());
}
}
Comment thread
XrossFox marked this conversation as resolved.
}
}
// [END retail_v2_search_request]
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
* Copyright 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.search;

// [START retail_v2_search_offset]

import com.google.cloud.retail.v2.BranchName;
import com.google.cloud.retail.v2.Product;
import com.google.cloud.retail.v2.SearchRequest;
import com.google.cloud.retail.v2.SearchResponse;
import com.google.cloud.retail.v2.SearchResponse.SearchResult;
import com.google.cloud.retail.v2.SearchServiceClient;
import com.google.cloud.retail.v2.SearchServiceClient.SearchPagedResponse;
import com.google.cloud.retail.v2.ServingConfigName;
import java.io.IOException;

public class SearchOffset {
public static void main(String[] args) throws IOException {
String projectId = "my-project-id";
String visitorId = "my-visitor-id";
String query = "my search query";
int offset = 10;

searchWithOffset(projectId, visitorId, query, offset);
}

/**
* Search for products with an offset using Vertex AI Search for commerce.
*
* Performs a search request starting from a specified position.
*
* @param projectId The Google Cloud project ID.
* @param visitorId A unique identifier for the user.
* @param query The search term for text search.
* @param offset The number of results to skip.
* @throws IOException
*/
public static void searchWithOffset(String projectId, String visitorId, String query, int offset)
throws IOException {
try (SearchServiceClient searchServiceClient = SearchServiceClient.create()) {
ServingConfigName servingConfigName =
ServingConfigName.of(projectId, "global", "default_catalog", "default_search");
BranchName branchName =
BranchName.of(projectId, "global", "default_catalog", "default_branch");
SearchRequest searchRequest =
SearchRequest.newBuilder()
.setPlacement(servingConfigName.toString())
.setBranch(branchName.toString())
.setVisitorId(visitorId)
.setQuery(query)
.setPageSize(10)
.setOffset(offset)
.build();
SearchPagedResponse response = searchServiceClient.search(searchRequest);

SearchResponse searchResponse = response.getPage().getResponse();

System.out.println("Found " + searchResponse.getResultsCount() + " results in current page");
for (SearchResult searchResult : searchResponse.getResultsList()) {
Product product = searchResult.getProduct();
System.out.println("---- Search Result ----");
System.out.println("Product Name: " + product.getName());
}
}
}
}
// [END retail_v2_search_offset]
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
* Copyright 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.search;

// [START retail_v2_search_pagination]

import com.google.cloud.retail.v2.BranchName;
import com.google.cloud.retail.v2.Product;
import com.google.cloud.retail.v2.SearchRequest;
import com.google.cloud.retail.v2.SearchResponse.SearchResult;
import com.google.cloud.retail.v2.SearchServiceClient;
import com.google.cloud.retail.v2.SearchServiceClient.SearchPage;
import com.google.cloud.retail.v2.SearchServiceClient.SearchPagedResponse;
import com.google.cloud.retail.v2.ServingConfigName;
import java.io.IOException;

public class SearchPagination {
public static void main(String[] args) throws IOException {
String projectId = "my-project-id";
String visitorId = "my-visitor-id";
String query = "my search query";
int pageSize = 10;

searchWithPagination(projectId, visitorId, query, pageSize);
}

/**
* Search for products with pagination using Vertex AI Search for commerce.
*
* Performs a search request, then uses the next_page_token to get the next page.
*
* @param projectId The Google Cloud project ID.
* @param visitorId A unique identifier for the user.
* @param query The search term for text search.
* @param pageSize The amount of results per page.
* @throws IOException
*/
public static void searchWithPagination(
String projectId, String visitorId, String query, int pageSize) throws IOException {
try (SearchServiceClient searchServiceClient = SearchServiceClient.create()) {
ServingConfigName servingConfigName =
ServingConfigName.of(projectId, "global", "default_catalog", "default_search");
BranchName branchName =
BranchName.of(projectId, "global", "default_catalog", "default_branch");
SearchRequest request =
SearchRequest.newBuilder()
.setPlacement(servingConfigName.toString())
.setBranch(branchName.toString())
.setVisitorId(visitorId)
.setQuery(query)
.setPageSize(pageSize)
.build();
int currentPage = 0;
while (true) {
SearchPagedResponse response = searchServiceClient.search(request);

SearchPage page = response.getPage();
currentPage++;
System.out.println("\nResults of page number " + currentPage + ":");
System.out.println(
"Found " + page.getResponse().getResultsCount() + " results in current page");
for (SearchResult searchResult : page.getResponse().getResultsList()) {
Product product = searchResult.getProduct();
System.out.println("---- Search Result ----");
System.out.println("Product Name: " + product.getName());
}

if (page.hasNextPage()) {
request = request.toBuilder().setPageToken(page.getNextPageToken()).build();
} else {
System.out.println("\nNo more available pages.");
break;
}
}
}
}
}
// [END retail_v2_search_pagination]
Loading