Java SDK
RecallEngine with the Java SDK
Use the Java SDK with RecallEngine to recall and write data.
Prerequisites
-
You have created a recall engine instance and obtained its endpoint, instance ID, username, and password.
-
You have created a target table and a recall service in the recall engine.
Install the Java SDK
Add the following dependency to your Maven project's pom.xml file:
<dependency>
<groupId>com.aliyun.openservices.aiservice</groupId>
<artifactId>pairec-sdk</artifactId>
<version>1.0.9</version>
</dependency>
Initialize the Recall Engine client
API
RecallEngineClient client = new RecallEngineClient(endpoint, username, password);
Parameters
|
Parameter |
Example |
Description |
|
endpoint |
http://ep-xxxxxx.aliyuncs.com |
The Recall Engine service endpoint. |
|
username |
System.getenv("RECALL_ENGINE_SERVICE_USERNAME") |
The username for authentication. |
|
password |
System.getenv("RECALL_ENGINE_SERVICE_PASSWORD") |
The password for authentication. |
The Recall Engine endpoint is available on the Basic Information page of Recall Management in the PAI-Rec console.
In the VPC High-speed Connection Configuration section, the endpoint column shows the Recall Engine endpoint.
Optional settings for internal calls
|
Method |
Description |
|
withRetryTimes(int retryTimes) |
Sets the number of retries for a failed request. The default is 0 (no retries). |
|
withHttpClient(OkHttpClient httpClient) |
Sets a custom OkHttpClient instance to configure parameters such as the connection pool and timeout. |
Note
-
By default, the client has a connection timeout of 200 ms, a read/write timeout of 500 ms, and a maximum connection pool size of 1,000.
-
All optional configuration methods can be chained.
Example
import com.aliyun.openservices.pairec.recallengine.RecallEngineClient;
// Get authentication information from environment variables.
String endpoint = System.getenv("RECALL_ENGINE_SERVICE_ENDPOINT");
String username = System.getenv("RECALL_ENGINE_SERVICE_USERNAME");
String password = System.getenv("RECALL_ENGINE_SERVICE_PASSWORD");
// Create the client.
RecallEngineClient client = new RecallEngineClient(endpoint, username, password);
// Set the number of retries.
client.withRetryTimes(2);
Optional settings for public calls
|
Method |
Description |
|
withRetryTimes(int retryTimes) |
Sets the number of retries for a failed request. The default is 0 (no retries). |
|
withHttpClient(OkHttpClient httpClient) |
Sets a custom OkHttpClient instance to configure parameters such as the connection pool and timeout. |
|
withRegion(String region) |
Sets the region of the instance. This parameter is required. |
|
withInstanceId(String instanceId) |
Sets the instance ID. This parameter is required. |
|
withAccessKeyId(String accessKeyId) |
Sets the access key ID. This parameter is required. |
|
withAccessKeySecret(String accessKeySecret) |
Sets the access key secret. This parameter is required. |
|
withPublicEndpoint(boolean usePublicEndpoint) |
Enables the public endpoint. Must be set to true. Takes effect only after the four preceding required parameters are set. |
Note
-
You must set the access key parameters for authentication.
-
When using a public endpoint, pass an empty string to the endpoint parameter of the client constructor.
-
Call the withPublicEndpoint(boolean usePublicEndpoint) method last.
Example
import com.aliyun.openservices.pairec.recallengine.RecallEngineClient;
// Get authentication information from environment variables.
String akId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String akSecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
String region = System.getenv("PAI_REC_REGION");
String instanceId = System.getenv("RECALL_ENGINE_INSTANCE_ID");
String username = System.getenv("RECALL_ENGINE_SERVICE_USERNAME");
String password = System.getenv("RECALL_ENGINE_SERVICE_PASSWORD");
// Create the client.
RecallEngineClient client = new RecallEngineClient("", username, password);
// Configure parameters for a public call.
client.withAccessKeyId(akId)
.withAccessKeySecret(akSecret)
.withRegion(region)
.withInstanceId(instanceId)
.withPublicEndpoint(true)
.withRetryTimes(2);
Recall data
API
public RecallResponse recall(RecallRequest request) throws RecallEngineException;
RecallRequest parameters
|
Parameter |
JSON property name |
Type |
Description |
|
instanceId |
instance_id |
String |
The Recall Engine instance ID. |
|
service |
service |
String |
The recall service name. |
|
version |
version |
String |
The recall service version. |
|
uid |
uid |
String |
The user ID. |
|
recalls |
recalls |
Map<String, RecallConf> |
A map of recall configurations, keyed by recall name. |
|
requestId |
request_id |
String |
The request ID. This parameter is optional. |
|
exposureList |
exposure_list |
String |
An exposure list to filter out previously exposed content. This parameter is optional. |
|
contextParams |
context_params |
Map<String, Object> |
Custom context parameters. This parameter is optional. |
|
debug |
debug |
boolean |
Enables debug mode. This parameter is optional. Default: |
|
retainFields |
retain_fields |
List<String> |
The fields to include in the recall result. This parameter is optional. |
RecallConf parameters
|
Parameter |
Type |
Description |
|
trigger |
String |
The trigger value for the recall. |
|
count |
int |
The number of results to return. |
RecallResponse
|
Method |
Return type |
Description |
|
getResult() |
Record |
Returns the record set. |
Example
import com.aliyun.openservices.pairec.recallengine.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
RecallEngineClient client = new RecallEngineClient(endpoint, username, password);
// Create a recall request.
RecallRequest request = new RecallRequest();
request.setInstanceId("your-instance-id");
request.setService("recall_test");
request.setVersion("V1");
request.setUid("123");
request.setRetainFields(Arrays.asList("click"))
// Set recall configurations.
Map<String, RecallConf> recalls = new HashMap<>();
recalls.put("u2i_recall", new RecallConf("123", 100));
request.setRecalls(recalls);
// Execute the recall.
RecallResponse resp = client.recall(request);
Record result = resp.getResult();
// Get the result information.
System.out.println("Total records: " + result.size());
System.out.println("Field names: " + result.fieldNames());
Write data
Syntax
public WriteResponse write(String instanceId, String table, WriteRequest request) throws RecallEngineException;
Parameters
|
Parameter |
Type |
Description |
|
instanceId |
String |
The Recall Engine instance ID. |
|
table |
String |
The name of the target table. |
|
request |
WriteRequest |
The write request object. |
WriteRequest parameters
|
Parameter |
JSON property name |
Type |
Description |
|
requestId |
request_id |
String |
The request ID. This parameter is optional. |
|
content |
content |
List<Map<String, Object>> |
The data to write. Each Map object represents a data row, mapping field names (keys) to their corresponding values. |
|
versionId |
versionId |
String |
The version ID. This parameter is optional. |
|
insertMode |
insert_mode |
String |
The insert mode. Valid values are |
WriteResponse
WriteResponse extends Response and provides the following methods:
|
Method |
Return type |
Description |
|
getRequestId() |
String |
The request ID. |
|
getCode() |
String |
The status code. A value of "OK" indicates success. |
|
getMessage() |
String |
The response message. |
|
getData() |
Map<String, Object> |
The response data. |
Example
import com.aliyun.openservices.pairec.recallengine.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// 1. Insert an initial record with all fields.
WriteRequest insertRequest = new WriteRequest();
insertRequest.setRequestId("partial-update-init");
insertRequest.setInsertMode(InsertMode.INSERT);
Map<String, Object> initialData = new HashMap<>();
initialData.put("item_id", "item_partial_test_002");
initialData.put("bool_field", true);
initialData.put("category", "electronics");
initialData.put("list", java.util.Arrays.asList("tag1", "tag2", "tag3"));
java.util.List<Map<String, Object>> content = new java.util.ArrayList<>();
content.add(initialData);
insertRequest.setContent(content);
WriteResponse initResp = client.write(instanceId, tableName, insertRequest);
assertEquals("OK", initResp.getCode());
// Flush to ensure the data is written.
client.writeFlush();
System.out.println("Initial insert completed");
// 2. Partial update: Update only the category field.
WriteRequest updateRequest = new WriteRequest();
updateRequest.setRequestId("partial-update-category");
updateRequest.setInsertMode(InsertMode.UPSERT); // The UPSERT mode supports partial updates.
Map<String, Object> partialData = new HashMap<>();
// The primary key is required to identify the record.
partialData.put("item_id", "item_partial_test_002");
// Only the category field is updated. Other fields (bool_field, list) are not affected.
partialData.put("category", "home_appliances");
java.util.List<Map<String, Object>> updateContent = new java.util.ArrayList<>();
updateContent.add(partialData);
updateRequest.setContent(updateContent);
WriteResponse updateResp = client.write(instanceId, tableName, updateRequest);
assertEquals("OK", updateResp.getCode());
// Flush to ensure the data is written.
client.writeFlush();
System.out.println("Partial update completed: category updated to 'home_appliances'");
Delete data
API
public DeleteResponse delete(String instanceId, String table, DeleteRequest request) throws RecallEngineException
Parameters
|
Parameter |
Type |
Description |
|
instanceId |
String |
The ID of the Recall Engine instance. |
|
table |
String |
The name of the target table. |
|
request |
DeleteRequest |
The delete request object. |
DeleteRequest parameters
|
Parameter |
JSON property |
Type |
Description |
|
requestId |
request_id |
String |
The request ID (optional). |
|
keys |
keys |
List<String> |
The primary keys of the data rows to delete. |
|
versionId |
version_id |
String |
The version ID (optional). |
|
schema |
schema |
String |
The schema or namespace of the data table. Defaults to "default" if not specified. |
DeleteResponse
DeleteResponse extends Response and provides the following methods:
|
Method |
Return type |
Description |
|
getRequestId() |
String |
The request ID. |
|
getCode() |
String |
The status code. A value of "OK" indicates success. |
|
getMessage() |
String |
The response message. |
|
getData() |
Map<String, Object> |
The response data. |
Example
import com.aliyun.openservices.pairec.recallengine.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
String instanceId = "learn-pairec-cn-3ic4mhhvr01";
String tableName = "test_exposure1";
DeleteRequest deleteRequest = new DeleteRequest();
deleteRequest.setRequestId("delete-version-test-001");
deleteRequest.setKeys(Arrays.asList("12345", "67890"));
deleteRequest.setSchema("default");
deleteRequest.setVersionId("20260327102603");
DeleteResponse deleteResp = client.delete(instanceId, tableName, deleteRequest);
System.out.println("Delete with version response: " + deleteResp.getCode() + ", " + deleteResp.getMessage());
Work with recall results
The Record returned by RecallResponse.getResult() provides chainable methods to sort, filter, truncate, and process the recall results.
API
public Record sort(String name, boolean desc);
public Record retain(int count);
public Record filter(String name);
public Record filterByColumnValue(String name, Predicate<Object> predicate);
public Record filterByValues(Predicate<Map<String, Object>> predicate);
public Record random();
public List<Object> columnValues(String columnName);
public List<String> columnValuesString(String columnName);
public List<String> fieldNames();
public int size();
Methods
|
Method |
Description |
|
sort(name, desc) |
Sorts the records by a specified column. Set |
|
retain(count) |
Keeps the first |
|
filter(name) |
Deduplicates records by the specified column. |
|
filterByColumnValue(name, predicate) |
Keeps only records where the specified column value satisfies the predicate. |
|
filterByValues(predicate) |
Filters records by applying a predicate to each row ( |
|
random() |
Randomly shuffles the records. |
|
columnValues(columnName) |
Returns all values in the specified column. |
|
columnValuesString(columnName) |
Returns all non-null string values in the specified column. |
|
fieldNames() |
Returns the names of all fields. |
|
size() |
Returns the current number of records. |
Notes
-
The
sort,retain,filter,filterByColumnValue,filterByValues, andrandommethods all returnthisto support method chaining. -
The
Recordclass is not thread-safe. Do not use the sameRecordinstance from multiple threads.
Example
RecallResponse resp = client.recall(request);
Record result = resp.getResult();
// Sort by score in descending order, deduplicate by item_id, and retain the top 10.
Record processed = result
.sort("score", true)
.filter("item_id")
.retain(10);
System.out.println("Processed records: " + processed.size());
// Get all values from the item_id column.
List<String> itemIds = processed.columnValuesString("item_id");
System.out.println("Item IDs: " + itemIds);
// Filter by condition: keep only records where score > 0.5.
Record filtered = result.filterByColumnValue("score", value -> {
if (value instanceof Number) {
return ((Number) value).doubleValue() > 0.5;
}
return false;
});
// Filter based on the entire row.
Record filtered2 = result.filterByValues(row -> {
Object category = row.get("category");
return category != null && "video".equals(category.toString());
});
Complete example
The following example demonstrates write, recall, and delete operations:
import com.aliyun.openservices.pairec.recallengine.*;
import java.util.*;
public class RecallEngineDemo {
public static void main(String[ ] args) throws RecallEngineException {
// 1. Initialize the client.
String endpoint = System.getenv("RECALL_ENGINE_SERVICE_ENDPOINT");
String username = System.getenv("RECALL_ENGINE_SERVICE_USERNAME");
String password = System.getenv("RECALL_ENGINE_SERVICE_PASSWORD");
RecallEngineClient client = new RecallEngineClient(endpoint, username, password);
client.withRetryTimes(2);
String instanceId = System.getenv("INSTANCE_ID");
// 2. Write data.
WriteRequest writeRequest = new WriteRequest();
writeRequest.setRequestId("write-req-001");
List<Map<String, Object>> content = new ArrayList<>();
Map<String, Object> item = new HashMap<>();
item.put("user_id", "123");
item.put("item_id", "item_456");
item.put("score", 0.95);
content.add(item);
writeRequest.setContent(content);
WriteResponse writeResp = client.write(instanceId, "u2i_table", writeRequest);
System.out.println("Write result: " + writeResp.getCode());
// 3. Recall data.
RecallRequest recallRequest = new RecallRequest();
recallRequest.setInstanceId(instanceId);
recallRequest.setService("recall_test");
recallRequest.setVersion("V1");
recallRequest.setUid("123");
Map<String, RecallConf> recalls = new HashMap<>();
recalls.put("u2i_recall", new RecallConf("123", 100));
recallRequest.setRecalls(recalls);
RecallResponse recallResp = client.recall(recallRequest);
Record result = recallResp.getResult();
// 4. Process the recall result.
System.out.println("Total records: " + result.size());
System.out.println("Field names: " + result.fieldNames());
// Sort by score in descending order and retain the top 10 records.
Record top10 = result.sort("score", true).retain(10);
System.out.println("Top 10 records: " + top10.toString());
// Get the item_id list.
List<String> itemIds = top10.columnValuesString("item_id");
System.out.println("Top 10 item IDs: " + itemIds);
// 5. Delete data.
DeleteRequest deleteRequest = new DeleteRequest();
deleteRequest.setRequestId("delete-version-test-001");
deleteRequest.setKeys(Arrays.asList("123"));
deleteRequest.setSchema("default");
DeleteResponse deleteResp = client.delete(instanceId, "u2i_table", deleteRequest);
System.out.println("Delete result: " + deleteResp.getCode());
}
}
Exception handling
All recall and write operations can throw RecallEngineException. Use a try-catch block to handle exceptions:
try {
RecallResponse resp = client.recall(request);
// Process the result.
} catch (RecallEngineException e) {
System.err.println("Recall failed: " + e.getMessage());
}