1

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.

3
  • Can you first state what is your tables partition and sort key. Also share the values you have to make the request. I know what you need to do but I need more info to explain it more clearly to you. Commented Jan 23, 2023 at 15:43
  • I edited the question and provided the table details. Can you please help now? Commented Jan 23, 2023 at 16:13
  • my answer below should work for you Commented Jan 23, 2023 at 16:49

2 Answers 2

3

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.