文件 AWS 開發套件範例 GitHub 儲存庫中有更多可用的 AWS SDK 範例。
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
使用 AWS SDKs OpenSearch Service 程式碼範例
下列程式碼範例示範如何搭配 AWS 軟體開發套件 (SDK) 使用 Amazon OpenSearch Service。
基本概念是程式碼範例,這些範例說明如何在服務內執行基本操作。
Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數,但您可以在其相關情境中查看內容中的動作。
開始使用
下列程式碼範例說明如何開始使用 OpenSearch Service。
- Java
-
- SDK for Java 2.x
-
import software.amazon.awssdk.services.opensearch.OpenSearchAsyncClient;
import software.amazon.awssdk.services.opensearch.model.ListVersionsRequest;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* Before running this Java V2 code example, set up your development
* environment, including your credentials.
*
* For more information, see the following documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
*/
public class HelloOpenSearch {
public static void main(String[] args) {
try {
CompletableFuture<Void> future = listVersionsAsync();
future.join();
System.out.println("Versions listed successfully.");
} catch (RuntimeException e) {
System.err.println("Error occurred while listing versions: " + e.getMessage());
}
}
private static OpenSearchAsyncClient getAsyncClient() {
return OpenSearchAsyncClient.builder().build();
}
public static CompletableFuture<Void> listVersionsAsync() {
ListVersionsRequest request = ListVersionsRequest.builder()
.maxResults(10)
.build();
return getAsyncClient().listVersions(request).thenAccept(response -> {
List<String> versionList = response.versions();
for (String version : versionList) {
System.out.println("Version info: " + version);
}
}).exceptionally(ex -> {
// Handle the exception, or propagate it as a RuntimeException
throw new RuntimeException("Failed to list versions", ex);
});
}
}