Document key generatation

A document key (also called a document identifier) is a unique string associated with a document which allows to differ the document from the other ones. There are two limitations for document identifiers:

  • Maximum length allowed is 1023 unicode characters
  • Cannot contain \ character

RavenDB server supports three document key generation strategies. Their descriptions below refer purely to server side behavior. Knowledge of them is important mostly when you save a document by using REST API, however RavenDB client also takes advantage of them, so it's good to know how it all works under the hood.

Autogenerated GUID

When a document key is not specified, Raven will generate a globally unique identifier (Guid) for the stored document. This function can be used when you don't care for the document key, for example when saving log entries, or when the user will never be exposed to the document key.

Semantic key

The problem with Guids is that they are not human friendly. They are very hard to read, compare etc. The much better option is to have ids that contain useful information about the documents. You know best what you need and how your keys should look like, so you can decide what id the document will have before saving it. Then RavenDB will use the assigned key. It is most often used when you save documents which already have native id, such as users; then you can use keys like users/ayende.

Identity key

If you want to have keys that contain some useful info about the document but you also need to have consecutive ids, then the identity keys is an option for you. There you can allow RavenDB to take care of creating your keys sequentially, by adding the incremented number value at the end of the key. In order to use this option you need to follow the convention: the key you specify during save ends with a slash (/). Raven will automatically start tracking identity numbers for the prefix if it doesn't exist and append the current identity value to the key. Let's see the example:

SAVE 'users/' -> will assign 'users/1'
SAVE 'users/' -> will assign 'users/2'

Raven stores the relation between the prefix and the current identity value internally, so it is able to deal with the scenario in which you mix the identity keys usage with the manual key generation:

SAVE 'users/1'
SAVE 'users/' -> will assign 'users/2'

This approach is recommended for most scenarios, since it produces keys that are readable for humans.