SlideShare a Scribd company logo
NoSQL databases
Sometimes being unstructured helps
Amrit Sanjeev
Organizer @ Blrdroid
Who am I ?
Agenda
● Type of databases available in Android
● When to use them
● How they help ?
● Some feature of popular db products
Data trends
- Amount of data stored is increasing
- Data is more unstructured
- Efficiency and performance are critical
- Relations are more complex
Datastore evolution
RDBMS vs NoSQL
- Structured data
- Transform data policy
- Atomic transactions
- Data model != Entity model
- Scale up
- Semi or unstructured data
- Update schema policy
- Eventual consistency
- Data model ~= Entity model
- Scale out
No sql databases   blrdroid devfest 2016
Real time database
- NoSQL, JSON database
- Maps each piece of data to a URL
- Offline support
- Supports iOS , Android and Web
- Pushes updates in milliseconds when
things change
Cross platform support
Listening to data changes
● Attach an asynchronous listener to a Firebase reference.
● The listener will be triggered
○ once for the initial state of the data
○ again anytime the data changes
Firebase ref = new Firebase("https://docs-examples.firebaseio.com/web/saving-data/fireblog/posts");
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println(snapshot.getValue());
}
@Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
Reading data once
● Callback will be called only once
● removed after the first trigger
Firebase ref = new Firebase("https://docs-examples.firebaseio.com/web/saving-data/fireblog/posts");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
// do some stuff once
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Querying data
● Selectively retrieve data based on various factors.
● Start by specifying how you want your data to be ordered
○ orderByChild()
○ orderByKey()
○ orderByValue()
○ orderByPriority()
● combine these other methods to conduct complex queries
○ limitToFirst()
○ limitToLast()
○ startAt()
○ endAt()
○ equalTo()
No sql databases   blrdroid devfest 2016
What is Realm ?
- Zero copy object store database
- Easy setup
- Optimized for read , not writes
- Cross platform
- Simple Querying interface
Defining objects in realm
public class Person extends RealmObject {
@PrimaryKey
private long id;
private String name;
private RealmList<Dog> dogs;
// Declare one-to-many relationships
// ... Generated getters and setters ...
}
@RealmClass
public class Person implements RealmModel {
@PrimaryKey
private long id;
private String name;
private RealmList<Dog> dogs;
// Declare one-to-many relationships
// ... Generated getters and setters ...
}
Relationships
public class Person extends RealmObject {
private String firstName;
private String lastName;
private Dog dog;
// ... Generated getters and setters ...
}
public class Person extends RealmObject {
private String firstName;
private String lastName;
private RealmList<Dog> dogs;
// ... Generated getters and setters ...
}
public class Person extends RealmObject {
private String firstName;
private String lastName;
private RealmList<Person> friends;
// .. getters/setters
}
Saving objects in realm
// Use them like regular java objects
Dog dog = new Dog();
dog.setName("Rex");
dog.setAge("1");
// Get a Realm instance
Realm realm = Realm.getDefaultInstance();
// Persist your data easily
realm.beginTransaction();
realm.copyToRealm(dog);
realm.commitTransaction();
// Get a Realm instance
Realm realm = Realm.getDefaultInstance();
// Create and persist your data easily
realm.beginTransaction();
Dog dog = realm.createObject(Dog.class);
dog.setName("Rex");
dog.setAge("1");
realm.commitTransaction();
Transactions
try {
realm.beginTransaction();
Dog dog = realm.where(Dog.class).
equalTo("name", "Fido").findFirst();
dog.setAge(15);
realm.commitTransaction();
}
catch (Exception ex) {
// rollback
realm.cancelTransaction();
}
realm.executeTransaction(
new Realm.Transaction() {
@Override
public void execute(Realm realm) {
Dog dog= realm.where(Dog.class).
equalTo("name", "Fido").findFirst();
dog.setAge(15);
}
})
Async Transactions
// Use them like regular java objects
realm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm bgRealm) {
User user = bgRealm.createObject(User.class);
user.setName("John");
}
}, new Realm.Transaction.OnSuccess() {
@Override
public void onSuccess() {
// Transaction was a success.
}
}, new Realm.Transaction.OnError() {
@Override
public void onError(Throwable error) {
// Transaction failed and was automatically canceled.
}
});
RealmAsyncTask transaction = realm.executeTransactionAsync(
new Realm.Transaction() {
@Override
public void execute(Realm bgRealm) {
User user = bgRealm.createObject(User.class);
user.setName("John");
user.setEmail("john@corporation.com");
}
}, null);
Querying data
// Build the query looking at all users:
RealmQuery<User> query = realm.where(User.class);
// Add query conditions:
query.equalTo("name", "John");
query.or().equalTo("name", "Peter");
// Execute the query:
RealmResults<User> result1 = query.findAll();
// Or alternatively do the same all at once (the "Fluent interface"):
RealmResults<User> result2 = realm.where(User.class)
.equalTo("name", "John")
.or()
.equalTo("name", "Peter")
.findAll();
Query data supports
- Conditions like lessThan, greaterThan, contains, beginsWith etc
- Modifiers for ignoring Cases
- Logical Operations OR AND
- Sorting Ascending, Descending
- Chaining Queries
- Aggregations like SUM, MIN, MAX, AVG
- Synchronous, Asynchronous operations
Linked queries
public class Person extends RealmObject {
private String id;
private String name;
private RealmList<Dog> dogs;
// getters and setters
}
public class Dog extends RealmObject {
private String id;
private String name;
private String color;
// getters and setters
}
Linked queries
RealmResults<Person> r1 = realm.where(Person.class)
.equalTo("dogs.name", "Fluffy")
.findAll();
RealmResults<Person> r2 = r1.where()
.equalTo("dogs.color", "Brown")
.findAll();
Auto updating objects
Dog d1 = realm.where(Dog.class).equals("id", 123).findFirst();
// register a listener to get notified when the object is updated.
d1.registerChangeListener(new RealmChangeListener() {
@Override
public void onChange() {
// called once the query complete and on every update
// do something now that the obj is updated
}
});
// assume code below is in some other thread
// Retrieve the same dog as above
Dog d2 = realm.where(Dog.class).equals("id", 123).first();
realm.beginTransaction();
d2.setAge(12);
realm.commitTransaction();
// d1's change listener gets called after the commit.*
Migration
// Example migration adding a new class
RealmMigration MyMigration = new RealmMigration() {
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
// DynamicRealm exposes an editable schema
RealmSchema schema = realm.getSchema();
if (oldVersion == 0) {
schema.create("Person")
.addField("id", long.class, FieldAttribute.PRIMARY_KEY)
.addField("name", String.class)
.addField("age", int.class);
oldVersion++;
}
}
}
// in your init
RealmConfiguration config = new RealmConfiguration.Builder(context).schemaVersion(1)
.migration(new MyMigration()) ;
More features
● Direct support for Json to Object store
● Notification for database change like CP
● Encryption support in built
● Adapters for binding data with views (Android)
● Cross Platform, same data can work across ios and android
● Robust 3rd parties addons
Limitations
● Managing memory is tricky
● Not Entirely NOSQL, need migration on schema Changes
● No support for auto incrementing primary keys
● Mutable, thread-confined objects.
● Slower write
● Increase method count and size of apk
Latest update
● Server side tech
○ Real time sync
○ Conflict resolution
○ Reactive event handling
○ Authentication
○ Access control
● Good to building offline experiences
● Not a managed service yet
Thank you!
Amrit Sanjeev
@amsanjeev
#blrdroid

