Now, we can create the Lambda function in our CloudFormation file:
"UserRegistrationCloudSearchLambda": { "Type": "AWS::Lambda::Function", "Properties": { "Handler": "com.serverlessbook.lambda.userregistration.search.Handler", "Runtime": "java8", "Timeout": "300", "MemorySize": "1024", "Description": "User Registration Search Lambda", "Role": { "Fn::GetAtt": [ "LambdaExecutionRole", "Arn" ] }, "Code": { "S3Bucket": { "Ref": "DeploymentBucket" }, "S3Key": { "Fn::Sub": "artifacts/lambda-userregistration-cloudsearch/
${ProjectVersion}/${DeploymentTime}.jar" } }, "Environment": { "Variables": { "CloudSearchDomain": { "Fn::Sub": "doc-${CloudSearchDomain}.${AWS::Region}.
cloudsearch.amazonaws.com" } } } }
}
Note that we prepended doc- to construct the document endpoint of CloudSearch and inject it into our Lambda function as an environment variable named CloudSearchDomain.
To integrate this function with SNS, we have to give permission to SNS to invoke the function, and we do this exactly how we did with the previous function:
"UserRegistrationCloudSearchLambdaPermission": { "Type": "AWS::Lambda::Permission", "Properties": { "Action": "lambda:InvokeFunction", "FunctionName": { "Ref": "UserRegistrationCloudSearchLambda" }, "Principal": "sns.amazonaws.com","SourceArn": { "Fn::Sub": "arn:aws:sns:${AWS::Region}:${AWS::AccountId}:*" } } }
Finally, we will add the Lambda to our SNS topic as a subscriber:
{ "Endpoint": { "Fn::GetAtt": [ "UserRegistrationCloudSearchLambda", "Arn" ] }, "Protocol": "lambda" }
We're done. Now, we can deploy our stack, and all the new users who registered to our application will be also indexed in CloudSearch.
You can now register a new user using the user registration endpoint, executing the same command from previous chapters. Once you register the user, you can query your endpoint at /search path with the q parameter and a result should appear.
Alternatively, you can use the CloudSearch dashboard to execute a query against the search domain and ensure that data flow is working without any problem.