Can I use RavenDB to generate unique IDs for child objects within a document?

138 views
Skip to first unread message

Chris Fellows

unread,
Aug 10, 2017, 8:33:24 AM8/10/17
to RavenDB - 2nd generation document database
I have a document of type A and one property is a collection of classes of type B. B has an integer Id property and the only restriction is that it has to be unique within that Raven database. The Raven client is a Web API web application (C#) that runs on a single physical server. The server could be dealing with multiple requests simultaneously and so there could be multiple threads all trying to get a new ID.

In Raven then is it possible to generate a unique value for the B.Id property? In reality then I will get a new ID for each B instance in the collection.

The way that I had considered to do it is as follows:
  • Store an IDInfo document in Raven with a LastValue (int) property to store the last generated B.ID value.
  • Have a generic ID generator class that would have a function GetNewIDs<T>(int numberOfIds) that could provide N new B.ID values using the IDInfo document. It would load the document, increment LastValue, call IDocumentSession.SaveChanges and then return a collection of IDs.
  • Ensure that IDs are not duplicated by serializing access to GetNewIDs using a machine wide mutex. This obviously has issues if the web app is running on multiple machines simultaneously. E.g. A Dev running the Web API source code also.
Is this the best way to do it? Can it be done within a transaction?



Idan Haim

unread,
Aug 10, 2017, 8:51:37 AM8/10/17
to RavenDB - 2nd generation document database
Hi Chris,
In RavenDB we do something quite similar to what you want
you can read about Hilo algoritm

hope it helps.


Tal Weiss

unread,
Aug 10, 2017, 9:50:47 AM8/10/17
to RavenDB - 2nd generation document database
You can use asnycKeyGenerator

var hilo = new AsyncHiLoKeyGenerator("MyNestedObjectName", 1);
var nextId = await hilo.NextIdAsync(store.AsyncDatabaseCommands);

--
You received this message because you are subscribed to the Google Groups "RavenDB - 2nd generation document database" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ravendb+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--

Hibernating Rhinos Ltd  cid:image001.png@01CF95E2.8ED1B7D0

Tal Weiss l Core Team Developer Mobile:+972-54-802-4849

Office: +972-4-622-7811 l Fax: +972-153-4-622-7811l Skype: talweiss1982

RavenDB paving the way to "Data Made Simplehttp://ravendb.net/ 

Reply all
Reply to author
Forward
0 new messages