Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define sorting key in serverless.yaml

I am new to serverless, AWS and lambda function.
I want to know how to define a sorting key into serverless.yaml file and how we can sort data ASC or DEC order when we fetch the data from DynamoDB table?

I also want to know that suppose I have user table fields like

ID(Primary key)
Fullname(String)
Email(String)
City(String)
State(String)
PhoneNumber(String)

I want to sort in ASC or DEC order on Fullname and email column. So, as per my understanding, I need to define Fullname and email column as sorting key.

Here is my serverless.yaml file

resources:
Resources:
UserDynamoDbTable:
  Type: 'AWS::DynamoDB::Table'
  DeletionPolicy: Retain
  Properties:
    AttributeDefinitions:
      -
        AttributeName: id
        AttributeType: S
    KeySchema:
      -
        AttributeName: id
        KeyType: HASH
    ProvisionedThroughput:
      ReadCapacityUnits: 1
      WriteCapacityUnits: 1
    TableName: 'user'

So, how can i define multiple sorting keys(Here is Fullname and email) in a table?

In above .yaml file how can i define Fullname and email as sorting key?

Please help me here. Thanks in advance

like image 878
Akib Deraiya Avatar asked Oct 21 '25 11:10

Akib Deraiya


1 Answers

Example defining the primary sort key in your serverless.yml file:

Is this example I added a timestamp sort key to my table.

This key needs to be defined under AttributeDefinitions and KeySchema.

resources:
  Resources:
    MyTable:
      Type: 'AWS::DynamoDB::Table'
      DeletionPolicy: Retain
      Properties:
        TableName: your_table_name
        AttributeDefinitions:
          -
            AttributeName: id
            AttributeType: S
          -
            AttributeName: timestamp
            AttributeType: N
        KeySchema:
          -
            AttributeName: id
            KeyType: HASH
          -
            AttributeName: timestamp
            KeyType: RANGE

I looked into the definition and it follows Cloud Formations docs.

AttributeDefinitions - https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-keyschema.html

KeySchema - https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_AttributeDefinition.html

like image 187
Richard Avatar answered Oct 24 '25 04:10

Richard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!