2
votes

When querying in DynamoDB (with a hash-and-range primary key), is it essential to provide the hash key or can you simply search by providing the range key? This is my use case: I have a table which has the following "schema": Category#Domain (String) - Hash key GroupType#GroupName (String) - Range key Some other string fields like UpdatedOn, UpdatedBy etc.

I have to frequently do there two things: 1. Given a Category#Domain, get all the matching items. 2. Given a GroupType#GroupName, get all the matching items.

Both the operations are fairly frequent so I do not want to use scan. Is there an effective way to do this in DynamoDB? Is there a better way to design the schema (more tables, secondary indexes etc.)? Any suggestion would be helpful. Someone suggested using Global Secondary Index but with that my question is will I be able to make the range key of my main table as the hash key of my gsi? I know all the "keys" are copied over automatically but this would help me only if I can make GroupType#GroupName as the hash key in the gsi so as to be able to query on it. Also, is there any special way to handle gsi from DynamoDBMapper? Will I need to create a new POJO?

1

1 Answers

3
votes

Is there an effective way to do this in DynamoDB?

It sounds like you are looking for Global Secondary Indexes (GSI). You have your table which has:

  • Hash key: Category#Domain
  • Range key: GroupType#GroupName
  • Other attributes

And based off this table it sounds like you want to have a GSI:

  • Hash key: GroupType#GroupName
  • Range key: depends on design (not necessary in GSI)
  • Other attributes that are wanted

will I be able to make the range key of my main table as the hash key of my gsi?

Yes, the example on the developer guide does just this.

Since the table's primary key attributes are always projected into an index, the Category#Domain attribute is also present. You can also select which attributes you want to project onto this index. GSIs also do not need to have a range key:

Also, is there any special way to handle gsi from DynamoDBMapper? Will I need to create a new POJO?

DynamoDBMapper provides the ability to do this. I'm not sure which AWS SDK version it was released with (maybe 1.7?). You should not need to create a new POJO, but if you are trying to deal with existing tables you will not be able to add GSIs to them right now (support for online indexing was announced last month). You can use the annotation DynamoDBIndexHashKey and DynamoDBIndexRangeKey annotations in your POJO in the same way you use them currently.

Update 2015/1/27: Online Indexing is now available