23

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.

Ankit Banerjee
  • 279
  • 1
  • 2
  • 6
  • Just to be clear the Global Secondary Index is formed of only HashKey and no range Key, how do i generate a query for it using DynamoDBMapper? – Ankit Banerjee May 26 '15 at 12:03

1 Answers1

46

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);
BamaPookie
  • 2,560
  • 1
  • 16
  • 21
mkobit
  • 43,979
  • 12
  • 156
  • 150
  • Hi..what about @DynamoDBIndexRangeKey. It gives me same problem with IndexRangeKey. – Jignesh Ansodariya Jun 29 '16 at 06:48
  • Hi @mkobit: the code you sent is working perfectly but when i add queryExpression.withLimit(10); it gives this error: Unable to evaluate the expression Method threw 'android.os.NetworkOnMainThreadException' exception. i am using RxAndroid for the network ops – Shaw Dec 20 '17 at 07:07
  • @Shaw I'm not familiar with Android specifics, but I'm guessing that you can't do blocking calls on the main UI thread - see https://stackoverflow.com/questions/6343166/how-do-i-fix-android-os-networkonmainthreadexception – mkobit Dec 20 '17 at 14:45
  • I have found the solution. If you want to set limit on the DynamoDBQueryExpression object, then use mapper.queryPage() method, not mapper.query() Its a weird error on Amazon SDK that if we call mapper.query() method with limit parameter set, it gives NetworkOnMainThreadException :D :D – Shaw Dec 26 '17 at 08:49
  • hello everyone i am able to connect to dynamo db successfully but my result set contains no data...thats strange what else i can look for to resolve . – divyanayan awasthi May 29 '19 at 19:23