tahamajs/IE / Slides /extracted_text /13-NoSQL Databases.txt
tahamajs's picture
download
raw
23 kB
--- PAGE 1 ---
NoSQL DatabasesEhsan Khamespanah
Spring 2024
--- PAGE 2 ---
Introduction to Database Transactions
•Lets start by an example
•Lost updates
•Inconsistent read
Scenario 1:
Read1(A) : A = 100
Write1(A) : A = 110
Read2(A) : A = 110
Write2(A) : A = 100
Scenario 2:
Read2(A) : A = 100
Write2(A) : A = 90
Read1(A) : A = 90
Write1(A) : A = 99
Scenario 3:
Read1(A) : A = 100
Read2(A) : A = 100
Write1(A) : A = 110
Write2(A) : A = 90
Thread 1: A = A + A * 0.1
Thread 2: A = A - 10
2
--- PAGE 3 ---
Transactions
•A bounded sequence of work
•All resources are in consistent state
•When the transaction begins and when it ends
•Must complete on an all-or-nothing basis
•ACID properties
•Atomicity: the operation cannot split down into its
individual processes. All of the actions that take place
inside it pass or fail at the same time. If any individual
operation fails, the entire transaction has been
deemed a failure and must be reversed (rolled back)
3
--- PAGE 4 ---
Transactions
•Consistency: Guaranteeing that perhaps the data
updated by the transaction conforms with all of
the column requirements, ensuring data security
•Isolation: Each transaction is kept separate from
the others, results in having no impact on
transactions that are executed simultaneously
•Durability: Data alterations that occur inside a
completed transaction may be securely regarded
to be saved in the system irrespective of what
else might follow, which helps with durability.
4
--- PAGE 5 ---
Database Transactions
•Designed for all purposes ACID
•Strong consistency, concurrency, recovery
•Mathematical background
•Standard Query language (SQL)
•Lots of tools to use with i.e: Reporting services,
entity frameworks, ...
•Vertical scaling (up scaling)
5
--- PAGE 6 ---
Relaxing Isolation for Better Performance
•SQL defines a set of reduced isolation levels
6
ptg10179753
74 CON CURRE N CY
files. An unrepeata bl e rea d allow s hi m to rea d a tota l of se ven for loc ki ng. N ext
D avid co mm its; t hen he rea ds a tota l of e igh t for m ultiphase. It ’s ca lled an unre-
peata bl e rea d because, if Mart in w ere to rerea d the tota l for t he loc ki ng pac k-
age after D avid co mm itte d, he w ou ld get t he ne w nu m ber of n ine. H is or igi na l
rea d of se ven can ’t be repeate d after D avid’ s up date. It ’s eas ier for data bases to
spot unrepeata bl e rea ds t han p hanto m s, so t he repeata bl e rea d giv es you m ore
correctness t han rea d co mm itte d but less liv eness.
The low est level of isolation is read uncomm itted , whi ch allow s dirty reads .
At rea d unco mm itte d you can rea d data t hat anot her transact ion hasn ’t actua lly
co mm itte d yet. T hi s causes t w o ki nds of errors. Mart in m igh t loo k at t he loc k-
ing pac kage wh en D avid add s the first of hi s fi les but before he a dd s the secon d.
As a resu lt he sees e igh t fi les in t he loc ki ng pac kage. T he secon d ki nd of error
co m es if D avid add s hi s fi les but t hen ro lls back hi s transact ion— in whi ch case
Mart in sees fi les t hat w ere ne ver rea lly t here.
Ta bl e 5. 1 lists t he rea d errors cause d by eac h isolation level.
To be sure of correctness you s hou ld a lw ays use t he ser ializabl e isolation
level. T he pro bl em is that c hoos ing ser ializabl e rea lly m esses up t he liv eness of a
syste m , so m uc h so t hat you often have to re duce ser ializabili ty in or der to
increase t hrou gh put. You have to decid e wh at r isks you w ant to ta ke an d m ake
your o w n tra de-off of errors versus perfor m ance.
You don ’t have to use t he sa m e isolation level for a ll transact ions, so you
shou ld loo k at eac h transact ion an d decid e how to balance liv eness versus cor-
rectness for it.
Bus iness and System Transact ions
Wh at w e’ve ta lk ed about so far, an d m ost of wh at m ost peop le ta lk about, is
wh at w e ca ll syste m transact ions, or transact ions supporte d by R D BMS sys-
tem s an d transact ion m on itors. A data base transact ion is a group of SQL co m -
Table 5 .1 Isolat ion Levels and the Incons istent Read Errors They Allow
Isolat ion Level D irty Read Unrepeatable Read Phantom
Rea d Unco mm itte d Yes Yes Yes
Rea d Co mm itte dN o Yes Yes
Repeata bl e Rea dN o N o Yes
Ser ializabl e N o N o N o
From the Library of Kyle Geoffrey Passarelli
--- PAGE 7 ---
Transaction in Practice
•What we have in JDBC
•In JPA
•Stored Procedures
7
con.setAutoCommit(boolean);
//database updates
con.commit();
con.rollback();
entityManager.getTransaction().begin();
//database updates
entityManager.getTransaction().commit();
entityManager.getTransaction().rollback();
--- PAGE 8 ---
A Brief History of Databases
8
--- PAGE 9 ---
A Brief History of Databases
A brief history of databases
4
9
--- PAGE 10 ---
Era of Distributed Computing
•Relational databases
were not built for
distributed applications.
•Because...
•Joins are expensive
•Hard to scale
horizontally
•Impedance mismatch occurs
•Expensive (product cost, hardware, maintenance)
10
--- PAGE 11 ---
Rise of Big Data
•Three V of big data: Volume, Velocity, Verity
11
--- PAGE 12 ---
Rise of Big Data
12
Rise of Big data
9
--- PAGE 13 ---
Rise of Big Data
•Walmart: 1 million transactions per hour
•Facebook: 40 billion
photos
•People are talking
about petabytes
today
13
--- PAGE 14 ---
NoSQL why, what and when?
•Google & Amazon built their own databases (Big
table & Dynamo) Facebook invented Cassandra and
is using thousands of them
•#NoSQL was a twitter hashtag for a conference in
2009
•The name doesn’t indicate its characteristics
•There is no strict definition for NoSQL databases
•There are more than 150 NoSQL
databases (nosql-database.org)
14
--- PAGE 15 ---
Characteristics of NoSQL Databases
•Non relational
•Cluster friendly
•Schema-less
•21 century web
•Open-source
15
--- PAGE 16 ---
Characteristics of NoSQL Databases
•NoSQL avoids:
•Overhead of ACID transactions
•Complexity of SQL query
•Burden of up-front schema design
•DBA presence
•Transactions (It should be handled at application layer)
•Provides:
•Easy and frequent changes to DB
•Horizontal scaling (scaling out)
•Solution to Impedance mismatch
•Fast development
16
--- PAGE 17 ---
Schema-Based Data Model
•You can’t add a record which does not fit the
schema
•You need to add NULLs to unused items in a row
•We should consider the datatypes. i.e : you can’t
add a string to an integer field
•You can’t add multiple items in a field (You should
create another table: primary-key, foreign key, joins,
normalization, ... !!!)
17
--- PAGE 18 ---
There is No … in NoSQL Databases
•No schema to consider
•No unused cell
•No datatype (implicit)
•Most of considerations
are done in application layer
•Items are gathered in
an aggregate (document)
18
--- PAGE 19 ---
What is Aggregation?
•The term comes from Domain Driven Design
•Shared nothing architecture
•An aggregate is a cluster of domain objects that can
be treated as a single unit
•Aggregates are the basic element of transfer of data
storage - you request to load or save whole
aggregates
•Transactions should not cross aggregate boundaries
•This mechanism reduces the join operations to a
minimal level
19
--- PAGE 20 ---
An Example of Aggregation
20
--- PAGE 21 ---
An Example of Aggregation
21
--- PAGE 22 ---
Four Major Aggregate Data Models
22
--- PAGE 23 ---
Key-Value Data Model
•The main idea is the use of a hash table
•Access data (values) by strings called keys
•Data has no required format – data may have any
format
•Data model: (key, value) pairs
•Basic Operations:
•Insert(key,value),
Fetch(key),
Update(key),
Delete(key)
23
Key-value data model
X The main idea is the use of a hash table
X Access data (values) by strings called keys
X Data has no required format –data may have any format
X Data model: (key, value) pairs
X Basic Operations:
Insert(key,value ), Fetch(key),Update(key), Delete(key )
22
--- PAGE 24 ---
Key-Value Data Model
•Value is stored as a “blob”
•Without caring or knowing what is inside
•Application is responsible for understanding the
data
•Main observation from Amazon (using Dynamo)
•“There are many services on Amazon’s platform
that only need primary-key access to a data store.”
•E.g. Best seller lists, shopping carts, customer
preferences, session management, sales rank,
product catalog
24
--- PAGE 25 ---
Hazelcast
•Hazelcast IMDG is an open source in-memory data
grid based on Java.
•A Data Grid is a system of multiple servers that work
together to manage information and related
operations in a distributed environment.
25
--- PAGE 26 ---
Using IMDG Results in:
•Performance increase: One of the best advantages
of an In-Memory Data Grid is the increase in the
entire system performance.
•Data structure: the data structure itself is a simple
key-value store, rather than a complex relational
model (still providing ACID properties)
•Operations: from an operational perspective, we
already saw how an IMDG can be scaled up and
down and how redundancy is built-in, which will
allow us to easily achieve a highly-available system.
26
--- PAGE 27 ---
Connecting to the IMDG
•Connecting to two instances
•Data Manipulation
27
Config config = new Config();
HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);
import com.hazelcast.core.*; !
import java.util.ConcurrentMap;!
Map<String, Customer> map = hazelcast.getMap(“customers");
map.put ("1", customer);
Customer c = map.get("1");
//ConcurrentMap methods!
map.putIfAbsent ("2", new Customer("Chuck Norris”));
map.replace ("3", new Customer("Bruce Lee"));
--- PAGE 28 ---
Transactions
28
import com.hazelcast.core.*; import java.util.*;
TransactionOptions options = new
TransactionOptions().setTransactionType(TransactionType.TWO_PHASE);
TransactionContext context = hz.newTransactionContext(options);
context.beginTransaction();
TransactionalQueue queue = context.getQueue(“myqueue");
TransactionalMap map = context.getMap(“mymap");
TransactionalSet set = context.getSet("myset");
try {
Object obj = queue.poll();
//process obj
map.put ("1", "value1");
set.add ("value");
//do other things..
context.commitTransaction();
}catch (Throwable t) {
context.rollbackTransaction();
}
--- PAGE 29 ---
•Java MapStore and MapLoader interfaces to
implement a custom MapStore with your own logic,
loading data from a data store, and writing data to a
data store.
•MapLoader: The methods on the MapLoader
interface get invoked when the application requests a
value from the map
•MapStore: The methods on the MapStore interface
can also replicate updates made to a map to the data
store. This replication can be implemented blocking
(write-through) or non-blocking (write-behind)
29
--- PAGE 30 ---
Column Family Data Model
•The column is
lowest/smallest
instance of data.
•It is a tuple that
contains a name,
a value and a
timestamp
30
Column family data model
X The column is lowest/smallest instance of
data.
X It is a tuple that contains a name, a value
and a timestamp
24
--- PAGE 31 ---
Column Family Data Model
Some statistics about Facebook Search (using Cassandra)
•MySQL > 50 GB Data
•Writes Average : ~300 ms
•Reads Average : ~350 ms
•Rewritten with Cassandra > 50 GB Data
•Writes Average : 0.12 ms
•Reads Average : 15 ms
31
--- PAGE 32 ---
Graph Data Model
•Based on Graph Theory.
•Scale vertically, no clustering.
•You can use graph algorithms easily
•Transactions ACID
32
--- PAGE 33 ---
Document-Based Data Model
•Usually JSON like interchange model.
•Query Model: JavaScript-like or custom.
•Aggregations: Map/Reduce
•Indexes are done via B-Trees.
•Unlike simple key-value stores, both keys and values
are fully searchable in document databases.
33
--- PAGE 34 ---
Connecting to MongoDB
•Very similar to connecting to RDBMS
•But there is an easy to use option for connecting to
a cluster of servers
34
MongoClient mongoClient = MongoClients.create(“user:pass//localhost:27017");
MongoClient mongoClient = new MongoClient("db1.server.com", 27018);
MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder()
.applyToClusterSettings(builder ->
builder.hosts(Arrays.asList(
new ServerAddress("host1", 27017),
new ServerAddress("host2", 27017))))
.build()
);
--- PAGE 35 ---
Connecting to MongoDB
•Databases and Collections
•Security
35
//database instance
MongoDatabase database = mongoClient.getDatabase("test");
//collection instance
MongoCollection<Document> collection = database.getCollection("col1");
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("test");
char[] password = new char[] {'s', 'e', 'c', 'r', 'e', 't'};
boolean authenticated = db.authenticate("root", password);
if (authenticated) {
System.out.println("Successfully logged in to MongoDB!");
} else {
System.out.println("Invalid username/password");
}
--- PAGE 36 ---
Collections Manipulation
•Creating a collection
•Define document validations
•Drop a collection
36
database.createCollection("cappedCollection",
new CreateCollectionOptions().capped(true).sizeInBytes(0x100000));
ValidationOptions collOptions = new ValidationOptions().validator(
Filters.or(Filters.exists("email"), Filters.exists("phone")));
database.createCollection("contacts",
new CreateCollectionOptions().validationOptions(collOptions));
MongoCollection<Document> collection = database.getCollection("contacts");
collection.drop();
--- PAGE 37 ---
Defining Indexes
•Ascending, descending, and compound indexes
•Unique and partial indexes (only index valid documents)
37
collection.createIndex(Indexes.ascending("name"));
collection.createIndex(Indexes.ascending("stars", "name"));
collection.createIndex(Indexes.descending("stars", "name"));
collection.createIndex(Indexes.compoundIndex(Indexes.descending("stars"),
Indexes.ascending("name")));
IndexOptions indexOptions = new IndexOptions().unique(true);
collection.createIndex(Indexes.ascending("name", "stars"), indexOptions);
IndexOptions partialFilterIndexOptions = new IndexOptions()
.partialFilterExpression(Filters.exists("contact.email"));
collection.createIndex(
Indexes.descending("name", "stars"), partialFilterIndexOptions);
--- PAGE 38 ---
Different Types of Indexes
•Traditional text and hashed indexes
•Location-Based indexes which their efficiencies is
based on the nature of data and queries
38
collection.createIndex(Indexes.geo2dsphere("contact.location"));
collection.createIndex(Indexes.geo2d("contact.location"));
IndexOptions haystackOption = new IndexOptions().bucketSize(1.0);
collection.createIndex(
Indexes.geoHaystack("contact.location", Indexes.ascending("stars")),
haystackOption);
collection.createIndex(Indexes.text(“name"));
collection.createIndex(Indexes.hashed("_id"));
--- PAGE 39 ---
Query a Collection
•Finding documents by passing a filter as a criteria
•More complex criteria: the stars field is greater than
or equal to 2 and less than 5, AND the categories
field equals "Bakery" (or if categories is an array,
contains the string "Bakery" as an element):
39
FindIterable<Document> result = collection.find(eq("name", "456 Cookies Shop"));
collection.find(
new Document("stars", new Document("$gte", 2)
.append("$lt", 5))
.append("categories", "Bakery"));
import static com.mongodb.client.model.Filters.*;
collection.find(and(gte("stars", 2), lt("stars", 5),
eq("categories", “Bakery")));
--- PAGE 40 ---
Projection
•Queries in MongoDB return all fields in matching
documents.
•Specify a projection document to return the needed
fields
•The following includes a projection Document which
specifies that the matching documents return only
the name field, stars field, and the categories field.
40
import static com.mongodb.client.model.Projections.*;
collection.find(and(gte("stars", 2), lt("stars", 5), eq(“categories",
“Bakery"))
).projection(fields(include("name", "stars", "categories"), excludeId()));
--- PAGE 41 ---
Iterating the Result
•Sorting the result
•MongoIterable: iterator(), first(), forEach(), map(),
into()
41
collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories",
“Bakery"))
).sort(Sorts.ascending(“name"));
Block<Document> printBlock = new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document.toJson());
}
};
collection.find(and(gte("stars", 2), lt("stars", 5), eq("categories",
“Bakery"))
).sort(Sorts.ascending(“name”)).forEach(printBlock);
--- PAGE 42 ---
Writing to a Collection
•Inserting a document in a collection
•Inserting a set of documents
42
Document document = new Document("name", "Café Con Leche")
.append("contact", new Document("phone", "228-555-0149")
.append("email", "cafeconleche@example.com")
.append(“location", Arrays.asList(-73.92502, 40.8279556))
)
.append("stars", 3)
.append("categories", Arrays.asList("Bakery", "Coffee", “Pastries")
);
collection.insertOne(document);
Document doc1 = ...
Document doc2 = ...
List<Document> documents = new ArrayList<Document>();
documents.add(doc1);
documents.add(doc2);
collection.insertMany(documents);
--- PAGE 43 ---
Updating Documents
•updateOne(): updates at most a single document,
even if multiple documents can be matched
•Updating the restaurants collection whose _id is
ObjectId("57506d62f57802807471dd41")
•using “set” to set the value of stars to 1 and
contact.phone to "228-555-9999"
•using “currentDate” to modify the lastModified
field to the current date.
43
collection.updateOne(
eq("_id", new ObjectId("57506d62f57802807471dd41")),
combine(set("stars", 1), set("contact.phone", "228-555-9999"),
currentDate(“lastModified"))
);
--- PAGE 44 ---
Updating Documents
•updateMany(): updates at most a single document,
even if multiple documents can be matched
•Updating options
•upsert: insert if there is no match
•bypassDocumentValidation: ignore validation
44
collection.updateMany(
eq("stars", 2),
combine(set("stars", 0), currentDate(“lastModified"))
);
collection.updateOne(
eq("_id", 1),
combine(set("name", "Tulips"), currentDate("lastModified")),
new UpdateOptions().upsert(true).bypassDocumentValidation(true));
--- PAGE 45 ---
Replacing Document
•ReplaceOne(): replaces the entire document - fields
in the old document not contained in the new will
be lost
•You are allowed to update options( i.e. upsert and
bypassDocumentValidation)
45
collection.replaceOne(
eq("_id", new ObjectId("57506d62f57802807471dd41")),
new Document("name", "Green Salads Buffet")
.append("contact", "TBD")
.append("categories", Arrays.asList("Salads", "Health
Foods", “Buffet")
)
);
--- PAGE 46 ---
Delete Documents
•Delete one document
•Delete many documents
46
collection.deleteOne(eq("_id", new ObjectId("57506d62f57802807471dd41")));
collection.deleteMany(eq("stars", 4));
--- PAGE 47 ---
Write Concerns
•WriteConcern.ACKNOWLEDGED
47
WriteConcern.ACKNOWLEDGED
--- PAGE 48 ---
Write Concerns
•WriteConcern.ACKNOWLEDGED
•WriteConcern.UNACKNOWLEDGED
48
WriteConcern.UNACKNOWLEDGED
--- PAGE 49 ---
Write Concerns
•WriteConcern.ACKNOWLEDGED
•WriteConcern.UNACKNOWLEDGED
•WriteConcern.JOURNALED
49
WriteConcern.JOURNALED
--- PAGE 50 ---
Write Concerns
•WriteConcern.ACKNOWLEDGED
•WriteConcern.UNACKNOWLEDGED
•WriteConcern.JOURNALED
•WriteConcern.
REPLICA_ACKNOWLEDGED
50
WriteConcern.REPLICA_ACKNOWLEDGED
--- PAGE 51 ---
Write Concerns
•WriteConcern.ACKNOWLEDGED
•WriteConcern.UNACKNOWLEDGED
•WriteConcern.JOURNALED
•WriteConcern.REPLICA_ACKNOWLEDGED
•WriteConcern.MAJORITY;
51
MongoClientOptions options =
MongoClientOptions.builder().writeConcern(WriteConcern.MAJORITY).build();
MongoClient mongoClient = new MongoClient(Arrays.asList(
new ServerAddress("host1", 27017),
new ServerAddress("host1", 27018)), options
);
--- PAGE 52 ---
What We Need?
•We need a distributed database system having such
features:
•Fault tolerance
•High availability
•Consistency
•Scalability
•Which is impossible!!! According to CAP theorem
52
--- PAGE 53 ---
CAP Theorem
•This theorem explains that it is not possible to guarantee
three properties, consistency, availability, and partition
tolerance at the same time in a distributed system with
data replication
•Consistency: Every read receives the most recent write or
an error among replicated copies.
•Availability: Every request receives a (non-error) response,
without the guarantee for containing the most recent write.
•Partition tolerance: The system continues to operate in the
case that nodes in the system being partitioned by a
network fault.
53
--- PAGE 54 ---
54
--- PAGE 55 ---
Thinking Differently
•In some cases getting an answer quickly is more
important than getting a correct answer
•By giving up ACID properties, one can achieve
higher performance and scalability.
•Any data store can achieve Atomicity, Isolation and
Durability but do you always need consistency?
•Maybe we should implement Asynchronous Inserts
and updates and should not wait for confirmation?
55
--- PAGE 56 ---
BASE
•Almost the opposite of ACID.
•Basically available: Nodes in the a distributed
environment can go down, but the whole system
shouldn’t be affected.
•Soft State (scalable): The state of the system and
data changes over time.
•Eventual Consistency: Given enough time, data will
be consistent across the distributed system.
56
--- PAGE 57 ---
ACID vs. BASE
•ACID
•Strong consistency
•Less availability
•Pessimistic concurrency
•Complex
•BASE
•Availability is the most important thing. Willing to
sacrifice for this (CAP)
•Weaker consistency (Eventual)
•Best effort
•Simple and Fast
•Optimistic
57
--- PAGE 58 ---
PolyglotPersistence
58
Polyglot persistence : the future of database
systems
ƒFuture databases are the combination of SQL & NoSQL
ƒWe still need relational databases
45

Xet Storage Details

Size:
23 kB
·
Xet hash:
df25c6e59af79f6ac821f1063b8dffc967a02b8ab6f7a15459202de8e9fb18b8

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.