More Related Content

PPTX
ElasticSearch for .NET Developers
PDF
Green dao 3.0
PPTX
Getting started with Elasticsearch and .NET
PPTX
Elastic search
PDF
Advanced Redis data structures
KEY
Getting the most out of Java [Nordic Coding-2010]
PDF
Going beyond Django ORM limitations with Postgres
PDF
Postgresql search demystified
ElasticSearch for .NET Developers
Green dao 3.0
Getting started with Elasticsearch and .NET
Elastic search
Advanced Redis data structures
Getting the most out of Java [Nordic Coding-2010]
Going beyond Django ORM limitations with Postgres
Postgresql search demystified

What's hot (18)

PDF
Full Text Search In PostgreSQL
PPTX
Simplifying Persistence for Java and MongoDB with Morphia
PPTX
Golang slidesaudrey
PPTX
Oak Lucene Indexes
PPTX
ElasticSearch 5.x - New Tricks - 2017-02-08 - Elasticsearch Meetup
ODP
A Year With MongoDB: The Tips
KEY
Scala - den smarta kusinen
PPTX
Indexing and Query Optimisation
PDF
SICP_2.5 일반화된 연산시스템
PPTX
Introduction to NOSQL And MongoDB
PDF
Apache Spark - Key-Value RDD | Big Data Hadoop Spark Tutorial | CloudxLab
PPTX
Sequelize
PDF
Fun with Functional Programming in Clojure
PDF
Brief introduction of Slick
PDF
How to Use JSON in MySQL Wrong
PPT
DB2 Native XML
PPT
2011 Mongo FR - MongoDB introduction
PDF
Let's talk about NoSQL Standard
Full Text Search In PostgreSQL
Simplifying Persistence for Java and MongoDB with Morphia
Golang slidesaudrey
Oak Lucene Indexes
ElasticSearch 5.x - New Tricks - 2017-02-08 - Elasticsearch Meetup
A Year With MongoDB: The Tips
Scala - den smarta kusinen
Indexing and Query Optimisation
SICP_2.5 일반화된 연산시스템
Introduction to NOSQL And MongoDB
Apache Spark - Key-Value RDD | Big Data Hadoop Spark Tutorial | CloudxLab
Sequelize
Fun with Functional Programming in Clojure
Brief introduction of Slick
How to Use JSON in MySQL Wrong
DB2 Native XML
2011 Mongo FR - MongoDB introduction
Let's talk about NoSQL Standard
Ad

Similar to No sql databases blrdroid devfest 2016 (20)

PPTX
Integration patterns in AEM 6
PDF
MongoDB .local Houston 2019: REST-less Mobile Apps: Why Offline-first and Syn...
PDF
MongoDB World 2019: Realm: The Secret Sauce for Better Mobile Apps
PPTX
Present realm
PDF
Terrastore - A document database for developers
PPTX
PostgreSQL's Secret NoSQL Superpowers
PDF
Hands On Spring Data
PPT
Persistences
PDF
Android Architecure Components - introduction
PDF
Android Jetpack: Room persistence library
PDF
09.Local Database Files and Storage on WP
PDF
Using Combine, SwiftUI and callAsFunction to build an experimental localizati...
PPTX
07 darwino rest services
PDF
Java Web Programming on Google Cloud Platform [2/3] : Datastore
PDF
Painless Persistence in a Disconnected World
PDF
MongoDB .local Chicago 2019: REST-less Mobile Apps: Why Offline-first & Sync ...
PPTX
Webinar: Simplifying Persistence for Java and MongoDB
PDF
Infinispan,Lucene,Hibername OGM
PDF
Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...
PDF
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
Integration patterns in AEM 6
MongoDB .local Houston 2019: REST-less Mobile Apps: Why Offline-first and Syn...
MongoDB World 2019: Realm: The Secret Sauce for Better Mobile Apps
Present realm
Terrastore - A document database for developers
PostgreSQL's Secret NoSQL Superpowers
Hands On Spring Data
Persistences
Android Architecure Components - introduction
Android Jetpack: Room persistence library
09.Local Database Files and Storage on WP
Using Combine, SwiftUI and callAsFunction to build an experimental localizati...
07 darwino rest services
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Painless Persistence in a Disconnected World
MongoDB .local Chicago 2019: REST-less Mobile Apps: Why Offline-first & Sync ...
Webinar: Simplifying Persistence for Java and MongoDB
Infinispan,Lucene,Hibername OGM
Object Graph Mapping with Spring Data Neo4j 3 - Nicki Watt & Michael Hunger @...
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
Ad

More from amsanjeev (8)

PDF
Introduction to Firebase on Android
PDF
Introduction to Android M
PDF
Io13 deep dive location api
PPTX
Jelly bean aka Andorid 4.1
PPTX
Mobile UX
PPTX
Location Based Services - An Overview
PPTX
NFC - quick primer
PPTX
Introduction to ICS
Introduction to Firebase on Android
Introduction to Android M
Io13 deep dive location api
Jelly bean aka Andorid 4.1
Mobile UX
Location Based Services - An Overview
NFC - quick primer
Introduction to ICS

