Alibaba Cloud OpenSearch is a full-text search service that is built on the Apsara distributed system by Alibaba Cloud. OpenSearch enables developers to search, sort, filter, and aggregate various types of data, such as text, number, and time data. This tutorial walks you through the process and procedure of using OpenSearch and provides a few usage notes.
// Add the following dependencies to the pom.xml file of your project to import OpenSearch SDK.
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-opensearch</artifactId>
<version>2020-09-28</version>
</dependency>
//Create an OpenSearch object.
//Use your AccessKey ID and AccessKey secret to create an OpenSearch object.
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.opensearch.model.v20171225.SearchRequest;
import com.aliyuncs.opensearch.model.v20171225.SearchResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.opensearch.OpenSearchClient;
import com.aliyuncs.opensearch.model.v20171225.SearchResponse.ResultItem;
public class OpenSearchDemo {
public static void main(String[] args) {
String accessKeyId = "<your-access-key-id>";
String accessKeySecret = "<your-access-key-secret>";
String endpoint = "<your-endpoint>";
String appName = "<your-app-name>";
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
DefaultAcsClient client = new DefaultAcsClient(profile);
OpenSearchClient searchClient = new OpenSearchClient(endpoint, appName, accessKeyId, accessKeySecret, client);
}
}
//Create a query request.
//Create a SearchRequest object and specify the search parameters such as the keyword, the number of search results, and the start and end positions of search results.
SearchRequest searchRequest = new SearchRequest();
searchRequest.setAppName(appName);
searchRequest.setQuery("query");
searchRequest.setStart(0);
searchRequest.setHits(10);
//Send the query request and obtain the response to the request.
try {
SearchResponse searchResponse = searchClient.search(searchRequest);
for (ResultItem item : searchResponse.getResult().getItems()) {
//Handle the search results.
}
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
The current account is an Alibaba Cloud account or a Resource Access Management (RAM) user that is granted the AliyunRAMFullAccess permission. For more information about how to grant permissions to a RAM user, see Grant permissions to the RAM user.
Assume that a mobile app developer plans to store the user data of an app in Alibaba Cloud Object Storage Service (OSS). The data of each user must be isolated to prevent users from obtaining the data of other users. In this case, you can use Security Token Service (STS) to authorize users to access their own data in your OSS buckets.
The following list describes how to use STS to authorize a user to access OSS:
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"oss:PutObject"
],
"Resource": [
"acs:oss:*:*:examplebucket/exampledir",
"acs:oss:*:*:examplebucket/exampledir/*"
]
}
]
}
You can use STS SDKs to obtain temporary access credentials.
The following code provides an example on how to use STS SDK for Java to obtain temporary access credentials that have the simple upload (oss:PutObject) permission.
Parameters | Example | Description |
---|---|---|
endpoint | sts.cn-hangzhou.aliyuncs.com | The endpoint of STS. You can access STS over the Internet or a virtual private cloud (VPC). For more information about STS endpoints, see Endpoints. |
accessKeyId | LTAI5tJHezdULrXcczCW**** | The AccessKey ID that is generated for the RAM user in Step 1. |
accessKeySecret | CTkGhP9xUpMR5IWj4WRZTQ2SR**** | The AccessKey secret that is generated for the RAM user in Step 1. |
roleArn | acs:ram::137918634****:role/ramosstest | The role ARN that is obtained in Step 3. |
roleSessionName | SessionTest | The name of the role session. You can specify this parameter based on your business requirements. In most cases, you can set this parameter to the identity of the user who calls API operations. The name must be 2 to 64 characters in length and can contain letters, digits, periods (.), at signs (@), hyphens (-), and underscores (_). |
policy | The policy that specifies the permissions of the returned STS token. This allows you to implement more fine-grained access control. * If you specify this parameter, the permissions that are granted to the STS token are the intersection of the RAM role permissions and the permissions that are specified in this parameter. * If you do not specify this parameter, the STS token has all permissions of the RAM role. For information about how to configure the elements in a policy, see Overview. If you want to obtain temporary access credentials that can be used to perform specific operations, such as multipart upload and append upload, configure the Action element in the policy based on the operations. For more information about the Action element in a policy of OSS, see Action element in RAM policies for OSS. |
|
durationSeconds | 3600 | The validity period of the temporary access credentials. Unit: seconds. Minimum value: 900. The maximum value is based on the maximum session duration of the current role. The maximum session duration for the current role ranges from 3600 seconds to 43200 seconds. The default value of the maximum session duration for the current role is 3600 seconds. For more information, see Specify the maximum session duration for a RAM role. In time-consuming scenarios or when large objects need to be uploaded, we recommend that you specify a long validity period for temporary access credentials. This way, you do not need to frequently call STS to obtain temporary access credentials. |
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
public class StsServiceSample {
public static void main(String[] args) {
// Specify the endpoint of STS. Example: sts.cn-hangzhou.aliyuncs.com.
String endpoint = "<sts-endpoint>";
// Specify the AccessKey pair that is generated for the RAM user in Step 1.
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
// Specify the role ARN that is obtained in Step 3.
String roleArn = "<yourRoleArn>";
// Specify a custom role session name to distinguish different tokens. Example: SessionTest.
String roleSessionName = "<yourRoleSessionName>";
// The following policy allows users to use temporary access credentials to upload objects only to the bucket named examplebucket.
// The permissions that are granted to the temporary access credentials are the intersection of the role permissions that are configured in Step 4 and the permissions that are defined in the RAM policy. Users can use the temporary access credentials to upload objects only to the exampledir directory in the examplebucket bucket.
// If the policy is empty, the user is granted all permissions of the role.
String policy = "{\n" +
" \"Version\": \"1\", \n" +
" \"Statement\": [\n" +
" {\n" +
" \"Action\": [\n" +
" \"oss:PutObject\"\n" +
" ], \n" +
" \"Resource\": [\n" +
" \"acs:oss:*:*:examplebucket/*\" \n" +
" ], \n" +
" \"Effect\": \"Allow\"\n" +
" }\n" +
" ]\n" +
"}";
// Set the validity period of the temporary access credentials to 3600 seconds.
Long durationSeconds = 3600L;
try {
// regionId specifies the region ID of the RAM user. For example, if the RAM user is located in the China (Hangzhou) region, set regionId to cn-hangzhou. You can also retain the default setting, which is an empty string ("").
String regionId = "";
// Add the endpoint. You can specify this parameter by using STS SDK for Java V3.12.0 or later.
DefaultProfile.addEndpoint(regionId, "Sts", endpoint);
// Add the endpoint. You can specify this parameter by using STS SDK for Java that is earlier than V3.12.0.
// DefaultProfile.addEndpoint("",regionId, "Sts", endpoint);
// Create a default profile.
IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
// Use the profile to create a client.
DefaultAcsClient client = new DefaultAcsClient(profile);
final AssumeRoleRequest request = new AssumeRoleRequest();
// You can specify this parameter by using STS SDK for Java V3.12.0 or later.
request.setSysMethod(MethodType.POST);
// You can specify this parameter by using STS SDK for Java that is earlier than V3.12.0.
//request.setMethod(MethodType.POST);
request.setRoleArn(roleArn);
request.setRoleSessionName(roleSessionName);
request.setPolicy(policy);
request.setDurationSeconds(durationSeconds);
final AssumeRoleResponse response = client.getAcsResponse(request);
System.out.println("Expiration: " + response.getCredentials().getExpiration());
System.out.println("Access Key Id: " + response.getCredentials().getAccessKeyId());
System.out.println("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
System.out.println("Security Token: " + response.getCredentials().getSecurityToken());
System.out.println("RequestId: " + response.getRequestId());
} catch (ClientException e) {
System.out.println("Failed:");
System.out.println("Error code: " + e.getErrCode());
System.out.println("Error message: " + e.getErrMsg());
System.out.println("RequestId: " + e.getRequestId());
}
}
}
The following code provides an example on how to use OSS SDK for Java V3.12.0 to upload a file named exampletest.txt from D:\localpath to a directory named exampledir in a bucket named examplebucket:
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectRequest;
import java.io.File;
public class Upload {
public static void main(String[] args) {
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
String endpoint = "oss-cn-hangzhou.aliyuncs.com";
// Specify the temporary AccessKey ID and AccessKey secret that are included in the temporary access credentials obtained from STS in Step 5. The temporary AccessKey ID and AccessKey secret are not the AccessKey ID and AccessKey secret of an Alibaba Cloud account.
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// Specify the security token that is included in the temporary access credentials obtained from STS in Step 5.
String securityToken = "yourSecurityToken";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
// Upload a local file named exampletest.txt to the directory named exampledir in the bucket named examplebucket.
PutObjectRequest putObjectRequest = new PutObjectRequest("examplebucket", "exampledir/exampletest.txt", new File("D:\localpath\exampletest.txt"));
// ObjectMetadata metadata = new ObjectMetadata();
// Specify the storage class of the object when you upload the file.
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// Specify the ACL of the object when you upload the file.
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);
// Upload the local file.
ossClient.putObject(putObjectRequest);
// Shut down the OSSClient instance.
ossClient.shutdown();
}
}
Was this helpful?
Was this helpful?