Google LevelDB with C


LevelDB is a fast key-value storage library written at Google that provides an ordered mapping from string keys to string values.The library was written in C++ and developers have developed bindings for many languages such as C# and node.js. The db is using google's snappy compression library to decrease the on-disk size of LevelDB stores with minimal sacrifice of speed. In this post we'll talk about using LevelDB in an Ubuntu environment with C.

First install snappy dependencies using following command.

sudo apt-get install libsnappy-dev

Get the latest copy of  levelDB from GitHub.

git clone https://github.com/google/leveldb.git

Execute the following set of commands to make and install the library on your Ubuntu environment.(the libleveldb.* is in the out-static now).

cd leveldb/
make
sudo scp -r out-static/lib* out-shared/lib* /usr/local/lib/
cd include/
sudo scp -r leveldb /usr/local/include/
sudo ldconfig
man scp - r
sudo ldconfig
man scp -r
If the commands didn't work follow these additional steps.
ls -l out-static/lib* out-shared/lib*
rm -f /usr/local/lib/libleveldb*
scp -r out-static/lib* out-shared/lib* /usr/local/lib/
ls -l /usr/local/lib/libleveldb*

We'll write a simple C programme to understand the functionality of the levelDB.

#include <leveldb/c.h>
#include <stdio.h>

int main() {
    leveldb_t *db;
    leveldb_options_t *options;
    leveldb_readoptions_t *roptions;
    leveldb_writeoptions_t *woptions;
    char *err = NULL;
    char *read;
    size_t read_len;

    options = leveldb_options_create();
    leveldb_options_set_create_if_missing(options, 1);
    db = leveldb_open(options, "levelDB", &err);
}

Compile and run and you'll see a file named "levelDB" is created in your work space.This file holds all your data entries and you can use this database anywhere in your future implementations.Let's add some data to the database.

 woptions = leveldb_writeoptions_create();
 leveldb_put(db, woptions, "Josh", 4, "Male", 4, &err);

4 and 4 fields are the lengths of key(Josh) and value(Male) fields.

roptions = leveldb_readoptions_create();
read = leveldb_get(db, roptions, "Josh", 3, &read_len, &err);
printf("%s\n",read);
 
You'll get Male as the output.

Comments