Storing Objects in Key/Value Stores – Serialized vs Separate Values

database-designnosql

I'm playing around with Go and BadgerDB, which is an embedded disk based (not in-memory like Redis) key/value store. There's just so little information about how to use key/values stores in general.

My main question basically is: Does it make more sense to store one entity/object/item per key? Like this:

user:0 = {"email":"johndoe@example.com","password":"some-hash"}

Or to store every field on its own? Like this:

user:0:email = "johndoe@example.com"
user:0:password = "some-hash"

Does anyone have some experience with this? Does one technique have some performance advantages over the other? Or does one have management issues I don't think about yet? Or is there something else to consider?

Best Answer

It really depends. You've identified one of the primary flaws with a key->value design (structure).

Your former example is more like a document-oriented database, which is kind of an extra implementation on top of a key->value store. Using something like JSON for your document is one approach. Some document-oriented DB's will optimize/index that for you.

Your latter example is more of a traditional key->value approach.


To answer your question more specifically, one problem with storing a JSON string/object as your value would be that every time you want to access part of that value, you generally have to parse (and possibly decompress) the whole thing. The problem with the key->value design is a lack of structure, everything is almost flat. How are you going to represent a class/object this way, and what if you have a web of complicated classes/objects, etc.?

https://en.wikipedia.org/wiki/NoSQL#Types_and_examples