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)

ODP
Realm Mobile Database - An Introduction
PPTX
Realm or: How I learned to stop worrying and love my app database
PPTX
Present realm
PDF
Painless Persistence in a Disconnected World
PDF
Realm Java 2.2.0: Build better apps, faster apps
PDF
Realm Java 2.2.0: Build better apps, faster apps
PDF
Realm: Building a mobile database
PPTX
Realm mobile database
PDF
Webinar: MongoDB Persistence with Java and Morphia
PPTX
RealmDB for Android
PDF
Let's talk about NoSQL Standard
ODP
Polyglot persistence with Spring Data
PDF
Painless Persistence with Realm
PDF
A Spring Data’s Guide to Persistence
PDF
Java Web Programming on Google Cloud Platform [2/3] : Datastore
PDF
Wed 1630 greene_robert_color
PDF
#MBLTdev: Уроки, которые мы выучили, создавая Realm
PDF
ITB_2023_Relationships_are_Hard_Data_modeling_with_NoSQL_Curt_Gratz.pdf
PDF
Introduction to Datastore
PDF
Using JPA applications in the era of NoSQL: Introducing Hibernate OGM
Realm Mobile Database - An Introduction
Realm or: How I learned to stop worrying and love my app database
Present realm
Painless Persistence in a Disconnected World
Realm Java 2.2.0: Build better apps, faster apps
Realm Java 2.2.0: Build better apps, faster apps
Realm: Building a mobile database
Realm mobile database
Webinar: MongoDB Persistence with Java and Morphia
RealmDB for Android
Let's talk about NoSQL Standard
Polyglot persistence with Spring Data
Painless Persistence with Realm
A Spring Data’s Guide to Persistence
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Wed 1630 greene_robert_color
#MBLTdev: Уроки, которые мы выучили, создавая Realm
ITB_2023_Relationships_are_Hard_Data_modeling_with_NoSQL_Curt_Gratz.pdf
Introduction to Datastore
Using JPA applications in the era of NoSQL: Introducing Hibernate OGM
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
Encapsulation_ Review paper, used for researhc scholars
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Machine Learning_overview_presentation.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPT
Teaching material agriculture food technology
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Encapsulation theory and applications.pdf
PDF
Approach and Philosophy of On baking technology
PPTX
Big Data Technologies - Introduction.pptx
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
cuic standard and advanced reporting.pdf
Encapsulation_ Review paper, used for researhc scholars
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Empathic Computing: Creating Shared Understanding
Machine Learning_overview_presentation.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
20250228 LYD VKU AI Blended-Learning.pptx
Network Security Unit 5.pdf for BCA BBA.
Per capita expenditure prediction using model stacking based on satellite ima...
Diabetes mellitus diagnosis method based random forest with bat algorithm
A comparative analysis of optical character recognition models for extracting...
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Teaching material agriculture food technology
Reach Out and Touch Someone: Haptics and Empathic Computing
Encapsulation theory and applications.pdf
Approach and Philosophy of On baking technology
Big Data Technologies - Introduction.pptx
“AI and Expert System Decision Support & Business Intelligence Systems”
Chapter 3 Spatial Domain Image Processing.pdf
cuic standard and advanced reporting.pdf

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("john@corporation.com"); } }, 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