Search code examples
amazon-dynamodbamazon-dynamodb-index

Use the same DynamoDB attribute as both HASH and RANGE key


I have a DynamoDB that is indexed by a single numerical key. I'd like to be able to both retrieve items having a specific value of the key, and find its maximum value by querying and requesting a single item in inverse sorting order. When I try to define 2 indices as in the excerpt below on the same key I get the error 'Two keys can not have the same name'.

"KeySchema": [
  {
    "AttributeName": "logs",
    "KeyType": "HASH"
  },
  {
    "AttributeName": "logs",
    "KeyType": "RANGE"
  }
]

Solution

  • You could define your key schema with only the hash key, no range key

    "KeySchema": [
      {
        "AttributeName": "logs",
        "KeyType": "HASH"
      }
    ]
    

    To request an item using a specific 'logs' value, use GetItem.

    To find the highest value you would need to perform a Scan. This would be a poor way to find the highest value as it would mean evaluating every item in your table. It would be slow and expensive.

    You might want to reassess your approach. If you are simply trying to create unique IDs, this is not the right approach for DynamoDB. What you should do is:

    • Generate a long UUID
    • Do a GetItem to verify that the UUID is available. This is very cheap and fast in DynamoDB
    • Use the UUID