Skip to content
v2.273.0

OpenSearchDataSource ​

An Appsync datasource backed by OpenSearch.

Example ​

ts
import * as opensearch from 'aws-cdk-lib/aws-opensearchservice';

const user = new iam.User(this, 'User');
const domain = new opensearch.Domain(this, 'Domain', {
  version: opensearch.EngineVersion.OPENSEARCH_2_3,
  removalPolicy: RemovalPolicy.DESTROY,
  fineGrainedAccessControl: { masterUserArn: user.userArn },
  encryptionAtRest: { enabled: true },
  nodeToNodeEncryption: true,
  enforceHttps: true,
});

declare const api: appsync.GraphqlApi;
const ds = api.addOpenSearchDataSource('ds', domain);

ds.createResolver('QueryGetTestsResolver', {
  typeName: 'Query',
  fieldName: 'getTests',
  requestMappingTemplate: appsync.MappingTemplate.fromString(JSON.stringify({
    version: '2017-02-28',
    operation: 'GET',
    path: '/id/post/_search',
    params: {
      headers: {},
      queryString: {},
      body: { from: 0, size: 50 },
    },
  })),
  responseMappingTemplate: appsync.MappingTemplate.fromString(`[
    #foreach($entry in $context.result.hits.hits)
    #if( $velocityCount > 1 ) , #end
    $utils.toJson($entry.get("_source"))
    #end
  ]`),
});
python
import aws_cdk.aws_opensearchservice as opensearch

# api: appsync.GraphqlApi


user = iam.User(self, "User")
domain = opensearch.Domain(self, "Domain",
    version=opensearch.EngineVersion.OPENSEARCH_2_3,
    removal_policy=RemovalPolicy.DESTROY,
    fine_grained_access_control=opensearch.AdvancedSecurityOptions(master_user_arn=user.user_arn),
    encryption_at_rest=opensearch.EncryptionAtRestOptions(enabled=True),
    node_to_node_encryption=True,
    enforce_https=True
)
ds = api.add_open_search_data_source("ds", domain)

ds.create_resolver("QueryGetTestsResolver",
    type_name="Query",
    field_name="getTests",
    request_mapping_template=appsync.MappingTemplate.from_string(JSON.stringify({
        "version": "2017-02-28",
        "operation": "GET",
        "path": "/id/post/_search",
        "params": {
            "headers": {},
            "query_string": {},
            "body": {"from": 0, "size": 50}
        }
    })),
    response_mapping_template=appsync.MappingTemplate.from_string("""[
            #foreach($entry in $context.result.hits.hits)
            #if( $velocityCount > 1 ) , #end
            $utils.toJson($entry.get("_source"))
            #end
          ]""")
)
java
import software.amazon.awscdk.services.opensearchservice.*;

GraphqlApi api;


User user = new User(this, "User");
Domain domain = Domain.Builder.create(this, "Domain")
        .version(EngineVersion.OPENSEARCH_2_3)
        .removalPolicy(RemovalPolicy.DESTROY)
        .fineGrainedAccessControl(AdvancedSecurityOptions.builder().masterUserArn(user.getUserArn()).build())
        .encryptionAtRest(EncryptionAtRestOptions.builder().enabled(true).build())
        .nodeToNodeEncryption(true)
        .enforceHttps(true)
        .build();
OpenSearchDataSource ds = api.addOpenSearchDataSource("ds", domain);

ds.createResolver("QueryGetTestsResolver", BaseResolverProps.builder()
        .typeName("Query")
        .fieldName("getTests")
        .requestMappingTemplate(MappingTemplate.fromString(JSON.stringify(Map.of(
                "version", "2017-02-28",
                "operation", "GET",
                "path", "/id/post/_search",
                "params", Map.of(
                        "headers", Map.of(),
                        "queryString", Map.of(),
                        "body", Map.of("from", 0, "size", 50))))))
        .responseMappingTemplate(MappingTemplate.fromString("[\n    #foreach($entry in $context.result.hits.hits)\n    #if( $velocityCount > 1 ) , #end\n    $utils.toJson($entry.get(\"_source\"))\n    #end\n  ]"))
        .build());
csharp
// Install: dotnet add package Amazon.CDK.Lib
using Amazon.CDK.AWS.OpenSearchService;

GraphqlApi api;


var user = new User(this, "User");
var domain = new Domain(this, "Domain", new DomainProps {
    Version = EngineVersion.OPENSEARCH_2_3,
    RemovalPolicy = RemovalPolicy.DESTROY,
    FineGrainedAccessControl = new AdvancedSecurityOptions { MasterUserArn = user.UserArn },
    EncryptionAtRest = new EncryptionAtRestOptions { Enabled = true },
    NodeToNodeEncryption = true,
    EnforceHttps = true
});
var ds = api.AddOpenSearchDataSource("ds", domain);

