Push demo
Configure environment variables
Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
The AccessKey pair of an Alibaba Cloud account can be used to access all API operations. We recommend that you use a Resource Access Management (RAM) user to call API operations or perform routine O&M. For information about how to use a RAM user, see Create a RAM user.
For information about how to create an AccessKey pair, see Create an AccessKey pair.
If you use the AccessKey pair of a RAM user, make sure that the required permissions are granted to the AliyunServiceRoleForOpenSearch role by using your Alibaba Cloud account. For more information, see AliyunServiceRoleForOpenSearch and Access authorization rules.
We recommend that you do not include your AccessKey pair in materials that are easily accessible to others, such as the project code. Otherwise, your AccessKey pair may be leaked and resources in your account become insecure.
Linux and macOS
Run the following commands. Replace
<access_key_id>and<access_key_secret>with the AccessKey ID and AccessKey secret of the RAM user that you use.export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id> export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>Windows
Create an environment variable file, add the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables to the file, and then set the environment variables to your AccessKey ID and AccessKey secret.
Restart Windows for the AccessKey pair to take effect.
Sample code for adding documents by using the push method in SDK V3.1
With the push method, you generate a collection of data to be pushed in the specified format in advance. Then, when you call the Push method, the entire data collection is pushed to the application in a single batch.
Note
The pushed data collection must conform to the specified data collection format. For reference, see the data collection format in the sample data file that is available in the application console under Upload File -> Sample Data.
Alternatively, you can use JSONObject and JSONArray objects in your program to assemble a data collection in the specified format in advance, and then call the Push method to push the entire data collection to the application in a single batch.
The number of documents in a batch push must not be too large and must not exceed the specified limit. Otherwise, the push may fail with an error.
Scenarios
Pushing dynamically assembled data
Pushing a single document
Generating a data collection in advance and then pushing the data collection in a batch
Pushing data in batches
package com.aliyun.opensearch;
import com.aliyun.opensearch.sdk.dependencies.com.google.common.collect.Lists;
import com.aliyun.opensearch.sdk.dependencies.com.google.common.collect.Maps;
import com.aliyun.opensearch.sdk.dependencies.org.json.JSONArray;
import com.aliyun.opensearch.sdk.dependencies.org.json.JSONObject;
import com.aliyun.opensearch.sdk.generated.OpenSearch;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchClientException;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchException;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchResult;
import com.aliyun.opensearch.sdk.generated.document.Command;
import com.aliyun.opensearch.sdk.generated.document.DocumentConstants;
import com.aliyun.opensearch.sdk.generated.search.*;
import com.aliyun.opensearch.sdk.generated.search.general.SearchResult;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Random;
public class testPushSearch2 {
private String appName = "Replace with the OpenSearch application name";
private String tableName = "Replace with the OpenSearch application table name";
private String host = "Replace with the API endpoint of the application";
public static void main(String[] args) {
//User identification information
//Read the configured AccessKey ID and AccessKey Secret from environment variables.
//You must configure the environment variables before you run the sample code. For more information, see the "Configure environment variables" step earlier in this document.
String accesskey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String secret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
//View the file encoding and the default encoding
System.out.println(String.format("file.encoding: %s", System.getProperty("file.encoding")));
System.out.println(String.format("defaultCharset: %s", Charset.defaultCharset().name()));
//-------------Sample code for pushing data-----------------
//Generate random numbers as primary key values
Random rand = new Random();
int value1 = rand.nextInt(Integer.MAX_VALUE);
int value2 = rand.nextInt(Integer.MAX_VALUE);
//Define a Map object to store the data of the document to upload. This is document 1.
Map<String, Object> doc1 = Maps.newLinkedHashMap();
doc1.put("id", value1);
String title_string = "Document 1 added by using the push method";// utf-8
byte[] bytes;
try {
bytes = title_string.getBytes("utf-8");
String utf8_string = new String(bytes, "utf-8");
doc1.put("name", utf8_string);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
doc1.put("phone", "137****1111");
int[] int_arr = {11,11};
doc1.put("int_arr", int_arr);
String[] literal_arr1 = {"Document 1 added by push","Test document 1 added by push]"};
doc1.put("literal_arr", literal_arr1);
float[] float_arr = {(float)1.1,(float)1.1};
doc1.put("float_arr", float_arr);
doc1.put("cate_id", 1);
//The standard edition does not support update. Use ADD to update all fields. The advanced edition supports update for updating specific fields.
JSONObject json1 = new JSONObject();
json1.put(DocumentConstants.DOC_KEY_CMD, Command.ADD.toString());
json1.put(DocumentConstants.DOC_KEY_FIELDS, doc1);
//Define a Map object to store the data of the document to upload. This is document 2.
Map<String, Object> doc2 = Maps.newLinkedHashMap();
doc2.put("id", value2);
String title_string2 = "Document 2 added by using the push method";// utf-8
byte[] bytes2;
try {
bytes2 = title_string2.getBytes("utf-8");
String utf8_string2 = new String(bytes2, "utf-8");
doc2.put("name", utf8_string2);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
doc2.put("phone", "137****2222");
int[] int_arr2 = {22,22};
doc2.put("int_arr", int_arr2);
String[] literal_arr2 = {"Document 2 added by push","Test document 2 added by push"};
doc2.put("literal_arr", literal_arr2);
float[] float_arr2 = {(float)2.2,(float)2.2};
doc2.put("float_arr", float_arr2);
doc2.put("cate_id", 1);
//Set both additions and updates to ADD. update is not supported. If a document with the same primary key value already exists, the document is updated. Otherwise, a document is added. Here, the document is added.
JSONObject json2 = new JSONObject();
json2.put(DocumentConstants.DOC_KEY_CMD, Command.ADD.toString());
json2.put(DocumentConstants.DOC_KEY_FIELDS, doc2);
//Define a Map object to test updating document data. This is document 3.
Map<String, Object> doc3 = Maps.newLinkedHashMap();
doc3.put("id", value2);
String title_string3 = "Update push document 2 to doc3";// utf-8
byte[] bytes3;
try {
bytes3 = title_string3.getBytes("utf-8");
String utf8_string3 = new String(bytes3, "utf-8");
doc3.put("name", utf8_string3);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
doc3.put("phone", "137****3333");
int[] int_arr3 = {33,33};
doc3.put("int_arr", int_arr3);
String[] literal_arr3 = {"Update push document 2 to doc3","Update push document 2 to doc3"};
doc3.put("literal_arr", literal_arr3);
float[] float_arr3 = {(float)3.3,(float)3.3};
doc3.put("float_arr", float_arr3);
doc3.put("cate_id", 1);
//Set both additions and updates to ADD. update is not supported. A document with the same primary key value must already exist. This is used to test the update.
JSONObject json3 = new JSONObject();
json3.put(DocumentConstants.DOC_KEY_CMD, Command.ADD.toString());
json3.put(DocumentConstants.DOC_KEY_FIELDS, doc3);
//Define a Map object to test document data. This is document 4. To delete a document, you only need to specify the primary key value of the document to delete. Here, document 1 is deleted for testing.
Map<String, Object> doc4 = Maps.newLinkedHashMap();
doc4.put("id", value1);
//Specify the document deletion operation
JSONObject json4 = new JSONObject();
json4.put(DocumentConstants.DOC_KEY_CMD, Command.DELETE.toString());
json4.put(DocumentConstants.DOC_KEY_FIELDS, doc4);
JSONArray docsJsonArr = new JSONArray();
docsJsonArr.put(json1);//Add document 1
docsJsonArr.put(json2);//Add document 2
docsJsonArr.put(json3);//Update push document 2 to doc3
docsJsonArr.put(json4);//Delete document 1
String docsJson = docsJsonArr.toString();
//Create and construct an OpenSearch object
OpenSearch openSearch = new OpenSearch(accesskey, secret, host);
//Create an OpenSearchClient object and use the OpenSearch object as the constructor parameter
OpenSearchClient serviceClient = new OpenSearchClient(openSearch);
//Define a DocumentClient object to submit doc data in JSON format in a batch
DocumentClient documentClient = new DocumentClient(serviceClient);
try {
//Perform the push operation
OpenSearchResult osr = documentClient.push(docsJson, appName, tableName);
//To determine whether the data is pushed successfully, check two things: first, whether the push on the user side succeeds; second, whether error logs exist in the application console.
//Even if the push on the user side succeeds, processing may still fail on the application side. Such errors are recorded directly in the error logs of the application console, for example, a field content conversion failure.
if(osr.getResult().equalsIgnoreCase("true")){
System.out.println("No error occurred during the push on the user side!\nThe push request ID from getTraceInfo is as follows:"+osr.getTraceInfo().getRequestId());
}else{
System.out.println("An error occurred during the push on the user side!"+osr.getTraceInfo());
}
} catch (OpenSearchException e) {
e.printStackTrace();
} catch (OpenSearchClientException e) {
e.printStackTrace();
}
try {
Thread.sleep(1000);//Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
//-------------Query the documents pushed above-----------------
//Create a SearcherClient object and use the OpenSearchClient object as the constructor parameter
SearcherClient searcherClient = new SearcherClient(serviceClient);
//Define a Config object to set the parameters of the config clause, such as pagination or the format of returned data
Config config = new Config(Lists.newArrayList(appName));
config.setStart(0);
config.setHits(30);
//Set the return format to JSON. Currently, only the XML and JSON formats are supported. The fulljson format is not supported.
config.setSearchFormat(SearchFormat.JSON);
// Specify the application fields to return in the search results
config.setFetchFields(Lists.newArrayList("id", "name", "phone", "int_arr", "literal_arr", "float_arr", "cate_id"));
// Create a parameter object
SearchParams searchParams = new SearchParams(config);
// Set the query clause. To query multiple indexes in combination, merge them in a single setQuery call. Otherwise, if you call setQuery multiple times, later queries overwrite earlier ones.
searchParams.setQuery("id:'" + value1 + "'|'"+value2 +"'");
// Set the query filter condition
searchParams.setFilter("cate_id<=3");
// Set the sort condition
Sort sorter = new Sort();
sorter.addToSortFields(new SortField("id", Order.DECREASE)); //Sort by the id field in descending order
sorter.addToSortFields(new SortField("RANK", Order.INCREASE)); //If id values are the same, sort by RANK in ascending order
//Add the Sort object parameter
searchParams.setSort(sorter);
// Execute the query and return the results
SearchResult searchResult;
try {
searchResult = searcherClient.execute(searchParams);
String result = searchResult.getResult();
JSONObject obj = new JSONObject(result);
// Print the query results
System.out.println(obj.toString());
} catch (OpenSearchException e) {
e.printStackTrace();
} catch (OpenSearchClientException e) {
e.printStackTrace();
}
}
}When you push data, the data can contain only fields from the same table. You cannot push data across tables.