Recently uploaded (20)

PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PPTX
Cloud computing and distributed systems.
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Transforming Manufacturing operations through Intelligent Integrations
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Sensors and Actuators in IoT Systems using pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
The Rise and Fall of 3GPP – Time for a Sabbatical?
NewMind AI Weekly Chronicles - August'25 Week I
Spectral efficient network and resource selection model in 5G networks
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
GamePlan Trading System Review: Professional Trader's Honest Take
Cloud computing and distributed systems.
NewMind AI Monthly Chronicles - July 2025
Reach Out and Touch Someone: Haptics and Empathic Computing
Transforming Manufacturing operations through Intelligent Integrations
The AUB Centre for AI in Media Proposal.docx
Sensors and Actuators in IoT Systems using pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Diabetes mellitus diagnosis method based random forest with bat algorithm
Mobile App Security Testing_ A Comprehensive Guide.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation

No sql databases blrdroid devfest 2016

  • 1. NoSQL databases Sometimes being unstructured helps Amrit Sanjeev Organizer @ Blrdroid
  • 3. Agenda ● Type of databases available in Android ● When to use them ● How they help ? ● Some feature of popular db products
  • 4. Data trends - Amount of data stored is increasing - Data is more unstructured - Efficiency and performance are critical - Relations are more complex
  • 6. RDBMS vs NoSQL - Structured data - Transform data policy - Atomic transactions - Data model != Entity model - Scale up - Semi or unstructured data - Update schema policy - Eventual consistency - Data model ~= Entity model - Scale out
  • 8. Real time database - NoSQL, JSON database - Maps each piece of data to a URL - Offline support - Supports iOS , Android and Web - Pushes updates in milliseconds when things change
  • 10. Listening to data changes ● Attach an asynchronous listener to a Firebase reference. ● The listener will be triggered ○ once for the initial state of the data ○ again anytime the data changes Firebase ref = new Firebase("https://docs-examples.firebaseio.com/web/saving-data/fireblog/posts"); ref.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { System.out.println(snapshot.getValue()); } @Override public void onCancelled(FirebaseError firebaseError) { System.out.println("The read failed: " + firebaseError.getMessage()); } });
  • 11. Reading data once ● Callback will be called only once ● removed after the first trigger Firebase ref = new Firebase("https://docs-examples.firebaseio.com/web/saving-data/fireblog/posts"); ref.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { // do some stuff once } @Override public void onCancelled(FirebaseError firebaseError) { } });
  • 12. Querying data ● Selectively retrieve data based on various factors. ● Start by specifying how you want your data to be ordered ○ orderByChild() ○ orderByKey() ○ orderByValue() ○ orderByPriority() ● combine these other methods to conduct complex queries ○ limitToFirst() ○ limitToLast() ○ startAt() ○ endAt() ○ equalTo()
  • 14. What is Realm ? - Zero copy object store database - Easy setup - Optimized for read , not writes - Cross platform - Simple Querying interface
  • 15. Defining objects in realm public class Person extends RealmObject { @PrimaryKey private long id; private String name; private RealmList<Dog> dogs; // Declare one-to-many relationships // ... Generated getters and setters ... } @RealmClass public class Person implements RealmModel { @PrimaryKey private long id; private String name; private RealmList<Dog> dogs; // Declare one-to-many relationships // ... Generated getters and setters ... }
  • 16. Relationships public class Person extends RealmObject { private String firstName; private String lastName; private Dog dog; // ... Generated getters and setters ... } public class Person extends RealmObject { private String firstName; private String lastName; private RealmList<Dog> dogs; // ... Generated getters and setters ... } public class Person extends RealmObject { private String firstName; private String lastName; private RealmList<Person> friends; // .. getters/setters }
  • 17. Saving objects in realm // Use them like regular java objects Dog dog = new Dog(); dog.setName("Rex"); dog.setAge("1"); // Get a Realm instance Realm realm = Realm.getDefaultInstance(); // Persist your data easily realm.beginTransaction(); realm.copyToRealm(dog); realm.commitTransaction(); // Get a Realm instance Realm realm = Realm.getDefaultInstance(); // Create and persist your data easily realm.beginTransaction(); Dog dog = realm.createObject(Dog.class); dog.setName("Rex"); dog.setAge("1"); realm.commitTransaction();
  • 18. Transactions try { realm.beginTransaction(); Dog dog = realm.where(Dog.class). equalTo("name", "Fido").findFirst(); dog.setAge(15); realm.commitTransaction(); } catch (Exception ex) { // rollback realm.cancelTransaction(); } realm.executeTransaction( new Realm.Transaction() { @Override public void execute(Realm realm) { Dog dog= realm.where(Dog.class). equalTo("name", "Fido").findFirst(); dog.setAge(15); } })
  • 19. Async Transactions // Use them like regular java objects realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm bgRealm) { User user = bgRealm.createObject(User.class); user.setName("John"); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { // Transaction was a success. } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { // Transaction failed and was automatically canceled. } }); RealmAsyncTask transaction = realm.executeTransactionAsync( new Realm.Transaction() { @Override public void execute(Realm bgRealm) { User user = bgRealm.createObject(User.class); user.setName("John"); user.setEmail("[email protected]"); } }, null);
  • 20. Querying data // Build the query looking at all users: RealmQuery<User> query = realm.where(User.class); // Add query conditions: query.equalTo("name", "John"); query.or().equalTo("name", "Peter"); // Execute the query: RealmResults<User> result1 = query.findAll(); // Or alternatively do the same all at once (the "Fluent interface"): RealmResults<User> result2 = realm.where(User.class) .equalTo("name", "John") .or() .equalTo("name", "Peter") .findAll();
  • 21. Query data supports - Conditions like lessThan, greaterThan, contains, beginsWith etc - Modifiers for ignoring Cases - Logical Operations OR AND - Sorting Ascending, Descending - Chaining Queries - Aggregations like SUM, MIN, MAX, AVG - Synchronous, Asynchronous operations
  • 22. Linked queries public class Person extends RealmObject { private String id; private String name; private RealmList<Dog> dogs; // getters and setters } public class Dog extends RealmObject { private String id; private String name; private String color; // getters and setters }
  • 23. Linked queries RealmResults<Person> r1 = realm.where(Person.class) .equalTo("dogs.name", "Fluffy") .findAll(); RealmResults<Person> r2 = r1.where() .equalTo("dogs.color", "Brown") .findAll();
  • 24. Auto updating objects Dog d1 = realm.where(Dog.class).equals("id", 123).findFirst(); // register a listener to get notified when the object is updated. d1.registerChangeListener(new RealmChangeListener() { @Override public void onChange() { // called once the query complete and on every update // do something now that the obj is updated } }); // assume code below is in some other thread // Retrieve the same dog as above Dog d2 = realm.where(Dog.class).equals("id", 123).first(); realm.beginTransaction(); d2.setAge(12); realm.commitTransaction(); // d1's change listener gets called after the commit.*
  • 25. Migration // Example migration adding a new class RealmMigration MyMigration = new RealmMigration() { @Override public void migrate(DynamicRealm realm, long oldVersion, long newVersion) { // DynamicRealm exposes an editable schema RealmSchema schema = realm.getSchema(); if (oldVersion == 0) { schema.create("Person") .addField("id", long.class, FieldAttribute.PRIMARY_KEY) .addField("name", String.class) .addField("age", int.class); oldVersion++; } } } // in your init RealmConfiguration config = new RealmConfiguration.Builder(context).schemaVersion(1) .migration(new MyMigration()) ;
  • 26. More features ● Direct support for Json to Object store ● Notification for database change like CP ● Encryption support in built ● Adapters for binding data with views (Android) ● Cross Platform, same data can work across ios and android ● Robust 3rd parties addons
  • 27. Limitations ● Managing memory is tricky ● Not Entirely NOSQL, need migration on schema Changes ● No support for auto incrementing primary keys ● Mutable, thread-confined objects. ● Slower write ● Increase method count and size of apk
  • 28. Latest update ● Server side tech ○ Real time sync ○ Conflict resolution ○ Reactive event handling ○ Authentication ○ Access control ● Good to building offline experiences ● Not a managed service yet