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

Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 
Types Of Keys in DBMS
Types Of Keys in DBMSTypes Of Keys in DBMS
Types Of Keys in DBMSPadamNepal1
 
Degree of relationship set
Degree of relationship setDegree of relationship set
Degree of relationship setMegha Sharma
 
Multi-Dimensional Lists
Multi-Dimensional ListsMulti-Dimensional Lists
Multi-Dimensional Listsprimeteacher32
 
lec02-Syntax Analysis and LL(1).pdf
lec02-Syntax Analysis and LL(1).pdflec02-Syntax Analysis and LL(1).pdf
lec02-Syntax Analysis and LL(1).pdfwigewej294
 
Dbms 10: Conversion of ER model to Relational Model
Dbms 10: Conversion of ER model to Relational ModelDbms 10: Conversion of ER model to Relational Model
Dbms 10: Conversion of ER model to Relational ModelAmiya9439793168
 
4. SQL in DBMS
4. SQL in DBMS4. SQL in DBMS
4. SQL in DBMSkoolkampus
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manualsameer farooq
 
Operator Precedence Grammar
Operator Precedence GrammarOperator Precedence Grammar
Operator Precedence GrammarHarisonFekadu
 
Relational Algebra,Types of join
Relational Algebra,Types of joinRelational Algebra,Types of join
Relational Algebra,Types of joinraj upadhyay
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#SyedUmairAli9
 
Python | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialPython | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialQA TrainingHub
 
Stack data structure
Stack data structureStack data structure
Stack data structureTech_MX
 
ER to relational Mapping: Data base design using ER to relational language. C...
ER to relational Mapping: Data base design using ER to relational language. C...ER to relational Mapping: Data base design using ER to relational language. C...
ER to relational Mapping: Data base design using ER to relational language. C...Raj vardhan
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Sagar Verma
 

What's hot (20)

Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Types Of Keys in DBMS
Types Of Keys in DBMSTypes Of Keys in DBMS
Types Of Keys in DBMS
 
Degree of relationship set
Degree of relationship setDegree of relationship set
Degree of relationship set
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
 
Multi-Dimensional Lists
Multi-Dimensional ListsMulti-Dimensional Lists
Multi-Dimensional Lists
 
lec02-Syntax Analysis and LL(1).pdf
lec02-Syntax Analysis and LL(1).pdflec02-Syntax Analysis and LL(1).pdf
lec02-Syntax Analysis and LL(1).pdf
 
Dbms 10: Conversion of ER model to Relational Model
Dbms 10: Conversion of ER model to Relational ModelDbms 10: Conversion of ER model to Relational Model
Dbms 10: Conversion of ER model to Relational Model
 
4. SQL in DBMS
4. SQL in DBMS4. SQL in DBMS
4. SQL in DBMS
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 
Operator Precedence Grammar
Operator Precedence GrammarOperator Precedence Grammar
Operator Precedence Grammar
 
Relational Algebra,Types of join
Relational Algebra,Types of joinRelational Algebra,Types of join
Relational Algebra,Types of join
 
STL in C++
STL in C++STL in C++
STL in C++
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
 
Python | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialPython | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python Tutorial
 
Heap sort
Heap sortHeap sort
Heap sort
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Singly link list
Singly link listSingly link list
Singly link list
 
ER to relational Mapping: Data base design using ER to relational language. C...
ER to relational Mapping: Data base design using ER to relational language. C...ER to relational Mapping: Data base design using ER to relational language. C...
ER to relational Mapping: Data base design using ER to relational language. C...
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
 

Viewers also liked

Google LevelDB Study Discuss
Google LevelDB Study DiscussGoogle LevelDB Study Discuss
Google LevelDB Study Discusseverestsun
 
iOS + Rails
iOS + RailsiOS + Rails
iOS + RailsLevel UP
 
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::ClientMike Friedman
 
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...Andrey Gershun
 
Multi-thematic spatial databases
Multi-thematic spatial databasesMulti-thematic spatial databases
Multi-thematic spatial databasesConor Mc Elhinney
 
Alasql - база данных SQL на JavaScript (MoscowJS)
Alasql - база данных SQL на JavaScript (MoscowJS)Alasql - база данных SQL на JavaScript (MoscowJS)
Alasql - база данных SQL на JavaScript (MoscowJS)Andrey Gershun
 
X query language reference
X query language referenceX query language reference
X query language referenceSteve Xu
 
SQL Server 2008 for Developers
SQL Server 2008 for DevelopersSQL Server 2008 for Developers
SQL Server 2008 for Developersllangit
 
Sql server ___________session3-normailzation
Sql server  ___________session3-normailzationSql server  ___________session3-normailzation
Sql server ___________session3-normailzationEhtisham Ali
 
Alasql.js - SQL сервер на JavaScript
Alasql.js - SQL сервер на JavaScriptAlasql.js - SQL сервер на JavaScript
Alasql.js - SQL сервер на JavaScriptAndrey Gershun
 
High Performance Front-End Development
High Performance Front-End DevelopmentHigh Performance Front-End Development
High Performance Front-End Developmentdrywallbmb
 
Css introduction
Css introductionCss introduction
Css introductionSridhar 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

Jdbc presentation
Jdbc presentationJdbc presentation
Jdbc presentationnrjoshiee
 
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 WolffJAX London
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele RialdiCodeFest
 
Concurrency at the Database Layer
Concurrency at the Database Layer Concurrency at the Database Layer
Concurrency at the Database Layer mcwilson1
 
DjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling DisqusDjangoCon 2010 Scaling Disqus
DjangoCon 2010 Scaling Disquszeeg
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRichard Lee
 
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.jsasync_io
 
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
 
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/presentationM Sajid R
 
Elements for an iOS Backend
Elements for an iOS BackendElements for an iOS Backend
Elements for an iOS BackendLaurent Cerveau
 
CBStreams - Java Streams for ColdFusion (CFML)
CBStreams - Java Streams for ColdFusion (CFML)CBStreams - Java Streams for ColdFusion (CFML)
CBStreams - Java Streams for ColdFusion (CFML)Ortus Solutions, Corp
 

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

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...Aniruddha Chakrabarti
 
NLP using JavaScript Natural Library
NLP using JavaScript Natural LibraryNLP using JavaScript Natural Library
NLP using JavaScript Natural LibraryAniruddha Chakrabarti
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageAniruddha Chakrabarti
 
Amazon alexa - building custom skills
Amazon alexa - building custom skillsAmazon alexa - building custom skills
Amazon alexa - building custom skillsAniruddha Chakrabarti
 
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 workflowsAniruddha Chakrabarti
 
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...Aniruddha Chakrabarti
 
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)Aniruddha Chakrabarti
 
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 PlatformsAniruddha 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 IoTAniruddha 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
 
memcached Distributed Cache
memcached Distributed Cachememcached Distributed Cache
memcached Distributed Cache
 
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
 

Recently uploaded

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
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...Drew Madelung
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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 DevelopmentsTrustArc
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Recently uploaded (20)

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
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...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

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 }); });