laahaa
laahaa

Reputation: 337

Is using json as sort key/partition key value good practice in DynamoDB?

Trying to define a schema for a DynamoDB table. More than two values decide a row.

A potential solution to put these key values is to have the sort key contain more than one value. As it's specified here.

Inspired by this approach, I'm thinking instead of using simple delimiter to concatenate values together, using JSON or any other string representation of objects(e.g.: String translated by Jackson) as the value of the sort key should be able to achieve similar goal and easy to convert.

However, my concern is by doing so - adding the length of the sort key - will it decrease the performance of DynamoDB? Is it a fine to use complicated string as the sort key?

Upvotes: 5

Views: 1538

Answers (1)

Tyler Ham
Tyler Ham

Reputation: 406

TL;DR: For your Sort Key, you can use any string (within the byte limits) that distinguishes your records within the primary key. But if you are clever about it, you can make better use of it for sorting and filtering.


There are limits to the key lengths:

  • Partition Key: 1 to 2048 bytes
  • Sort Key: 1 to 1024 bytes

I am not aware of any significant performance differences based on the length of your primary and sort keys. I'm sure that ensuring performance is part of the reason for AWS to set these particular limits.

Technically, you should be fine to use any string as your key, including JSON. However, depending on how you intend to query your table, you may want to consider a more clever arrangement for your Sort Key.

For example, if your sort key contains First and Last names, you might end up with JSON like these:

{"LastName":"Doe","FirstName":"John"}
{"FirstName":"Jane","LastName":"Doe"}

JSON alone doesn't care about the ordering of the name fields, so if you don't put additional constraints on your JSON, you might make it difficult to query all records with LastName "Doe".

The documentation you linked hints at an example of a pattern you might follow for your sort key:

LASTNAME#Doe#FIRSTNAME#John
LASTNAME#Doe#FIRSTNAME#Jane

Now you can easily query for all records with last name Doe with the startsWith condition "LASTNAME#Doe#FIRSTNAME#". Your records will also naturally be sorted by Last Name, First Name.

Rather than having to parse out that string when you want to find a record's first and last names, you could just duplicate the content in the record by adding separate fields for "FirstName" and "LastName" for convenience.

So your full record might look something like this:

{
  "PK":"some-primary-key",
  "SK":"LASTNAME#Doe#FIRSTNAME#John",
  "FirstName":"John",
  "LastName":"Doe"
}

Upvotes: 2

Related Questions