Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions developer-knowledge/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Google Developer Knowledge API Java Samples

This directory contains Java code samples demonstrating how to use the [Google Developer Knowledge API](https://developers.google.com/knowledge) client library (`com.google.cloud:google-cloud-developer-knowledge`).

## Setup

1. Enable the Developer Knowledge API on your Google Cloud project:
```bash
gcloud services enable developerknowledge.googleapis.com
```

2. Build with Maven:
```bash
mvn clean compile
```

## Samples

* **[Search Document Chunks](src/main/java/developerknowledge/SearchDocumentChunks.java)**: Search public developer documentation chunks by query (`developerknowledge_search_document_chunks`).
* **[Get Document](src/main/java/developerknowledge/GetDocument.java)**: Retrieve a single documentation page with full markdown content (`developerknowledge_get_document`).
* **[Batch Get Documents](src/main/java/developerknowledge/BatchGetDocuments.java)**: Fetch multiple documentation pages in one call (`developerknowledge_batch_get_documents`).
* **[Answer Query](src/main/java/developerknowledge/AnswerQuery.java)**: Get a grounded, cited answer to a technical question (`developerknowledge_answer_query`).

## Running Tests

```bash
mvn test
```
59 changes: 59 additions & 0 deletions developer-knowledge/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<!--
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="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.developerknowledge</groupId>
<artifactId>developer-knowledge-samples</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>Google Developer Knowledge Snippets</name>

<parent>
<groupId>com.google.cloud.samples</groupId>
<artifactId>shared-configuration</artifactId>
<version>1.2.0</version>
</parent>

<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-developer-knowledge</artifactId>
<version>0.3.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<version>1.4.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* 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 developerknowledge;

// [START developerknowledge_answer_query]
import com.google.developers.knowledge.v1.AnswerQueryRequest;
import com.google.developers.knowledge.v1.AnswerQueryResponse;
import com.google.developers.knowledge.v1.DeveloperKnowledgeClient;
import java.io.IOException;

public class AnswerQuery {

public static void main(String[] args) throws IOException {
// TODO(developer): Replace these variables before running the sample.
String query = "How do I create a Google Cloud Storage bucket?";
answerQuery(query);
}

// Answers a developer question grounded in Google developer documentation.
public static AnswerQueryResponse answerQuery(String query) throws IOException {
// 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 "close" method on the client to safely clean up any remaining background resources.
try (DeveloperKnowledgeClient client = DeveloperKnowledgeClient.create()) {
AnswerQueryRequest request =
AnswerQueryRequest.newBuilder().setQuery(query).build();

AnswerQueryResponse response = client.answerQuery(request);

System.out.println("Answer:\n" + response.getAnswer().getAnswerText() + "\n");
System.out.println("Citations count: " + response.getAnswer().getCitationsCount());
System.out.println("References count: " + response.getAnswer().getReferencesCount());

return response;
}
}
}
// [END developerknowledge_answer_query]
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* 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 developerknowledge;

// [START developerknowledge_batch_get_documents]
import com.google.developers.knowledge.v1.BatchGetDocumentsRequest;
import com.google.developers.knowledge.v1.BatchGetDocumentsResponse;
import com.google.developers.knowledge.v1.DeveloperKnowledgeClient;
import com.google.developers.knowledge.v1.Document;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class BatchGetDocuments {

public static void main(String[] args) throws IOException {
// TODO(developer): Replace these variables before running the sample.
List<String> names =
Arrays.asList(
"documents/docs.cloud.google.com/storage/docs/creating-buckets",
"documents/docs.cloud.google.com/storage/docs/deleting-buckets");
batchGetDocuments(names);
}

// Retrieves multiple developer documentation pages in a single request.
public static BatchGetDocumentsResponse batchGetDocuments(List<String> names) throws IOException {
// 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 "close" method on the client to safely clean up any remaining background resources.
try (DeveloperKnowledgeClient client = DeveloperKnowledgeClient.create()) {
BatchGetDocumentsRequest request =
BatchGetDocumentsRequest.newBuilder().addAllNames(names).build();

BatchGetDocumentsResponse response = client.batchGetDocuments(request);

for (Document doc : response.getDocumentsList()) {
System.out.println("Title: " + doc.getTitle());
System.out.println("URI: " + doc.getUri());
System.out.println("Content Length: " + doc.getContentLengthBytes() + " bytes\n");
}

return response;
}
}
}
// [END developerknowledge_batch_get_documents]
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* 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 developerknowledge;

// [START developerknowledge_get_document]
import com.google.developers.knowledge.v1.DeveloperKnowledgeClient;
import com.google.developers.knowledge.v1.Document;
import com.google.developers.knowledge.v1.GetDocumentRequest;
import java.io.IOException;

public class GetDocument {

public static void main(String[] args) throws IOException {
// TODO(developer): Replace these variables before running the sample.
String name = "documents/docs.cloud.google.com/storage/docs/creating-buckets";
getDocument(name);
}

// Retrieves a single developer documentation page by its resource name.
public static Document getDocument(String name) throws IOException {
// 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 "close" method on the client to safely clean up any remaining background resources.
try (DeveloperKnowledgeClient client = DeveloperKnowledgeClient.create()) {
GetDocumentRequest request = GetDocumentRequest.newBuilder().setName(name).build();

Document document = client.getDocument(request);

System.out.println("Title: " + document.getTitle());
System.out.println("URI: " + document.getUri());
System.out.println("Data Source: " + document.getDataSource());
System.out.println("Content Length: " + document.getContentLengthBytes() + " bytes");
String preview = document.getContent();
if (preview.length() > 150) {
preview = preview.substring(0, 150) + "...";
}
System.out.println("Content Preview: " + preview + "\n");

return document;
}
}
}
// [END developerknowledge_get_document]
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* 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 developerknowledge;

// [START developerknowledge_search_document_chunks]
import com.google.developers.knowledge.v1.DeveloperKnowledgeClient;
import com.google.developers.knowledge.v1.DeveloperKnowledgeClient.SearchDocumentChunksPagedResponse;
import com.google.developers.knowledge.v1.DocumentChunk;
import com.google.developers.knowledge.v1.SearchDocumentChunksRequest;
import java.io.IOException;

public class SearchDocumentChunks {

public static void main(String[] args) throws IOException {
// TODO(developer): Replace these variables before running the sample.
String query = "How to create a Cloud Storage bucket";
int pageSize = 5;
searchDocumentChunks(query, pageSize);
}

// Searches developer documentation chunks for a given query.
public static SearchDocumentChunksPagedResponse searchDocumentChunks(
String query, int pageSize) throws IOException {
// 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 "close" method on the client to safely clean up any remaining background resources.
try (DeveloperKnowledgeClient client = DeveloperKnowledgeClient.create()) {
SearchDocumentChunksRequest request =
SearchDocumentChunksRequest.newBuilder()
.setQuery(query)
.setPageSize(pageSize)
.build();

SearchDocumentChunksPagedResponse response = client.searchDocumentChunks(request);

for (DocumentChunk chunk : response.getPage().getValues()) {

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 PR description mentions "manual pagination handling," but the current implementation only retrieves the first page of results and does not fetch subsequent pages.

To retrieve all results across all pages in an idiomatic way, use response.iterateAll(). If you only want to retrieve a single page, please consider updating the PR description to avoid confusion.

Suggested change
for (DocumentChunk chunk : response.getPage().getValues()) {
for (DocumentChunk chunk : response.iterateAll()) {

System.out.println("Parent Document: " + chunk.getParent());
System.out.println("Chunk ID: " + chunk.getId());
String preview = chunk.getContent();
if (preview.length() > 100) {
preview = preview.substring(0, 100) + "...";
}
System.out.println("Content: " + preview + "\n");
}

return response;
}
}
}
// [END developerknowledge_search_document_chunks]
Loading