2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AWS AppSyncでElasticsearchから検索結果とtotal件数を取得するresponse mapping template.

Posted at

AWS AppSyncでElasticsearchを利用していると検索結果だけでなく、合計件数も取得したくなる場合があります。
AppSyncでは、response mapping templateの定義を調整することで実現できます。

検索結果とあわせて合計件数を取得するよう定義したresponse mapping templateは、以下。

{
  #set($total = $context.result.hits.total)
  #set($list = [])
  #if($total > 0)
    #foreach($entry in $context.result.hits.hits)
       $util.qr($list.add($entry.get('_source')))
    #end
    "list" : $util.toJson($list),
    "total" : "$total"
  #end
}
templateの説明

Elasticsearchでの検索結果が $context.result に格納されているので、
そこから total と 該当データをlistとして取得し、まとめてjson objectsで返します。

  • AppSyncで戻されるjsonのイメージ

{
  "list": [],
  "total": 0
}

total以外にも max_socre, took等もあわせて取得したい場合も同じように調整することで対応できます。

AppSyncのresponse mapping templateを作成する時は、どのようなjsonを返すのか をイメージしながら考えると、定義しやすいです。

参考

https://docs.aws.amazon.com/ja_jp/appsync/latest/devguide/resolver-mapping-template-reference-elasticsearch.html
https://docs.aws.amazon.com/ja_jp/appsync/latest/devguide/resolver-util-reference.html

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?