SlideShare a Scribd company logo
1 of 17
Aniruddha Chakrabarti
Associate Vice President and Chief Architect, Digital Practice, Mphasis
ani.c@outlook.com | Linkedin.com/in/aniruddhac | slideshare.net/aniruddha.chakrabarti | Twitter - anchakra
LevelDB Embedded Key Value Store
Quick Cheat sheet
Agenda
• What is LevelDB
• Why LevelDB was created
• LevelDB libraries and bindings
• LevelDB operations using Node
• Write data (put)
• Read data (get)
• Remove data (del)
• Batch Operations (batch)
• Iterating data (ReadStream)
• Storing and Retrieving JSON data
What is LevelDB
• LevelDB is a key value store, it stores data in disk. Highly optimized for fast read
write (specially writes - benchmark)
• Stores keys and values in arbitrary byte arrays, and data is sorted by key.
• LevelDB is typically used as embedded database (runs in the same process as
your code), but can be networked (by adding protocols such as http, tcp to your
process)
• LevelDB is not a key value database server like Redis or memcached. It’s a
database library similar to SQLite or Oracle Berkeley DB.
• Supported on Linux, Windows, OSX
• Has drivers and bindings for C++, Node, Python etc.
LevelDB is a light-weight, single-purpose library for persistence
with bindings to many platforms.
http://leveldb.org/
What is LevelDB
• Written by Google fellows Jeffrey Dean and Sanjay Ghemawat (authors of
MapReduce And BigTable)
• Inspired by BigTable - same general design as the BigTable tablet stack, but not
sharing any of the code
• Developed in early 2011
• Chrome IndexDB feature (HTML5 API) is built on top of LevelDB
• Similar storage libraries include Oracle Berkeley DB, SQLite, Kyoto Cabinet,
RocksDB etc.
LevelDB is a light-weight, single-purpose library for persistence
with bindings to many platforms.
http://leveldb.org/
Performance Benchmark
LevelDB outperforms both SQLite3 and TreeDB in sequential and random write operations and
sequential read operations. Kyoto Cabinet has the fastest random read operations
http://leveldb.googlecode.com/svn/trunk/doc/benchmark.html
LevelDB library and bindings
• LevelDown - Low-level Node.js LevelDB binding
• LevelUp – High level Node.js-style LevelDB wrapper. LevelUP aims to expose the
features of LevelDB in a Node.js-friendly way
• Rather than installing LevelDB and LevelUp separately you can install it as a
whole – npm install level
• We would be using LevelUp Node.js LevelDB wrapper for all our examples
• All operations in LevelUp are asynchronous although they don't necessarily
require a callback if you don't need to know when the operation was performed.
Installing LevelDB Node Bindings
Installation
• Install LevelUp Node Bindings (library) using npm (Node Package Manager) -
npm install level or
npm install level -- save (to update the dependency in project.json)
(LevelUp Node Bindings Location - https://github.com/Level/levelup)
Referencing the Node Library in code
• Reference the LevelUp Node library
var level = require('level');
• Create a db object by calling level() function passing the path where the data files would be stored.
db object contains all the methods required for interacting with LevelDB. Here the data files would
be stored in a subfolder called db relative to node file
var db = level('./db');
Write Data (put)
• Inserts/writes data into the store. Both the key and value can be arbitrary data objects.
• The Node API is asynchronous – put accepts key, value and a callback. Once the operation is
completed (success or error) the callback is called.
• If error occurs then the error object is passed as argument to the callback. The callback argument is
optional - if you don't provide the callback argument and an error occurs then the error is thrown, so
it’s better to provide the error argument.
var level = require('level');
var db = level('./db');
var key = "city", value = "Bangalore";
db.put(key, value, function(error){
if (error != null){
console.log(error);
}
else {
console.log('data saved successfully to disk');
}
});
Read Data (get)
• Reads/retrieves data from the store – the key for which data needs to be retrieved need to be
specified.
• Similar to get, put also works asynchronously. It accepts key and a callback. Once the operation is
completed (success or error) the callback is called, which accepts the value retrieved as parameter.
• If the key doesn't exist in the store then the callback will receive an error as its first argument. A not
found error object will be of type 'NotFoundError'
var key = "city", another_key = "student";
db.get(key, function(error, city){
console.log(city); // displays Bangalore
});
db.get(another_key, function(error, value){
if (error == null){
console.log(value);
}
else{
console.log(error.type + " - " + error.message);
} // displays NotFoundError - Key not found in database [student]
});
Remove Data (del)
• Removes data from the store permanently.
var key = "city";
db.del(key, function(error){
if (error != null){
console.log(error);
}
else {
console.log('data deleted successfully');
}
});
db.get(key, function(error, city){
console.log(city); // displays undefined
});
Batch Operations
• Batch operations could be used for very fast bulk-write operations
(both put and delete).
• Supports an array form and a chained form (similar to Fluent API)
• Array form
• db.batch(array, error callback)
• array argument should contain a list of operations to be executed sequentially, although as a
whole they are performed as an atomic operation inside LevelDB.
• Each operation is contained in an object having the following properties: type, key, value, where
the type is either 'put' or 'del'
• If key and value are defined but type is not, it will default to 'put'.
• Chained form
• batch(), when called with no arguments returns a Batch object which can be used to build, and
eventually commit, an atomic LevelDB batch operation.
• Depending on how it's used, it is possible to obtain greater performance when using the
chained form of batch() over the array form.
batch (array form)
var ops = [ // All operations of the batch are listed in an array
{type:'put', key:'city1', value:'Bangalore'}, // type of operation, key & value
{type:'put', key:'city2', value:'Kolkata'},
{type:'put', key:'city3', value:'Chennai'},
{type:'del', key:'city'},
]
db.batch(ops, function (error){
if (error != null){
console.log(error);
}
else {
console.log('batch operation successful');
}
})
batch (chained form)
• First line of code returns a Batch object which is then used to build all operations one by one
• Once it’s built, it’s eventually gets committed through write, which is an atomic LevelDB batch
operation.
db.batch() // returns a Batch object which is used to chain all operations
.del("city")
.put("city1","Bangalore")
.put("city2","Kolkata")
.put("city3","Chennai")
.write(function(){ // committing the batch operation
console.log('batch operation successful');
});
Iteration and ReadStream
• Get a ReadStream of the full database by calling the createReadStream() method – the returned
stream is a complete Node.js-style Readable Stream. data object have key and value property.
var stream = db.createReadStream()
stream.on('data', function (data) {
console.log('key=', data.key + ",value=" + data.value);
});
• Use the gt, lt and limit options to control the range of keys that are streamed.
var stream = db.createReadStream({limit:2})
KeyStream and ValueStream
• A KeyStream is a ReadStream where the 'data' events are simply the keys from the database – use
createKeyStream() method to get a KeyStream
• A ValueStream is a ReadStream where the 'data' events are simply the values from the database –
use createValueStream() method to get a ValueStream
Iterating through all keys
var keyStream = db.createKeyStream()
keyStream.on('data', function (data) {
console.log('key = ', data)
})
Iterating through all values
var valueStream = db.createValueStream()
valueStream.on('data', function (data) {
console.log('value = ', data)
})
Storing JSON objects
• JSON objects could be stored as value, apart from simple strings, numbers etc.
• To store JSON objects, set the valueEncoding options parameter to json while constructing the
db object.
• Multiple level of nested objects could be stored as value
var db = level('./dbJson', { valueEncoding : 'json' });
var employee = { name : "XYZ", age : 45, designation : "VP" };
db.put('employee', employee, function(error){
db.get('employee', function(error, employee){
console.log(employee.name); // Aniruddha
console.log(employee.age); // 45
console.log(employee.designation); // VP
});
});
Storing JSON objects (complex)
var db = level('./dbJson', { valueEncoding : 'json' });
var employee = { name : "XYZ", age : 45, designation : "VP" };
var employee = {
name : "XYZ",
age : 45,
designation : "VP",
skills : ["NoSQL","Management","Languages","Oracle"], // Array
address : { streetAddress:"123 M G Road", city: "Bangalore", country: "IN" } // Object
};
db.put('employee', employee, function(error){
db.get('employee', function(error, employee){
console.log(employee.name); // XYZ
console.log(employee.skills[0]); // NoSQL
console.log(employee.address.streetAddress + " - " + employee.address.city);
// 123 M G Road - Bangalore
});
});

More Related Content

What's hot

Key-Value-Stores -- The Key to Scaling?
Key-Value-Stores -- The Key to Scaling?Key-Value-Stores -- The Key to Scaling?
Key-Value-Stores -- The Key to Scaling?
Tim Lossen
 
Presto - Hadoop Conference Japan 2014
Presto - Hadoop Conference Japan 2014Presto - Hadoop Conference Japan 2014
Presto - Hadoop Conference Japan 2014
Sadayuki Furuhashi
 

What's hot (20)

ApacheCon09: Avro
ApacheCon09: AvroApacheCon09: Avro
ApacheCon09: Avro
 
Migrating to postgresql
Migrating to postgresqlMigrating to postgresql
Migrating to postgresql
 
SQL for Elasticsearch
SQL for ElasticsearchSQL for Elasticsearch
SQL for Elasticsearch
 
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, HerokuPostgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
 
Inside sql server in memory oltp sql sat nyc 2017
Inside sql server in memory oltp sql sat nyc 2017Inside sql server in memory oltp sql sat nyc 2017
Inside sql server in memory oltp sql sat nyc 2017
 
3 apache-avro
3 apache-avro3 apache-avro
3 apache-avro
 
8a. How To Setup HBase with Docker
8a. How To Setup HBase with Docker8a. How To Setup HBase with Docker
8a. How To Setup HBase with Docker
 
Key-Value-Stores -- The Key to Scaling?
Key-Value-Stores -- The Key to Scaling?Key-Value-Stores -- The Key to Scaling?
Key-Value-Stores -- The Key to Scaling?
 
3 avro hug-2010-07-21
3 avro hug-2010-07-213 avro hug-2010-07-21
3 avro hug-2010-07-21
 
Scylla Summit 2018: Introducing ValuStor, A Memcached Alternative Made to Run...
Scylla Summit 2018: Introducing ValuStor, A Memcached Alternative Made to Run...Scylla Summit 2018: Introducing ValuStor, A Memcached Alternative Made to Run...
Scylla Summit 2018: Introducing ValuStor, A Memcached Alternative Made to Run...
 
Debugging & Tuning in Spark
Debugging & Tuning in SparkDebugging & Tuning in Spark
Debugging & Tuning in Spark
 
Evolution of MongoDB Replicaset and Its Best Practices
Evolution of MongoDB Replicaset and Its Best PracticesEvolution of MongoDB Replicaset and Its Best Practices
Evolution of MongoDB Replicaset and Its Best Practices
 
Analyze corefile and backtraces with GDB for Mysql/MariaDB on Linux - Nilanda...
Analyze corefile and backtraces with GDB for Mysql/MariaDB on Linux - Nilanda...Analyze corefile and backtraces with GDB for Mysql/MariaDB on Linux - Nilanda...
Analyze corefile and backtraces with GDB for Mysql/MariaDB on Linux - Nilanda...
 
Serialization (Avro, Message Pack, Kryo)
Serialization (Avro, Message Pack, Kryo)Serialization (Avro, Message Pack, Kryo)
Serialization (Avro, Message Pack, Kryo)
 
Postgres-XC as a Key Value Store Compared To MongoDB
Postgres-XC as a Key Value Store Compared To MongoDBPostgres-XC as a Key Value Store Compared To MongoDB
Postgres-XC as a Key Value Store Compared To MongoDB
 
Cassandra Presentation for San Antonio JUG
Cassandra Presentation for San Antonio JUGCassandra Presentation for San Antonio JUG
Cassandra Presentation for San Antonio JUG
 
Presto - Hadoop Conference Japan 2014
Presto - Hadoop Conference Japan 2014Presto - Hadoop Conference Japan 2014
Presto - Hadoop Conference Japan 2014
 
Redis modules 101
Redis modules 101Redis modules 101
Redis modules 101
 
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
 
8. key value databases laboratory
8. key value databases laboratory 8. key value databases laboratory
8. key value databases laboratory
 

Viewers also liked

Google LevelDB Study Discuss
Google LevelDB Study DiscussGoogle LevelDB Study Discuss
Google LevelDB Study Discuss
everestsun
 
iOS + Rails
iOS + RailsiOS + Rails
iOS + Rails
Level UP
 
Multi-thematic spatial databases
Multi-thematic spatial databasesMulti-thematic spatial databases
Multi-thematic spatial databases
Conor Mc Elhinney
 
X query language reference
X query language referenceX query language reference
X query language reference
Steve Xu
 
Sql server ___________session3-normailzation
Sql server  ___________session3-normailzationSql server  ___________session3-normailzation
Sql server ___________session3-normailzation
Ehtisham Ali
 
High Performance Front-End Development
High Performance Front-End DevelopmentHigh Performance Front-End Development
High Performance Front-End Development
drywallbmb
 
Css introduction
Css introductionCss introduction
Css introduction
Sridhar P
 

Viewers also liked (20)

Google LevelDB Study Discuss
Google LevelDB Study DiscussGoogle LevelDB Study Discuss
Google LevelDB Study Discuss
 
Lokijs
LokijsLokijs
Lokijs
 
Lsm
LsmLsm
Lsm
 
iOS + Rails
iOS + RailsiOS + Rails
iOS + Rails
 
Building Scalable, Distributed Job Queues with Redis and Redis::Client
Building Scalable, Distributed Job Queues with Redis and Redis::ClientBuilding Scalable, Distributed Job Queues with Redis and Redis::Client
Building Scalable, Distributed Job Queues with Redis and Redis::Client
 
Amazon Echo
Amazon EchoAmazon Echo
Amazon Echo
 
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
 
Module01
Module01Module01
Module01
 
Multi-thematic spatial databases
Multi-thematic spatial databasesMulti-thematic spatial databases
Multi-thematic spatial databases
 
Alasql - база данных SQL на JavaScript (MoscowJS)
Alasql - база данных SQL на JavaScript (MoscowJS)Alasql - база данных SQL на JavaScript (MoscowJS)
Alasql - база данных SQL на JavaScript (MoscowJS)
 
X query language reference
X query language referenceX query language reference
X query language reference
 
SQL Server 2008 for Developers
SQL Server 2008 for DevelopersSQL Server 2008 for Developers
SQL Server 2008 for Developers
 
Sql server ___________session3-normailzation
Sql server  ___________session3-normailzationSql server  ___________session3-normailzation
Sql server ___________session3-normailzation
 
Module05
Module05Module05
Module05
 
Alasql.js - SQL сервер на JavaScript
Alasql.js - SQL сервер на JavaScriptAlasql.js - SQL сервер на JavaScript
Alasql.js - SQL сервер на JavaScript
 
Module03
Module03Module03
Module03
 
SQL Server 2008 Spatial Data - Getting Started
SQL Server 2008 Spatial Data - Getting StartedSQL Server 2008 Spatial Data - Getting Started
SQL Server 2008 Spatial Data - Getting Started
 
High Performance Front-End Development
High Performance Front-End DevelopmentHigh Performance Front-End Development
High Performance Front-End Development
 
Css introduction
Css introductionCss introduction
Css introduction
 
Module07
Module07Module07
Module07
 

Similar to Level DB - Quick Cheat Sheet

Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Richard Lee
 
AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)
Paul Chao
 
AWS IoT 핸즈온 워크샵 - 실습 5. DynamoDB에 센서 데이터 저장하기 (김무현 솔루션즈 아키텍트)
AWS IoT 핸즈온 워크샵 - 실습 5. DynamoDB에 센서 데이터 저장하기 (김무현 솔루션즈 아키텍트)AWS IoT 핸즈온 워크샵 - 실습 5. DynamoDB에 센서 데이터 저장하기 (김무현 솔루션즈 아키텍트)
AWS IoT 핸즈온 워크샵 - 실습 5. DynamoDB에 센서 데이터 저장하기 (김무현 솔루션즈 아키텍트)
Amazon Web Services Korea
 

Similar to Level DB - Quick Cheat Sheet (20)

Jdbc presentation
Jdbc presentationJdbc presentation
Jdbc presentation
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
 
Scala and Spring
Scala and SpringScala and Spring
Scala and Spring
 
jQuery Objects
jQuery ObjectsjQuery Objects
jQuery Objects
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele Rialdi
 
Concurrency at the Database Layer
Concurrency at the Database Layer Concurrency at the Database Layer
Concurrency at the Database Layer
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disqus
 
Couchbas for dummies
Couchbas for dummiesCouchbas for dummies
Couchbas for dummies
 
Wider than rails
Wider than railsWider than rails
Wider than rails
 
Getting Input from User
Getting Input from UserGetting Input from User
Getting Input from User
 
Unit-2 Getting Input from User.pptx
Unit-2 Getting Input from User.pptxUnit-2 Getting Input from User.pptx
Unit-2 Getting Input from User.pptx
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Unqlite
UnqliteUnqlite
Unqlite
 
cb streams - gavin pickin
cb streams - gavin pickincb streams - gavin pickin
cb streams - gavin pickin
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)
 
AWS IoT 핸즈온 워크샵 - 실습 5. DynamoDB에 센서 데이터 저장하기 (김무현 솔루션즈 아키텍트)
AWS IoT 핸즈온 워크샵 - 실습 5. DynamoDB에 센서 데이터 저장하기 (김무현 솔루션즈 아키텍트)AWS IoT 핸즈온 워크샵 - 실습 5. DynamoDB에 센서 데이터 저장하기 (김무현 솔루션즈 아키텍트)
AWS IoT 핸즈온 워크샵 - 실습 5. DynamoDB에 센서 데이터 저장하기 (김무현 솔루션즈 아키텍트)
 
JavaScript / Web Engineering / Web Development / html + css + js/presentation
JavaScript / Web Engineering / Web Development / html + css + js/presentationJavaScript / Web Engineering / Web Development / html + css + js/presentation
JavaScript / Web Engineering / Web Development / html + css + js/presentation
 
Elements for an iOS Backend
Elements for an iOS BackendElements for an iOS Backend
Elements for an iOS Backend
 
CBStreams - Java Streams for ColdFusion (CFML)
CBStreams - Java Streams for ColdFusion (CFML)CBStreams - Java Streams for ColdFusion (CFML)
CBStreams - Java Streams for ColdFusion (CFML)
 

More from Aniruddha Chakrabarti

Mphasis Digital POV - Emerging Open Standard Protocol stack for IoT
Mphasis Digital POV - Emerging Open Standard Protocol stack for IoTMphasis Digital POV - Emerging Open Standard Protocol stack for IoT
Mphasis Digital POV - Emerging Open Standard Protocol stack for IoT
Aniruddha Chakrabarti
 

More from Aniruddha Chakrabarti (20)

Pinecone Vector Database.pdf
Pinecone Vector Database.pdfPinecone Vector Database.pdf
Pinecone Vector Database.pdf
 
Mphasis-Annual-Report-2018.pdf
Mphasis-Annual-Report-2018.pdfMphasis-Annual-Report-2018.pdf
Mphasis-Annual-Report-2018.pdf
 
Thomas Cook and Accenture expand relationship with 10 year technology consult...
Thomas Cook and Accenture expand relationship with 10 year technology consult...Thomas Cook and Accenture expand relationship with 10 year technology consult...
Thomas Cook and Accenture expand relationship with 10 year technology consult...
 
NLP using JavaScript Natural Library
NLP using JavaScript Natural LibraryNLP using JavaScript Natural Library
NLP using JavaScript Natural Library
 
Dart programming language
Dart programming languageDart programming language
Dart programming language
 
Third era of computing
Third era of computingThird era of computing
Third era of computing
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
 
Amazon alexa - building custom skills
Amazon alexa - building custom skillsAmazon alexa - building custom skills
Amazon alexa - building custom skills
 
Using Node-RED for building IoT workflows
Using Node-RED for building IoT workflowsUsing Node-RED for building IoT workflows
Using Node-RED for building IoT workflows
 
Mphasis Digital - Use Go (gloang) for system programming, distributed systems...
Mphasis Digital - Use Go (gloang) for system programming, distributed systems...Mphasis Digital - Use Go (gloang) for system programming, distributed systems...
Mphasis Digital - Use Go (gloang) for system programming, distributed systems...
 
Using Swift for all Apple platforms (iOS, watchOS, tvOS and OS X)
Using Swift for all Apple platforms (iOS, watchOS, tvOS and OS X)Using Swift for all Apple platforms (iOS, watchOS, tvOS and OS X)
Using Swift for all Apple platforms (iOS, watchOS, tvOS and OS X)
 
Future of .NET - .NET on Non Windows Platforms
Future of .NET - .NET on Non Windows PlatformsFuture of .NET - .NET on Non Windows Platforms
Future of .NET - .NET on Non Windows Platforms
 
CoAP - Web Protocol for IoT
CoAP - Web Protocol for IoTCoAP - Web Protocol for IoT
CoAP - Web Protocol for IoT
 
Groovy Programming Language
Groovy Programming LanguageGroovy Programming Language
Groovy Programming Language
 
Mphasis Digital POV - Emerging Open Standard Protocol stack for IoT
Mphasis Digital POV - Emerging Open Standard Protocol stack for IoTMphasis Digital POV - Emerging Open Standard Protocol stack for IoT
Mphasis Digital POV - Emerging Open Standard Protocol stack for IoT
 
Lisp
LispLisp
Lisp
 
Overview of CoffeeScript
Overview of CoffeeScriptOverview of CoffeeScript
Overview of CoffeeScript
 
Redis and it's data types
Redis and it's data typesRedis and it's data types
Redis and it's data types
 
pebble - Building apps on pebble
pebble - Building apps on pebblepebble - Building apps on pebble
pebble - Building apps on pebble
 
TypeScript Overview
TypeScript OverviewTypeScript Overview
TypeScript Overview
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

Level DB - Quick Cheat Sheet

  • 1. Aniruddha Chakrabarti Associate Vice President and Chief Architect, Digital Practice, Mphasis ani.c@outlook.com | Linkedin.com/in/aniruddhac | slideshare.net/aniruddha.chakrabarti | Twitter - anchakra LevelDB Embedded Key Value Store Quick Cheat sheet
  • 2. Agenda • What is LevelDB • Why LevelDB was created • LevelDB libraries and bindings • LevelDB operations using Node • Write data (put) • Read data (get) • Remove data (del) • Batch Operations (batch) • Iterating data (ReadStream) • Storing and Retrieving JSON data
  • 3. What is LevelDB • LevelDB is a key value store, it stores data in disk. Highly optimized for fast read write (specially writes - benchmark) • Stores keys and values in arbitrary byte arrays, and data is sorted by key. • LevelDB is typically used as embedded database (runs in the same process as your code), but can be networked (by adding protocols such as http, tcp to your process) • LevelDB is not a key value database server like Redis or memcached. It’s a database library similar to SQLite or Oracle Berkeley DB. • Supported on Linux, Windows, OSX • Has drivers and bindings for C++, Node, Python etc. LevelDB is a light-weight, single-purpose library for persistence with bindings to many platforms. http://leveldb.org/
  • 4. What is LevelDB • Written by Google fellows Jeffrey Dean and Sanjay Ghemawat (authors of MapReduce And BigTable) • Inspired by BigTable - same general design as the BigTable tablet stack, but not sharing any of the code • Developed in early 2011 • Chrome IndexDB feature (HTML5 API) is built on top of LevelDB • Similar storage libraries include Oracle Berkeley DB, SQLite, Kyoto Cabinet, RocksDB etc. LevelDB is a light-weight, single-purpose library for persistence with bindings to many platforms. http://leveldb.org/
  • 5. Performance Benchmark LevelDB outperforms both SQLite3 and TreeDB in sequential and random write operations and sequential read operations. Kyoto Cabinet has the fastest random read operations http://leveldb.googlecode.com/svn/trunk/doc/benchmark.html
  • 6. LevelDB library and bindings • LevelDown - Low-level Node.js LevelDB binding • LevelUp – High level Node.js-style LevelDB wrapper. LevelUP aims to expose the features of LevelDB in a Node.js-friendly way • Rather than installing LevelDB and LevelUp separately you can install it as a whole – npm install level • We would be using LevelUp Node.js LevelDB wrapper for all our examples • All operations in LevelUp are asynchronous although they don't necessarily require a callback if you don't need to know when the operation was performed.
  • 7. Installing LevelDB Node Bindings Installation • Install LevelUp Node Bindings (library) using npm (Node Package Manager) - npm install level or npm install level -- save (to update the dependency in project.json) (LevelUp Node Bindings Location - https://github.com/Level/levelup) Referencing the Node Library in code • Reference the LevelUp Node library var level = require('level'); • Create a db object by calling level() function passing the path where the data files would be stored. db object contains all the methods required for interacting with LevelDB. Here the data files would be stored in a subfolder called db relative to node file var db = level('./db');
  • 8. Write Data (put) • Inserts/writes data into the store. Both the key and value can be arbitrary data objects. • The Node API is asynchronous – put accepts key, value and a callback. Once the operation is completed (success or error) the callback is called. • If error occurs then the error object is passed as argument to the callback. The callback argument is optional - if you don't provide the callback argument and an error occurs then the error is thrown, so it’s better to provide the error argument. var level = require('level'); var db = level('./db'); var key = "city", value = "Bangalore"; db.put(key, value, function(error){ if (error != null){ console.log(error); } else { console.log('data saved successfully to disk'); } });
  • 9. Read Data (get) • Reads/retrieves data from the store – the key for which data needs to be retrieved need to be specified. • Similar to get, put also works asynchronously. It accepts key and a callback. Once the operation is completed (success or error) the callback is called, which accepts the value retrieved as parameter. • If the key doesn't exist in the store then the callback will receive an error as its first argument. A not found error object will be of type 'NotFoundError' var key = "city", another_key = "student"; db.get(key, function(error, city){ console.log(city); // displays Bangalore }); db.get(another_key, function(error, value){ if (error == null){ console.log(value); } else{ console.log(error.type + " - " + error.message); } // displays NotFoundError - Key not found in database [student] });
  • 10. Remove Data (del) • Removes data from the store permanently. var key = "city"; db.del(key, function(error){ if (error != null){ console.log(error); } else { console.log('data deleted successfully'); } }); db.get(key, function(error, city){ console.log(city); // displays undefined });
  • 11. Batch Operations • Batch operations could be used for very fast bulk-write operations (both put and delete). • Supports an array form and a chained form (similar to Fluent API) • Array form • db.batch(array, error callback) • array argument should contain a list of operations to be executed sequentially, although as a whole they are performed as an atomic operation inside LevelDB. • Each operation is contained in an object having the following properties: type, key, value, where the type is either 'put' or 'del' • If key and value are defined but type is not, it will default to 'put'. • Chained form • batch(), when called with no arguments returns a Batch object which can be used to build, and eventually commit, an atomic LevelDB batch operation. • Depending on how it's used, it is possible to obtain greater performance when using the chained form of batch() over the array form.
  • 12. batch (array form) var ops = [ // All operations of the batch are listed in an array {type:'put', key:'city1', value:'Bangalore'}, // type of operation, key & value {type:'put', key:'city2', value:'Kolkata'}, {type:'put', key:'city3', value:'Chennai'}, {type:'del', key:'city'}, ] db.batch(ops, function (error){ if (error != null){ console.log(error); } else { console.log('batch operation successful'); } })
  • 13. batch (chained form) • First line of code returns a Batch object which is then used to build all operations one by one • Once it’s built, it’s eventually gets committed through write, which is an atomic LevelDB batch operation. db.batch() // returns a Batch object which is used to chain all operations .del("city") .put("city1","Bangalore") .put("city2","Kolkata") .put("city3","Chennai") .write(function(){ // committing the batch operation console.log('batch operation successful'); });
  • 14. Iteration and ReadStream • Get a ReadStream of the full database by calling the createReadStream() method – the returned stream is a complete Node.js-style Readable Stream. data object have key and value property. var stream = db.createReadStream() stream.on('data', function (data) { console.log('key=', data.key + ",value=" + data.value); }); • Use the gt, lt and limit options to control the range of keys that are streamed. var stream = db.createReadStream({limit:2})
  • 15. KeyStream and ValueStream • A KeyStream is a ReadStream where the 'data' events are simply the keys from the database – use createKeyStream() method to get a KeyStream • A ValueStream is a ReadStream where the 'data' events are simply the values from the database – use createValueStream() method to get a ValueStream Iterating through all keys var keyStream = db.createKeyStream() keyStream.on('data', function (data) { console.log('key = ', data) }) Iterating through all values var valueStream = db.createValueStream() valueStream.on('data', function (data) { console.log('value = ', data) })
  • 16. Storing JSON objects • JSON objects could be stored as value, apart from simple strings, numbers etc. • To store JSON objects, set the valueEncoding options parameter to json while constructing the db object. • Multiple level of nested objects could be stored as value var db = level('./dbJson', { valueEncoding : 'json' }); var employee = { name : "XYZ", age : 45, designation : "VP" }; db.put('employee', employee, function(error){ db.get('employee', function(error, employee){ console.log(employee.name); // Aniruddha console.log(employee.age); // 45 console.log(employee.designation); // VP }); });
  • 17. Storing JSON objects (complex) var db = level('./dbJson', { valueEncoding : 'json' }); var employee = { name : "XYZ", age : 45, designation : "VP" }; var employee = { name : "XYZ", age : 45, designation : "VP", skills : ["NoSQL","Management","Languages","Oracle"], // Array address : { streetAddress:"123 M G Road", city: "Bangalore", country: "IN" } // Object }; db.put('employee', employee, function(error){ db.get('employee', function(error, employee){ console.log(employee.name); // XYZ console.log(employee.skills[0]); // NoSQL console.log(employee.address.streetAddress + " - " + employee.address.city); // 123 M G Road - Bangalore }); });