How to Instantiate OpenSearch Serverless Java Client

I already wrote a post on how to connect to OpenSearch cluster (both AWS-hosted & non-AWS). Recently AWS launched OpenSearch Serverless & it is in GA phase now. So I thought of writing a quick post to show how to connect to serverless version of OpenSearch. It requires a little bit of change in the Java client instantiation code. For this, we would need at least opensearch-java 2.2.0 or later. AWS OpenSearch cluster has service name “es”. But OpenSearch serverless service name is “aoss”. In new code, we need to pass signing service name to differenciate between already existing OpenSearch service & newly launched OpenSearch serverless. The AWS signed request will be generated accordingly based on the service name.

Assuming you are using Gradle for building the project, you will need following dependencies in build.gradle file:

    api 'org.opensearch.client:opensearch-java:2.2.0'
    implementation 'software.amazon.awssdk:http-client-spi:2.17.275'
    implementation 'software.amazon.awssdk:apache-client:2.17.275'
    implementation 'software.amazon.awssdk:regions:2.17.275'
    implementation 'software.amazon.awssdk:auth:2.17.275'

Below you can find fully working code to instantiate an OpenSearch Java client to connect to the OpenSearch Serverless collection.

import org.opensearch.client.opensearch.OpenSearchClient;
import org.opensearch.client.transport.aws.AwsSdk2Transport;
import org.opensearch.client.transport.aws.AwsSdk2TransportOptions;

import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.regions.Region;

public class OpenSearchClientFactory {

	private static OpenSearchClient openSearchClient;

	static {
		openSearchClient = createAWSOpenSearchClientInstance();
	}

	private static OpenSearchClient createAWSOpenSearchClientInstance() {
		SdkHttpClient httpClient = ApacheHttpClient.builder().build();
		return new OpenSearchClient(
				new AwsSdk2Transport(httpClient, "vpc-test-w3spot-gffyfyut6hjhjgjg.us-west-2.aoss.amazonaws.com",
						"aoss", Region.of("us-west-2"), AwsSdk2TransportOptions.builder().build()));
	}

	public static OpenSearchClient getInstance() {
		return openSearchClient;
	}

}

Leave a Comment