I am new to DyanmoDB. I am creating partition key and sort key when pushing data into DynamoDb but when i want to retrieve the data i have the partition key but not the complete sort key. I know the beginning of the sort key but not the complete key.
table.query(QueryEnhancedRequest.builder().queryConditional(QueryConditional.keyEqualTo(Key.builder().partitionValue("KEY#" id).build())).build())
Below are the tables partition and sort key:
private static final String TEMPLATE = "%s#%s";
@DynamoDbPartitionKey
@Override
public String getPk() {
return String.format(TEMPLATE, "KEY", getId());
}
@DynamoDbSortKey
@Override
public String getSk() {
return String.format(TEMPLATE, "KEY_SORT", getName());
}
I used what i provided above but its showing this error:
The provided key element does not match the schema (Service: DynamoDb, Status Code: 400, Request ID: response id)
After looking into the issue i found out that key should be the combination of partition and sort key. But the issue is i don't know the complete sort key for the second request.
CodePudding user response:
If you only know the beginning of the sort key, you can use BEGINS_WITH
query.
aws dynamodb query \
--table-name TABLE \
--key-condition-expression "Id = :id and begins_with(Key, :key)" \
--expression-attribute-values '{":id":{"S":"1"}, ":key":{"S":"KEY-BEGINNING"}}'
You need to provide the primary key and the beginning of the sort key for this query.
See Key condition expressions for query
CodePudding user response:
You need to use QueryConditional
with sortBeginsWith()
:
For example, imagine you have the following information
partition key pk
= "key#23456"
sort key sk
begins with "abcd"
you are unsure of the remainder of the sort key:
QueryConditional condition = QueryConditional.sortBeginsWith(
Key.builder()
.partitionValue("key#23456")
.sortValue("abcd")
.build()
);
QueryEnhancedRequest request = QueryEnhancedRequest.builder()
.queryConditional(condition)
.build();
table.query(request);