1
votes

This error that Dynamo throws is extremely vague but there is a way to narrow down the issue quickly. The code that throws this error can be found at https://github.com/aws/aws-sdk-java/blob/master/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/DynamoDBMapperTableModel.java

Which is currently the only google search result for "no HASH key for GSI" which is why I've been inspired to create this post.

1

1 Answers

3
votes

Here's the most important code from the DynamoDB Java Library:

for (final DynamoDBMapperFieldModel<T,Object> field : fields.values()) {
                for (final String indexName : field.globalSecondaryIndexNames(RANGE)) {
                    final GlobalSecondaryIndex gsi = map.get(indexName);
                    if (gsi == null) {
                        throw new DynamoDBMappingException(
                            targetType.getSimpleName() + "[" + field.name() + "]; no HASH key for GSI " + indexName
                        );
                    }
                    gsi.withKeySchema(new KeySchemaElement(field.name(), RANGE));
                }
}    

Notice the call to final GlobalSecondaryIndex gsi = map.get(indexName);. DynamoDB is attempting to use the name of the index that you've defined in your annotation to query a map containing values for that object and it comes up with null. A null is always the response from a java map when a value doesn't exist in the map but you've asked for it anyways.

This should clue us in. The indexName entry in the map of values has no mapping or no value associated with it. That must mean the indexName is wrong in either the table's declaration of the GlobalSecondaryIndex's index name or the annotation is wrong in the DynamoDBTable class where the GSI is annotated with DynamoDBIndexHashKey.

For me personally there was an extremely small discrepancy: userId-Index was defined in my CreateTable request but the field was annotated userId-index. Note the different in casing in Index.

So to sum up - if you're receiving this error - double, triple, and quadruple check all your annotations related to the index name.