Om Singh
Om Singh

Reputation: 41

AppSync mapping response from Lambda getting result from ElasticSearch

I am trying to invoke a lambda function from AppSync passing a search query. The lambda is calling elastic search which returns the result set.

I am able to map the result set to different fields in the graphQL Schama

$#set($result = {
   "statusCode": "${context.result.statusCode}",
   "headers": "${context.result.headers}",
   "isBase64Encoded": "${context.result.isBase64Encoded}",
   "body": "${context.result.body}"
})
$util.toJson($result)

In body get the search result set which I need to then parse and map them to a Schama.

I am unable to extract the response ${context.result.body.hits.hits} to iterate through the _source and set the search result set

Any suggestion and guidance will very helpful.

Upvotes: 0

Views: 1052

Answers (2)

T Caines
T Caines

Reputation: 253

AppSync has built in support for Amazon Elasticsearch resolvers. You can find some more information about that here!

However, if you wish to keep your current Lambda resolver you could try the following mapping template:

## Delcare an empty array
#set( $result = [] )

## Loop through results
#foreach($entry in $context.result.hits.hits)   

    ## Add each item to the result array
    $util.qr($result.add(
    {
        'id' : $entry.get("_source")['id'],
        'title' : $entry.get("_source")['fields']['title'],
        'plot' : $entry.get("_source")['fields']['plot'],
        'year' : $entry.get("_source")['fields']['year'],
        'url' : $entry.get("_source")['fields']['image_url']
    }))

#end

## Parse the result
$util.toJson($result)

Upvotes: 3

Om Singh
Om Singh

Reputation: 41

The issue was resolved by converting the context results body as below. Once this was done , I was able to iterate the resultSet

[
#set($result = $context.result)

## resultSet - parse back to JSON
#set($result.resultSet = $util.parseJson($context.result.body))

#foreach($entry in $result.resultSet.hits.hits)

    ## $velocityCount starts at 1 and increments with the #foreach loop **
    #if( $velocityCount > 1 ) , #end

    $util.toJson(
        {
        'id' : $entry.get("_source")['id'],
        'title' : $entry.get("_source")['fields']['title'],
        'plot' : $entry.get("_source")['fields']['plot'],
        'year' : $entry.get("_source")['fields']['year'],
        'url' : $entry.get("_source")['fields']['image_url']
        }
    )

#end
]

Upvotes: 1

Related Questions