ds.CreateResolver("QueryGetTestsResolver", new BaseResolverProps {
    TypeName = "Query",
    FieldName = "getTests",
    RequestMappingTemplate = MappingTemplate.FromString(JSON.Stringify(new Dictionary<string, object> {
        { "version", "2017-02-28" },
        { "operation", "GET" },
        { "path", "/id/post/_search" },
        { "params", new Struct {
            Headers = new Struct { },
            QueryString = new Struct { },
            Body = new Struct { From = 0, Size = 50 }
        } }
    })),
    ResponseMappingTemplate = MappingTemplate.FromString(@"[
        #foreach($entry in $context.result.hits.hits)
        #if( $velocityCount > 1 ) , #end
        $utils.toJson($entry.get(""_source""))
        #end
      ]")
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
import "github.com/aws/aws-cdk-go/awscdk"

var api GraphqlApi


user := iam.NewUser(this, jsii.String("User"))
domain := opensearch.NewDomain(this, jsii.String("Domain"), &DomainProps{
	Version: opensearch.EngineVersion_OPENSEARCH_2_3(),
	RemovalPolicy: awscdk.RemovalPolicy_DESTROY,
	FineGrainedAccessControl: &AdvancedSecurityOptions{
		MasterUserArn: user.userArn,
	},
	EncryptionAtRest: &EncryptionAtRestOptions{
		Enabled: jsii.Boolean(true),
	},
	NodeToNodeEncryption: jsii.Boolean(true),
	EnforceHttps: jsii.Boolean(true),
})
ds := api.AddOpenSearchDataSource(jsii.String("ds"), domain)

ds.CreateResolver(jsii.String("QueryGetTestsResolver"), &BaseResolverProps{
	TypeName: jsii.String("Query"),
	FieldName: jsii.String("getTests"),
	RequestMappingTemplate: appsync.MappingTemplate_FromString(jSON.stringify(map[string]interface{}{
		"version": jsii.String("2017-02-28"),
		"operation": jsii.String("GET"),
		"path": jsii.String("/id/post/_search"),
		"params": map[string]map[string]interface{}{
			"headers": map[string]interface{}{
			},
			"queryString": map[string]interface{}{
			},
			"body": map[string]*f64{
				"from": jsii.Number(0),
				"size": jsii.Number(50),
			},
		},
	})),
	ResponseMappingTemplate: appsync.MappingTemplate_*FromString(jsii.String(`[
	    #foreach($entry in $context.result.hits.hits)
	    #if( $velocityCount > 1 ) , #end
	    $utils.toJson($entry.get("_source"))
	    #end
	  ]`)),
})

Initializer ​

ts
new OpenSearchDataSource(scope: Construct, id: string, props: OpenSearchDataSourceProps)
python
OpenSearchDataSource(scope: Construct, id: str, props: OpenSearchDataSourceProps)
java
new OpenSearchDataSource(Construct scope, String id, OpenSearchDataSourceProps props)
csharp
new OpenSearchDataSource(Construct scope, string id, OpenSearchDataSourceProps props)
go
NewOpenSearchDataSource(Scope Construct, Id *string, Props OpenSearchDataSourceProps)

Construct Props ​

The API to attach this data source to.
descriptionstringdescriptionstrdescriptionStringDescriptionstringDescription*string= None#
the description of the data source.
domainIDomaindomainIDomaindomainIDomainDomainIDomainDomainIDomainrequired#
The OpenSearch domain containing the endpoint for the data source.
metricsConfigDataSourceMetricsConfigmetrics_configDataSourceMetricsConfigmetricsConfigDataSourceMetricsConfigMetricsConfigDataSourceMetricsConfigMetricsConfigDataSourceMetricsConfig= no metrics configuration#
Whether to enable enhanced metrics of the data source Value will be ignored, if `enhancedMetricsConfig.dataSourceLevelMetricsBehavior` on AppSync GraphqlApi construct is set to `FULL_REQUEST_DATA_SOURCE_METRICS`.
namestringnamestrnameStringNamestringName*string= id of data source#
The name of the data source.
serviceRoleIRoleservice_roleIRoleserviceRoleIRoleServiceRoleIRoleServiceRoleIRole= Create a new role#
The IAM service role to be assumed by AppSync to interact with the data source.

Properties ​

the underlying CFN data source resource.
grantPrincipalIPrincipalgrant_principalIPrincipalgrantPrincipalIPrincipalGrantPrincipalIPrincipalGrantPrincipalIPrincipalrequired#
the principal of the data source to be IGrantable.
namestringnamestrnameStringNamestringName*stringrequired#
the name of the data source.
nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.

Methods ​

createFunction(id: string, props: BaseAppsyncFunctionProps): AppsyncFunctiondef create_function(self, id: str, props: BaseAppsyncFunctionProps) -> AppsyncFunctionpublic AppsyncFunction createFunction(String id, BaseAppsyncFunctionProps props)public AppsyncFunction CreateFunction(string id, BaseAppsyncFunctionProps props)func CreateFunction(Id *string, Props BaseAppsyncFunctionProps) AppsyncFunction#
creates a new appsync function for this datasource and API using the given properties.
createResolver(id: string, props: BaseResolverProps): Resolverdef create_resolver(self, id: str, props: BaseResolverProps) -> Resolverpublic Resolver createResolver(String id, BaseResolverProps props)public Resolver CreateResolver(string id, BaseResolverProps props)func CreateResolver(Id *string, Props BaseResolverProps) Resolver#
creates a new resolver for this datasource and API using the given properties.
isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.

1 parameter · returns

Parameters

  • mixinsmixinsmixinsmixinsMixins — The mixins to apply.

Returns: This construct for chaining