Search code examples
pythonamazon-web-servicesamazon-dynamodbboto

DynamoDB : The provided key element does not match the schema


Is there a way to get an item depending on a field that is not the hashkey?

Example

My Table Users: id (HashKey), name, email

And I want to retrieve the user having email as '[email protected]'

How this can be done?

I try this with boto:

user = users.get_item(email='[email protected]')

I get the following error:

'The provided key element does not match the schema'

Solution

  • To query on fields which are not the hash key you need to use a Global Secondary Index (GSI). Take a look at this AWS Post for more details on GSI's.

    UPDATE Feb 2015: It is now possible to add a GSI to an existing table. See the Amazon Docs for more details.

    Sadly you cannot add a GSI to an existing DynamoDB table so you'll need to create a new table and port your data if this is something you really need to query on.

    From the DynamoDB FAQ:

    Q: How do I create a global secondary index for a DynamoDB table?

    All GSIs associated with a table must be specified at table creation time. At this time, it is not possible to add a GSI after the table has been created. For detailed steps on creating a Table and its indexes, see here. You can create a maximum of 5 global secondary indexes per table.

    If you do not want to port your data you could consider creating a second DynamoDB table with the email as a hash key and the hash of the parent record to use as a lookup into your main data table but as you can imagine this isn't exactly an optimal solution and it comes with its own headaches of keeping it in synch with your master table.