The main idea of a key-value store is fairly simple. It allows you to associate some arbitrary data (the value) with a name (the key), such as a string or number. In fact, you could use any binary data as a key.

For example, you might store information about a person by associating the name of each entry (the key) with the entry’s content (the value).

Key Value
first_name Joe
last_name McLearny
address 123 Cloud Dr
city Dataville
state CA
zip_code 90210

Initially, we’ll be using JSON for the keys and values, and typically we’ll store multiple pieces of information in each value. This collection of data in the value can also be referred to as a document, as in a document store.

# Key (JSON)
{ "type": "person", "id": 1 }

# Value (JSON)
  "first_name": "Joe",
  "last_name": "McLearny",
  "address": "123 Cloud Dr",
  "city": "Dataville",
  "state": "CA",
  "zip_code": "90210"

JSON.parse() and JSON.stringify()

You’ll be seeing a lot of JSON.parse() and JSON.stringify() to convert between strings and JSON objects. While most databases store data in some kind of compact binary format, we’re going to start out with JSON to make it easier to inspect the data stored in our database system.

Client API interface

The client API interface for our key-value store will start out pretty simple. We’ll have methods to store (put), retrieve (get), and remove (delete) key-value pairs.

Method Description
put(key, value) Stores value associated with key, overwriting if it already exists.
get(key) Fetches the last value stored for key, or returns undefined if the key is not set or has been deleted.
delete(key) Removes the value for key.

Time to write some code! Let’s make a quick and simple in-memory implementation for the client API interface so we have something to start with.