简体   繁体   中英

AWS appsync GraphQL aggregate counts

Instead of all the items in return I want the number of items only in appsync query.Look at the below example:

My schema:

type Post @model {
  id: ID!
  title: String!
  comments: [Comment] @hasMany
}

type Comment @model {
  id: ID!
  content: String!
  post: Post @belongsTo
}

Here in getPost query we can get all the comments list related to post if we won't provide pagination limit. But I don't want the list of comments, I want the total number of comments. When user will click on the comment icon I will fetch comments in separate query.

Now my question is how to get that comments is there any in-built method avaliable or I have to do it manually ( how )?

DynamoDB doesn't have a count function in the API, and therefore, it is also not available in the VTL of AppSync. The concept of DynamoDB is to have scalable LOOKUP queries that are hitting a small number of records, and if you need to SCAN many records, it is possible however, not efficient.

The best way to achieve the counters you are after is to prepare them for a LOOKUP. On every addComment event, you can increase the comment counter, and on every deleteComment event, you can decrease that counter.

Here is an example of the CLI command to increase a counter , which you can include in your resolver VTL code .

aws dynamodb update-item \
    --table-name Posts \
    --key '{"Id":{"N":"789"}}' \
    --update-expression "ADD CommentCounter :q" \
    --expression-attribute-values '{":q": {"N": "1"}}' \
    --return-values ALL_NEW

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM