Given a DynamoDB table as follows:
- partition key:
tid
, type string
- sort key:
timestamp
, type string
You can query on:
- tid = 5
- tid = 5, timestamp between 2018-12-21T09:00:00Z and 2018-12-21T15:00:00Z
Try it out using the awscli, for example to query all items with tid=5
:
aws dynamodb query \
--table-name mytable \
--key-condition-expression "tid = :tid" \
--expression-attribute-values '{":tid":{"S":"5"}}'
To query all items for tid=5
and timestamp between 09:00 and 15:00 on 2015-12-21
:
aws dynamodb query \
--table-name mytable \
--key-condition-expression "tid = :tid AND #ts BETWEEN :ts1 AND :ts2" \
--expression-attribute-values '{":tid":{"S":"5"}, ":ts1":{"S":"2015-12-21T09:00:00Z"}, ":ts2":{"S":"2015-12-21T15:00:00Z"}}' \
--expression-attribute-names '{"#ts":"timestamp"}'
Note: because timestamp
is a reserved keyword in DynamoDB, you have to escape it using the expression attribute names.
You could also create the timestamp
attribute as a number and then store epoch times, if you prefer.
To query all items with timestamp between 09:00 and 15:00 on 2015-12-21
, regardless of tid
, cannot be done with the same partition/sort key schema. You would need to add a Global Secondary Index something like this:
- GSI partition key:
yyyymmdd
, type string
- GSI sort key:
timestamp
, type string
Now you can query for items with a given timestamp range, as long as they're on the same day (they have the same YYYYMMDD, which might be a reasonable restriction). Or you could go to YYYYMM as the partition key allowing a wider timestamp range. At this point you really need to understand the use cases for queries to decide if YYYYMMDD (restricting queries to a single day) is right. See How to query DynamoDB by date with no obvious hash key for more on this idea.