In AWS DynamoDB query, is it possible to query a string as a number?
In my case I have a myDate field which contains is a number of seconds from 1970 in a string format. It is also a sort key on a global secondary index.
I need to return all records from DynamoDb where myDate is between 2 query parameters: fromDate and toDate. The problem is that myDate is a string, so I cant easily compare those 3 values. At the moment I have a query that looks like that:
var params = {
TableName: "MyTable",
IndexName: "GSI",
KeyConditionExpression: "primaryKey = :primaryKey AND myDate BETWEEN :fromDate AND :toDate",
ExpressionAttributeValues: {
":primaryKey ": {"N": "1"},
":fromDate": {"S": "1550637900"},
":toDate": {"S": "1550639400"}
}
}
However that is not going to work correctly, because of string comparison. For example "2" > "10". So is there a way to do a number comparison for myDate?
Amazon specifically mentions that its not possible directly:
BETWEEN : Greater than or equal to the first value, and less than or equal to the second value.
AttributeValueList must contain two AttributeValue elements of the same type, either String, Number, or Binary (not a set type). A target attribute matches if the target value is greater than, or equal to, the first element and less than, or equal to, the second element. If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {"S":"6"} does not compare to {"N":"6"}. Also, {"N":"6"} does not compare to {"NS":["6", "2", "1"]}
But maybe there is a better way I am not seeing?
No, you can't.
And as you've found it, it won't be a problem for a while. How long depends...if you're dealing with a 32bit Unix/Linux Epoch value...then those run out in 2038
Otherwise, you don't have to worry till 2286, when you'd hit 10000000000 (11 digits)
In the future, consider storing dates/times as ISO formatted strings, "2019-07-29T12:37:54Z"
or "20190729T123754Z"
That will take care of you through the year 9999.