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

What's hot (10)

Relational database design
Relational database designRelational database design
Relational database design
 
Conditional jump
Conditional jumpConditional jump
Conditional jump
 
COMPUTER ORGANIZATION NOTES Unit 2
COMPUTER ORGANIZATION NOTES  Unit 2COMPUTER ORGANIZATION NOTES  Unit 2
COMPUTER ORGANIZATION NOTES Unit 2
 
Unit 3 dbms
Unit 3 dbmsUnit 3 dbms
Unit 3 dbms
 
Distributed DBMS - Unit 5 - Semantic Data Control
Distributed DBMS - Unit 5 - Semantic Data ControlDistributed DBMS - Unit 5 - Semantic Data Control
Distributed DBMS - Unit 5 - Semantic Data Control
 
introduction-to_mobile_computing 1
 introduction-to_mobile_computing 1 introduction-to_mobile_computing 1
introduction-to_mobile_computing 1
 
Ripple counter
Ripple counterRipple counter
Ripple counter
 
4Sem VTU-HDL Programming Notes-Unit1-Introduction
4Sem VTU-HDL Programming Notes-Unit1-Introduction4Sem VTU-HDL Programming Notes-Unit1-Introduction
4Sem VTU-HDL Programming Notes-Unit1-Introduction
 
Data-Persistency
Data-PersistencyData-Persistency
Data-Persistency
 
Lec 04 - Gate-level Minimization
Lec 04 - Gate-level MinimizationLec 04 - Gate-level Minimization
Lec 04 - Gate-level Minimization
 

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

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
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
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 

Recently uploaded (20)

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
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
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 

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