no sql msats mongodb | solidq summit 2014
DESCRIPTION
http://summit.solidq.com En un track de motor relacional una sesión NoSQL puede resultar extraña. En esta sesión mostraremos cómo funcionan estas tecnologías con dos aproximaciones diferentes: almacenamiento clave-valor en la nube (Azure) y almacenamiento orientado a documento (MongoDB). Evaluaremos y debatiremos sobre las dos tecnologías y su uso adecuado. Presentación realizada por Miguel López y Eladio Rincón.TRANSCRIPT
NoSQL: Azure Table Storage & MongoDBAlternativas y escenarios de uso NoSQL
@erincon
Click icon to add pictureClick icon to add pictureClick icon to add picture
Eladio Rincón
Director Relacional
MCT, MVP SQL Server
@augurarte
Click icon to add pictureClick icon to add pictureClick icon to add picture
Miguel López
Director Cloud | [email protected]
MCT, MCPD, MCTS, MCP
1
3
Agenda
1. Bases de datos relacionales y NoSQL2. Microsoft Azure Table Storage– Fundamentos MSATS– Diseño de NoSQL con MSATS– Programación del modelo
3. MongoDB– Fundamentos– Diseño de NoSQL con MongoDB– Programación del modelo
4. Escenarios5. Evaluación de costes
NoSQL: Azure Table Storage & MongoDB
BDD Relacionales y NoSQLAlmacenamiento de table de Azure (MSATS)MongoDBEscenariosCostes
5
BDD Relacionales y NoSQL
Las BDD Relacionales lideran el conjunto de sistemas de almacenamiento transaccional, escritura atómica, indexación de columnas, optimización de consultas y lenguaje de consulta declarative orientado a conjuntos.
Las BDD NoSQL se emplean de forma generalizada en sitios Web de tipo social masivamente accedidos y que necesitan escalar de forma intensiva, donde la característica principal son conjuntos de datos simples (frente a consultas complejas)
© 2012 SolidQ
Donde gasta el tiempo RDBMS en TPCC
http://static.cs.brown.edu/courses/csci2270/papers/looking-glass.pdf
7
Teorema de CAP
8
Teorema de CAP: Selección de variables
9
Next Generation Databases mostly addressing some of the points: being non-relational, distributed, open-source and horizontally scalable.
NoSQL
http://NoSQL-database.org
10
• Surgen a principios de 2009• Crecimiento exponencial. • Características comunes más importantes:
• No se basan en esquema• Soporte de replicación sencillo• API de fácil utilización• Consistencia parcial (eventually consistent) / BASE (not
ACID)• Enormes cantidades de información.
• "nosql" es traducido tradicionalmente como "not only sql“, y se considera un alias que referencia la definición anterior.
NoSQL Evolución y características
11
Modelos de datos NoSQL
http://www.slideshare.net/emileifrem/nosql-east-a-nosql-overview-and-the-benefits-of-graph-databases
12
• Wide Column Store / Column Families• Document Store• Key Value / Tuple Store• Graph Databases• Multimodel Databases• Object Databases• Grid & Cloud Database Solutions• XML Databases• Multidimensional Databases• Multivalue Databases• Event Sourcing• Network Model
Grandes familias NoSQL
13
DEMOhttp://nosql-database.orgBases de datos NoSQL (listado)
Icon de tecnologíaIcon de tecnologíaIcon de tecnología
NoSQL: Azure Table Storage & MongoDB
BDD Relacionales y NoSQLAlmacenamiento de table de Azure (MSATS)MongoDBEscenariosCostes
15
Almacenamiento de table Azure
Windows Azure Table ServiceWindows Azure tablesDesigning Windows Azure TablesImplementing Windows Azure TablesQuerying Windows Azure TablesAccessing table storageTable Storage Security– Set container permissions.– Use Shared Access Signatures (SAS)– Stored Access Policies
16
Cuentas de almacenamiento MSA
User creates a globally unique storage account nameChoose the primary location to host storage accountThree regions:– “North Central US”, “South Central US”– “North Europe”, “Europe West”– “South East Asia”, “East Asia”
Table Service:
http://myaccount.table.core.windows.net
17
DEMOAprovisionamiento de una cuenta de almacenamiento de Azure
Icon de tecnologíaIcon de tecnologíaIcon de tecnología
18
Características MSATS• Tabla de almacenamiento de Azure• Colección de entidades (parejas clave, valor)• La entidad tiene una clave principal y un conjunto
aleatorio no definido (schema-less) de propiedades. • PartitionKey (Particionamiento / distribución de carga / escalado)
• RowKey (conjuntos de filas relacionadas en una partición)
• TimeStamp (Sólo lectura, TS creación)
• Una propiedad es un par de nombre/valor (con tipo) similar a una columna
• MSATS no fuerza la creación o validación de esquema• El desarrollador necesitará implementar un esquema
concreto para su acceso
Abstracciones MSATS
EntityTableAccount
ICTGlobal
PartitionKey = SWITZERLANDRowKey = GENEVABuildingName = 13_CornavinHeigh = 47
GE06LMet
GR7B4Ant
19
PartitionKey = SPAINRowKey = ALBACETEBuildingName = 02_CathedralAddress = “RueGeneve 15”
PartitionKey = TERRESTRIALRowKey = AFRICA_KENIAFrequency = 313Hz
20
DEMOAplicaciónhttps://haveibeenpwned.com/
Icon de tecnologíaIcon de tecnologíaIcon de tecnología
21
Entidades del MSATS
Entities are the basic data item stored in a tableCollections of properties that are name value pairs. Each entity has 3 fixed properties called PartitionKey, RowKey and Timestamp. If we were to map this to concepts in a conventional database system, an entity is analogous to a row and property is analogous to a column.An entity can have up to 255 – 3 properties = 252 (3 system properties are reserved). 1 Entity = 1 MB of data (Maximum)
22
Entidades: Tipos de datos de propiedades
• Byte[]• Bool• DateTime• Double• Guid• Int32/Int• Int64/long• String
23
Entidades: Indexación (Primary Key)
• PartitionKey property• RowKey property• Timestamp property
24
Características de las propiedades PK
• Tablas particionadas para soportar balanceo de carga entre nodos de almacenamiento.
• Las entidades se organizan por partición. • Una partición es un rango consecutive de
entidades con la misma clave de partición. • Partition key: Identificador único de partición
dentro de una tabla. • PK es la primera parte de la clave principal de una
entidad. • PK puede ser una cadena de hasta 1KB de tamaño.• Incluir PartitionKey property en cada insert,
update, y delete.
25
Características de las propiedades RowKey
• The row key is a unique identifier for an entity within a given partition.
• Together the PartitionKey and RowKey uniquely identify every entity within a table.
• The row key is a string value that may be up to 1 KB in size.
• You must include the RowKey property in every insert, update, and delete operation.
RowKey
26
MSATS es una BDD sin esquema
PartitionKey: str
2012102517USR91
PV
RowKey: str
jobid0121
PV
TimeStamp: dt
201210251715
PV
Name: st
User_91
PV
PartitionKey: str
2012102517USR10
PV
RowKey: str
jobid0121
PV
TimeStamp: dt
201210251735
PV
Status: st
Processing
PV
Name: st
User_10
PV
PartitionKey: str
2012102517USR10
P
V
RowKey: str
jobid0125
P
V
TimeStamp: dt
201210251755
P
V
RoleExec: st
IN_121
P
V
Name: st
User_10
P
V
LastOp: st
Decrypt
P
V
PartitionKey: str
2012102517USR13
P
V
RowKey: str
jobid0002
P
V
TimeStamp: dt
201210251759
P
V
Name: st
User_13
P
V
PartitionKey: str
2012102517USR13
PV
RowKey: str
jobid0001
PV
TimeStamp: dt
201210251755
PV
Name: st
User_13
PV
Status: st
Aborted
PV
TABLE JOBEXECUTION
27
Consulta del servicio de tabla
PartitionKey: str
2012102517USR91
PV
RowKey: str
jobid0121
PV
TimeStamp: dt
201210251715
PV
Name: st
User_91
PV
PartitionKey: str
2012102517USR10
PV
RowKey: str
jobid0121
PV
TimeStamp: dt
201210251735
PV
Status: st
Processing
PV
Name: st
User_10
PV
PartitionKey: str
2012102517USR10
P
V
RowKey: str
jobid0125
P
V
TimeStamp: dt
201210251755
P
V
RoleExec: st
IN_121
P
V
Name: st
User_10
P
V
LastOp: st
Decrypt
P
V
PartitionKey: str
2012102517USR13
P
V
RowKey: str
jobid0002
P
V
TimeStamp: dt
201210251759
P
V
Name: st
User_13
P
V
PartitionKey: str
2012102517USR13
PV
RowKey: str
jobid0001
PV
TimeStamp: dt
201210251755
PV
Name: st
User_13
PV
Status: st
Aborted
PV
TABLE JOBEXECUTION
?$filter=Name eq ‘User_10’
28
Particiones (nodos) MSATS
PARTITIONKEY(CATEGORY)
ROWKEY(TITLE)
TIMESTAMP MODELYEAR
BikesSuper Duper Cycle
… 2009
BikesQuick Cycle 200 Deluxe
… 2007
… … … …
Canoes Whitewater … 2009
Canoes Flatwater … 2006
PARTITIONKEY(CATEGORY)
ROWKEY(TITLE)
TIMESTAMP MODELYEAR
Rafts14ft Super Tourer
… 1999
… … … …
SkisFabrikam Back Trackers
… 2009
… … … …
Tents Super Palace … 2008
PARTITIONKEY(CATEGORY)
ROWKEY(TITLE)
TIMESTAMP MODELYEAR
BikesSuper Duper Cycle
… 2009
BikesQuick Cycle 200 Deluxe
… 2007
… … … …
Canoes Whitewater … 2009
Canoes Flatwater … 2006
Rafts14ft Super Tourer
… 1999
… … … …
SkisFabrikam Back Trackers
… 2009
… … … …
Tents Super Palace … 2008
Partitions and Partition Ranges
Server A
Table = Products
Server B
Table = Products[Canoes - MaxKey)
Server A
Table = Products[MinKey - Canoes)
30
DEMOAcceso a un sistema MSATS en producción
Icon de tecnologíaIcon de tecnologíaIcon de tecnología
31
Table Storage Design
Define your modelKey selection
32
Key selection: Considerations
Entity Group TransactionsScalabilityEfficient queries
33
DEMOGestión de tablas con cliente Windows
Icon de tecnologíaIcon de tecnologíaIcon de tecnología
34
Modelo de programación
Windows Azure Storage: Connection StringsManaging tables in WATSEntities: CRUD operations (Create, read, update, delete)Querying tablesPerform Entity Group Transactions (EGT)
35
Connection Strings in Visual Studio 2013
Double click on the Web/Worker role in the solution
© 2012 SolidQ
36
Managing tables in WATS
Use Microsoft.WindowsAzure.StorageClient. There are several ways of creating tables. Initialize tables once: for example using session or Application start events.Use CreateCloudTableClient to interact with WATSFor example, to create a table called ‘Products’:
using Microsoft.WindowsAzure;using Microsoft.WindowsAzure.StorageClient;
var clAccount;clAccount = CloudStorageAccount.FromConfigurationSettings(“ProductStorage") var tableClient = clAccount.CreateCloudTableClient();tableClient.CreateTableIfNotExists(“Products”)
37
Entidades: Operaciones CRUD
Configurar las entidades (modelo de clases)Configurar un DataContext
38
Configuración de las entidadesClass modeling
39
Operaciones CRUD
Context class is required in .NET to access the WAT using WCF Data Services and the correspondent entity (GE06LDataEntry).
Setting up data context
namespace GE06L_Data {
public class GE06LDataContext : TableServiceContext {public GE06LDataContext(string baseAddress, Microsoft.WindowsAzure.StorageCredentials credentials) : base(baseAddress, credentials) {}
public IQueryable<GE06LEntry> GE06LEntry {get { return this.CreateQuery<GE06LEntry>(“GE06LEntry");} } }}
40
Entities CRUD operationsList, Add, Update
// List (read) operation for GE06LEntry entitiespublic IEnumerable<GE06LEntry> GetGE06LEntries() {var results = from g in this.context.GE06LEntry where g.PartitionKey == DateTime.UtcNow.ToString("MMddyyyy") select g; return results; }
// Add operation for GE06LEntry entities
public void AddGE06LEntry(GE06LEntry newItem) {this.context.AddObject(“GE06LEntry", newItem);this.context.SaveChanges(); }
// Update operation for GE06LEntry entities
public void UpdateFileURL(string partitionKey, string rowKey, string fileUrl) { var results = from g in this.context.GE06LEntry where g.PartitionKey == partitionKey && g.RowKey == rowKey
select g; var entry = results.FirstOrDefault<GE06LEntry>(); entry.FilelUrl = fileUrl; this.context.UpdateObject(entry); this.context.SaveChanges(); }
41
Consultar MSATSSingle Entity (a.k.a. Point Queries)
var q = (
from pais in context.CreateQuery<Pais>(tableName)
where pais.PartitionKey == “Paises“ &&
pais.RowKey == “España"
select movie);
42
Consultar MSATSRange Queries - Row Range Scan
© 2012 SolidQ
var q = (
from movie in context.CreateQuery<Movie>(tableName)
where
movie.PartitionKey == "Action" &&
movie.RowKey.CompareTo("Alien") >= 0 &&
movie.RowKey.CompareTo("Terminator") <= 0 &&
movie.IsFavorite
select movie
);
43
Consultar MSATSRange Queries - Partition Range Scan
var q = (
from movie in context.CreateQuery<Movie>(tableName)
where
movie.PartitionKey == "Action" &&
movie.RowKey.CompareTo("Alien") >= 0 &&
movie.RowKey.CompareTo("Terminator") <= 0 &&
movie.IsFavorite
select movie
);
44
Consultar MSATSFull Table Scan
var q = (from movie in context.CreateQuery<Movie>(tableName)
select movie );
var q = (from movie in context.CreateQuery<Movie>(tableName)
where movie.PartitionKey.CompareTo("Action") != 0
select movie );
var q = (
from movie in context.CreateQuery<Movie>(tableName)
where movie.IsFavorite select movie); var q =
(from movie in context.CreateQuery<Movie>(tableName)
where movie.RowKey.CompareTo("Sh") >= 0 &&
movie.RowKey.CompareTo("Si") < 0
select movie );
45
DEMOProgramación de MSATS
Icon de tecnologíaIcon de tecnologíaIcon de tecnología
NoSQL: Azure Table Storage & MongoDB
BDD Relacionales y NoSQLAlmacenamiento de table de Azure (MSATS)MongoDBEscenariosCostes
47
MongoDBMotivación
• ¿”Problemas” en RDBMs tradicionales?• Transaciones• JOINs
• Prescindimos de ellos• Transacciones a nivel de documento• No dejamos hacer JOINs
48
MongoDB
Unidad de Información es el Documento
49
MongoDB: Otro Paradigma
• Filosofía Schema On-Read• El Esquema es importante (aunque laxo)• En algún momento necesitas “modelar”• Antes o después
• Modelos Mapeados en Memoria• “Cerveza con alcohol vs cerveza sin
alcohol” by Garrigós• Importante arquitectura x64!
50
MongoDB: Conceptos Clave
• Aunque veamos JSON, almacenado en binario – BSON
• Consola de administración JavaScript y JSON• Varios GUI tipo SSMS• Drivers de Mongo para facilitar desarrollo
• Driver para C# y usar LINQ• Modelos de persistencia para mapeo• MongoRepository
• Sharding y Replicasets
51
DEMOMongoDB en Azure con correos electrónicos
Icon de tecnologíaIcon de tecnologíaIcon de tecnología
NoSQL: Azure Table Storage & MongoDB
BDD Relacionales y NoSQLAlmacenamiento de table de Azure (MSATS)MongoDBEscenariosCostes
53
Aplicaciones altamente escalables que necesitan consultas sencillas y rápidas• ONU, datos georeferenciados, info calculada• Energética, metadatos• BIG Data, datos temporales/sensores• Información social / redes sociales• Aplicaciones de localización de correos,
direcciones, etc.
Escenarios
NoSQL: Azure Table Storage & MongoDB
BDD Relacionales y NoSQLAlmacenamiento de table de Azure (MSATS)MongoDBEscenariosCostes
55
Costes
Microsoft Azure Table Storage
MongoDB on Azure
56
NoSQL: Azure Table Storage & MongoDB
Bases de datos relacionales y NoSQLMicrosoft Azure Table Storage– Fundamentos MSATS– Diseño de NoSQL con MSATS– Programación del modelo
MongoDB– Fundamentos – Diseño de NoSQL con MongoDB– Programación del modelo
EscenariosEvaluación de costes
Si quieres disfrutar de las mejores sesiones de nuestros mentores de España y Latino
América, ésta es tu oportunidad.
http://summit.solidq.com
Síguenos:
58