An example of using levelDB
Target:
- In this post, I will explain how to write a simple program that can utilize the API that provide by levelDB
Some facts:
- LevelDB is a database that embedded into the process rathen running independently just as Postgresql or MongoDB.
- The data that is stored in levelDB is straightforward, that simply pairs of KV, Key and Value.
- LeveDB support a set of API so users can call, and there not too many of commands that we can call here.
Lets see with source tree:
Here we have a single source code that include the header leveldb/db.h
Source code
Content of the file is as follow
- We open the database with leveldb::DB::Open()
- We write/put data to the database, in this case a pair of Key|Value -- name|Henry
- We read/get the data from the database to see if the data is written to database properly
- We delete the data
- And finally, we read the data again and see the confirmation that the data is deleted
Build the program
To build the program, we type the command below
Note:
-
To successfully build the program, the system need to installed leveldb. Otherwise, the compiling will fail due to lack of library that need for the build.
-
To install levelDB, refer to Google/leveldb
Execute
After compile the program, in your source will have the compiled/binary file as beloy:
Now, lets run the program to see the result:
root@Henry-WIN:leveldb_practice# ./leveldb_example
=== Write K:[name] V:[HenryLe] to DB
=== Read K:[name] V:[HenryLe] from DB
=== Failed to read kv after deletion: [name] Status: NotFound:
The data the content Key|Value name|Henry is written to database. Then read from database, then deleted, and after deleted, we read the data and receive warning that the data is not found in the database. All work as expected.
This short tutorial is a note so that I can refer later to when I need it.
Source code can be found HERE