amplify-cli icon indicating copy to clipboard operation
amplify-cli copied to clipboard

Transform @searchable directive generate wrong VTL response template

Open sakhmedbayev opened this issue 7 years ago • 43 comments

Describe the bug

  • graphql sort variable does not work on autogenerated VTL response template
  • the template also return null for the nextToken field

To Reproduce Steps to reproduce the behavior:

  1. Make new graphql type with @model and @searchable directive
  2. amplify push it
  3. Add several records to your DynamoDB
  4. check VTL response mapping template for the search query
#set( $items = [] )
#foreach( $entry in $context.result.hits.hits )
  #if( !$foreach.hasNext )
    #set( $nextToken = "$entry.sort.get(0)" )
  #end
  $util.qr($items.add($entry.get("_source")))
#end
$util.toJson({
  "items": $items,
  "total": $ctx.result.hits.total,
  "nextToken": $nextToken
})

this value "$entry.sort.get(0)" will return as a string for the nextToken field

  1. try to use sort variable on the graphql query
{
  "filter": {
    "cleanedContent": {
      "regexp": "someText.*"
    }
  },
  "sort": {
    "field": "myField",
    "direction": "desc"
  }
}

you will get this error:

{
  "data": {
    "searchBookEntitys": null
  },
  "errors": [
    {
      "path": [
        "searchBookEntitys"
      ],
      "data": null,
      "errorType": "Elasticsearch:UserIllegalArgumentException",
      "errorInfo": null,
      "locations": [
        {
          "line": 2,
          "column": 3,
          "sourceName": null
        }
      ],
      "message": "Elasticsearch responded with an error: Bad Request"
    }
  ]
}

Expected behavior nextToken and sort variable to functiion properly

Desktop (please complete the following information):

  • macOS
  • amplify cli version multienv.39

sakhmedbayev avatar Jan 31 '19 11:01 sakhmedbayev

Hello, I'm also getting the string "$entry.sort.get(0)" incorrectly returned as my nextToken. Is there any workaround I can use in my custom resolver to fix this in the meantime?

davidfarinha avatar Apr 24 '19 20:04 davidfarinha

The quotes need to be removed from around the nextToken

i.e.

"$entry.sort.get(0)"

Should be:

$entry.sort.get(0)

You could do a pull request for the fix, or use a custom template for the time being.

SteveHoggNZ avatar Apr 24 '19 21:04 SteveHoggNZ

This doesn't seem to work, there's no "sort" field in the Elasticsearch response (see below) so $entry.sort.get(0) in the response mapping always causes "nextToken" to be null.

{
    "errors": [],
    "mappingTemplateType": "Response Mapping",
    "path": "[searchUsers]",
    "context": {
        "arguments": {
            "filter": {
                "id": {
                    "ne": "cd82d03b-4d79-4fd4-bfea-b856cb86f3c7"
                }
            }
        },
        "result": {
            "took": 2,
            "timed_out": false,
            "_shards": {
                "total": 5,
                "successful": 5,
                "skipped": 0,
                "failed": 0
            },
            "hits": {
                "total": 30,
                "max_score": 1,
                "hits": [
                    {
                        "_index": "user",
                        "_type": "doc",
                        "_id": "bf37c7a7-00e7-4419-ba05-ffb7370c174a",
                        "_score": 1,
                        "_source": {
                            (user data etc)
                        }
                    },
                    (etc)
                ]
            }
        },
        "stash": {},
        "outErrors": []
    },
    "fieldInError": false
}

Apparently this is a known issue.

davidfarinha avatar Apr 24 '19 22:04 davidfarinha

Is there a workaround to get sort working for Elasticsearch entities while waiting for this fix?

brookslyrette avatar Jul 24 '19 11:07 brookslyrette

Closing this issue as the pr has been merged

SwaySway avatar Aug 13 '19 16:08 SwaySway

@SwaySway These changes seem to have broken sorting for a pretty standard search query for us. We had the below query running for more than a month with no issues, but updating various AWS libraries recently, the query broke.

My query is pretty simple:

query SearchApplications {
  searchApplications(
    limit: 999,
    sort: {
      field: createdAt,
      direction: desc
    },
    filter: {
      status: {eq:"NEW"}
    },
  ) {
    nextToken
    items {
      id
      name
      email
      createdAt
    }
  }
}

createdAt is a required AWSDateTime but having that field as the sort field I get this error:

{
  "data": {
    "searchApplications": null
  },
  "errors": [
    {
      "path": [
        "searchApplications"
      ],
      "data": null,
      "errorType": "Elasticsearch:UserIllegalArgumentException",
      "errorInfo": null,
      "locations": [
        {
          "line": 81,
          "column": 3,
          "sourceName": null
        }
      ],
      "message": "Elasticsearch responded with an error: Bad Request"
    }
  ]
}

Changing createdAt to another field fixes the problem, but I need my items listed by the creation date DESC.

houmark avatar Aug 18 '19 03:08 houmark

@SwaySway I'm still getting nextToken $entry.sort.get(0) - is that expected? Did this get merged yet? I am running latest amplify-cli and amplify-js.

houmark avatar Aug 27 '19 17:08 houmark

Hi @houmark in the resolver for elasticsearch the response is outputting nextToken in the form of a string (though it should get evaluated at runtime):

  • #set( $nextToken = "$entry.sort.get(0)" )

