nirvair
nirvair

Reputation: 4180

Query key condition not supported with GSI DynamoDB

Creation of table:

final ArrayList<KeySchemaElement> indexKeySchema = new ArrayList<KeySchemaElement>();
indexKeySchema.add(new KeySchemaElement().withAttributeName("expiresOn").withKeyType(KeyType.HASH));
indexKeySchema.add(new KeySchemaElement().withAttributeName("createdAt").withKeyType(KeyType.RANGE));

GlobalSecondaryIndex index = new GlobalSecondaryIndex()
        .withIndexName("expiresOnIndex")
        .withProvisionedThroughput(new ProvisionedThroughput()
                .withWriteCapacityUnits((long) 10)
                .withReadCapacityUnits((long) 1))
        .withProjection(new Projection().withProjectionType(ProjectionType.ALL));
index.setKeySchema(indexKeySchema);

dynamoDbclient.createTable(new CreateTableRequest()
        .withProvisionedThroughput(new ProvisionedThroughput(1000L, 1000L))
        .withTableName(tableName)
        .withAttributeDefinitions(Arrays.asList(new AttributeDefinition(hashColumn, ScalarAttributeType.S),
                new AttributeDefinition("expiresOn", ScalarAttributeType.S),
                new AttributeDefinition("createdAt", ScalarAttributeType.S)))
        .withKeySchema(Arrays.asList(new KeySchemaElement(hashColumn, KeyType.HASH)))
        .withGlobalSecondaryIndexes(index));

And this is the query:

final Map<String, AttributeValue> eav = new HashMap<String, AttributeValue>();
eav.put(":val1", new AttributeValue().withS(startTime.toString()));
eav.put(":val2", new AttributeValue().withS(endTime.toString()));

final DynamoDBQueryExpression<MyEntity> queryExpression =
        new DynamoDBQueryExpression<MyEntity>()
        .withKeyConditionExpression("expiresOn BETWEEN :val1 AND :val2")
        .withExpressionAttributeValues(eav)
        .withConsistentRead(false)
        .withIndexName("expiresOnIndex");

return dynamoDBMapper.query(MyEntity.class, queryExpression);

Always getting Query key condition not supported. I'm not sure what's wrong here. I read couple of stackoverflow answers which suggested to use GSI, but doesn't work for me.

Upvotes: 0

Views: 336

Answers (1)

Charles
Charles

Reputation: 23783

When you Query a DDB table or index,

The BETWEEN key condition can only be used on the Sort (aka Range) Key, the hash key must be an always be an EQUAL condition...

Upvotes: 1

Related Questions