Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query a Dynamo DB having a GSI with only hashKeys using DynamoDBMapper

Tags:

I am very new to Dynamo DB and may be this is very trivial question, but i went through the documents of Dynamo DB and stack overflow questions but i couldnt find a single link which tells how to query DDB for GSI which has only hash key and there are no range key specified for the same.

I get the exception Illegal query expression: No hash key condition is found in the query.

like image 232
Ankit Banerjee Avatar asked May 26 '15 11:05

Ankit Banerjee


People also ask

Does a GSI need a sort key?

Every global secondary index must have a partition key, and can have an optional sort key. The index key schema can be different from the base table schema.

Can DynamoDB have multiple hash keys?

Querying is a very powerful operation in DynamoDB. It allows you to select multiple Items that have the same partition ("HASH") key but different sort ("RANGE") keys.

What is a DynamoDBMapper?

The DynamoDBMapper class is the entry point to Amazon DynamoDB. It provides access to a DynamoDB endpoint and enables you to access your data in various tables. It also enables you to perform various create, read, update, and delete (CRUD) operations on items, and run queries and scans against tables.


1 Answers

On your DynamoDB annotated model object, you should use @DynamoDBIndexHashKey(globalSecondaryIndexName = "gsiIndexName) to signify that it is a hash key for the GSI:

@DynamoDBTable(tableName = "myTable") public class MyTable {     ...      @DynamoDBIndexHashKey(globalSecondaryIndexName = "myGsi")     public String getGsiHk() {         return gsiHk;     }      ... } 

And then use the query method on the DynamoDBMapper:

final MyTable gsiKeyObj = new MyTable(); gsiKeyObj.setGsiHk("myGsiHkValue"); final DynamoDBQueryExpression<MyTable> queryExpression =      new DynamoDBQueryExpression<>(); queryExpression.setHashKeyValues(gsiKeyObj); queryExpression.setIndexName("myGsi"); queryExpression.setConsistentRead(false);   // cannot use consistent read on GSI final PaginatedQueryList<MyTable> results =      mapper.query(MyTable.class, queryExpression); 
like image 134
mkobit Avatar answered Sep 21 '22 03:09

mkobit