I am using the AWS Dynamo DB library for Scala - com.amazonaws.services.dynamodbv2.
Earlier I had a table with a primary key and I was using GetItem to get specific item from it like so :
val item = Try(Option(ddb.getItem(new GetItemRequest().withTableName(table).withKey(Collections.singletonMap(keyField, new AttributeValue(key)))).getItem).map(_.get(valField).getS))
But now I need to start using a new sort key (timestamp of the created date) on top.
This way I can have multiple identical primary keys with different timestamp sort keys. This is meant so I will be able to get the closest item to my current sort timestamp property.
I think I need KeyConditionExpression
where my input timestamp is bigger or equal to the new sort key,
and I saw a property ScanIndexForward
which can be set to true in combination with
limit = 1
so I will get only one item and it will be the closest(?)
And this should get me the desired item I hope, but I am not so sure how to approach this in Scala and with the AWS library.
CodePudding user response:
In case anyone interested, this is what worked out for me -
val queryRequest = new QueryRequest().withTableName(table)
.withKeyConditions(createKeyConditionsMap(keyField, keyValue, sortField, sortValue))
.withScanIndexForward(false)
.withLimit(1)
val x = ddb.query(queryRequest).getItems()
def createKeyConditionsMap(keyField: String, keyValue: String, sortField: String, sortValue: String) = {
Map(keyField -> new Condition().withComparisonOperator("EQ").withAttributeValueList(new AttributeValue(keyValue)),
sortField -> new Condition().withComparisonOperator("LE").withAttributeValueList(new AttributeValue().withN(sortValue))).asJava
}