Can you send an email to [email protected] with your schema included? What field are you searching on? (aside from created at which is being addressed the merged pr #2090)

query SearchToDo {
  searchTodos(
    limit: 100
    sort: {
    field: id
    direction: desc
  }) {
    items {
      name
      createdAt
      description
    }
    nextToken
  }
}

SwaySway avatar Aug 29 '19 18:08 SwaySway

I can send that, but I did a console.log({nextToken}); of nextToken at runtime and it displays:

{nextToken: "$entry.sort.get(0)"}

To be honest, right now I am not sure if my dev is running on 1.12.0 or 2.0.0, considering the issues with the Console. I will return to this as soon as that is solved because this was buggy in 1.12.0 but should be fixed in 2.0.0 right?

houmark avatar Aug 29 '19 19:08 houmark

Whether the "$entry.sort.get(0)" has quotes on it shouldn't effect the variable itself. It seems that within the responses coming from elasticsearch it may not have sort specified in the response. I want to confirm if this is the case. Are you able to do a query on your dev env on a different field? Also if possible, edit the resolver in the console so the quotations are removed. If they are removed and the value returns null then this is the case.

SwaySway avatar Aug 29 '19 20:08 SwaySway

Thanks, I will get into this later tonight once I have the Console issue tested because this could be a mix of both. I also have a deadline that I need to meet today, and all these issues have delayed me so much.

houmark avatar Aug 29 '19 20:08 houmark

I was looking in the AppSync Console for the search resolver, but I cannot seem to find it. I have not done custom resolvers or modified any resolvers before, so I'm not very familiar with this part.

I entered Schema and on the right side I looked through the list, and while I found a few resolvers, I did not find the search specific one, and many places it will say "Attach" in the Resolver column.

Not sure how I can continue debugging on this part if I cannot find the resolver.

houmark avatar Aug 29 '19 23:08 houmark

It should in the API your working with under schema from there you can search for resolvers by entering query. The resolver datasource would be ElasticSearchDomain. Screenshot included below

You can also view your api in the aws console using the following command

amplify api console

image

SwaySway avatar Aug 30 '19 00:08 SwaySway

The resolver request template is viewable from there it would look something like

#set( $items = [] )
#foreach( $entry in $context.result.hits.hits )
  #if( !$foreach.hasNext )
    #set( $nextToken = "$entry.sort.get(0)" )
  #end
  $util.qr($items.add($entry.get("_source")))
#end
$util.toJson({
  "items": $items,
  "total": $ctx.result.hits.total,
  "nextToken": $nextToken
})

SwaySway avatar Aug 30 '19 00:08 SwaySway

Found it. The search in that interface is pretty useless. I search for my model name, and expect everything related to that model will show including the ElasticSearchDomain resolver. It did not. I searched for ElasticSearchDomain or just "elastic" and same result, nothing found. Searching "query" did find it though. That UI is also freezing up for close to one minute when loading the Schema the first time. Where should I report both of these?

My ElasticSearchDomain resolver response template is:

#set( $items = [] )
#foreach( $entry in $context.result.hits.hits )
  #if( !$foreach.hasNext )
    #set( $nextToken = "$entry.sort.get(0)" )
  #end
  $util.qr($items.add($entry.get("_source")))
#end
$util.toJson({
  "items": $items,
  "total": $ctx.result.hits.total,
  "nextToken": $nextToken
})

I wish I had found this resolver before I did the new push (related to the Console issue I have at this time), but I will continue testing once I have confirmed the Console can deploy and I have that solved with a forced API change and push from the CLI.

houmark avatar Aug 30 '19 00:08 houmark

The request resolver is viewable from there it would look something like

I think for less confusion you should refer to this as the "response template" in the ElasticSearchDomain resolver as there's also a "request template".

houmark avatar Aug 30 '19 00:08 houmark

I believe you can submit a report on the AppSync Forum.

If you remove the quotations (save the resolver) and run the query in the console (under Queries). Would it return null or a value?

SwaySway avatar Aug 30 '19 01:08 SwaySway

Result before changing the resolve response template:

After changing it:

The after should not be null as there are around 600 items and I was limiting to 10, so I should get a nextToken to be able to fetch more items.

So, what's next?

houmark avatar Aug 30 '19 01:08 houmark

Yes, here you go:

(I modified the name of the numberFields for privacy)

#set( $indexPath = "/application/doc/_search" )
#set( $numberFields = ["field1", "field2", "deleted"] )
{
  "version": "2017-02-28",
  "operation": "GET",
  "path": "$indexPath",
  "params": {
      "body":     {
                #if( $context.args.nextToken )"search_after": ["$context.args.nextToken"], #end
                "size": #if( $context.args.limit ) $context.args.limit #else 10 #end,
                "sort": #if( $context.args.sort )
  [#if( !$util.isNullOrEmpty($context.args.sort.field) && !$util.isNullOrEmpty($context.args.sort.direction) )
  {#if($numberFields.contains($context.args.sort.field))                                    
"$context.args.sort.field" #else "${context.args.sort.field}.keyword" #end : {
                                        "order": "$context.args.sort.direction"
                                    }
                                }
#end]
#else
  []
#end,
                "query": #if( $context.args.filter )
$util.transform.toElasticsearchQueryDSL($ctx.args.filter)
#else
{
      "match_all": {}
  }
#end
                }
  }
}

houmark avatar Aug 30 '19 01:08 houmark

Can you provide the query as well?

SwaySway avatar Aug 30 '19 01:08 SwaySway