56
NoSQL: Azure Table Storage & MongoDB Alternativas y escenarios de uso NoSQL @erincon Click icon to add picture Click icon to add picture Click icon to add picture Eladio Rincón Director Relacional MCT, MVP SQL Server @augurarte Click icon to add picture Click icon to add picture Click icon to add picture Miguel López Director Cloud | [email protected] MCT, MCPD, MCTS, MCP 1

No SQL MSATS MongoDB | SolidQ Summit 2014

  • Upload
    solidq

  • View
    186

  • Download
    1

Embed Size (px)

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.

Citation preview

Page 1: No SQL MSATS MongoDB | SolidQ Summit 2014

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

Page 2: No SQL MSATS MongoDB | SolidQ Summit 2014

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

Page 3: No SQL MSATS MongoDB | SolidQ Summit 2014

NoSQL: Azure Table Storage & MongoDB

BDD Relacionales y NoSQLAlmacenamiento de table de Azure (MSATS)MongoDBEscenariosCostes

Page 4: No SQL MSATS MongoDB | SolidQ Summit 2014

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

Page 5: No SQL MSATS MongoDB | SolidQ Summit 2014

Donde gasta el tiempo RDBMS en TPCC

http://static.cs.brown.edu/courses/csci2270/papers/looking-glass.pdf

Page 6: No SQL MSATS MongoDB | SolidQ Summit 2014

7

Teorema de CAP

Page 7: No SQL MSATS MongoDB | SolidQ Summit 2014

8

Teorema de CAP: Selección de variables

Page 8: No SQL MSATS MongoDB | SolidQ Summit 2014

9

Next Generation Databases mostly addressing some of the points: being non-relational, distributed, open-source and horizontally scalable.

NoSQL

http://NoSQL-database.org

Page 9: No SQL MSATS MongoDB | SolidQ Summit 2014

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

Page 10: No SQL MSATS MongoDB | SolidQ Summit 2014

11

Modelos de datos NoSQL

http://www.slideshare.net/emileifrem/nosql-east-a-nosql-overview-and-the-benefits-of-graph-databases

Page 11: No SQL MSATS MongoDB | SolidQ Summit 2014

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

Page 12: No SQL MSATS MongoDB | SolidQ Summit 2014

13

DEMOhttp://nosql-database.orgBases de datos NoSQL (listado)

Icon de tecnologíaIcon de tecnologíaIcon de tecnología

Page 13: No SQL MSATS MongoDB | SolidQ Summit 2014

NoSQL: Azure Table Storage & MongoDB

BDD Relacionales y NoSQLAlmacenamiento de table de Azure (MSATS)MongoDBEscenariosCostes

Page 14: No SQL MSATS MongoDB | SolidQ Summit 2014

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

Page 15: No SQL MSATS MongoDB | SolidQ Summit 2014

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

Page 16: No SQL MSATS MongoDB | SolidQ Summit 2014

17

DEMOAprovisionamiento de una cuenta de almacenamiento de Azure

Icon de tecnologíaIcon de tecnologíaIcon de tecnología

Page 17: No SQL MSATS MongoDB | SolidQ Summit 2014

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

Page 18: No SQL MSATS MongoDB | SolidQ Summit 2014

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

Page 19: No SQL MSATS MongoDB | SolidQ Summit 2014

20

DEMOAplicaciónhttps://haveibeenpwned.com/

Icon de tecnologíaIcon de tecnologíaIcon de tecnología

Page 20: No SQL MSATS MongoDB | SolidQ Summit 2014

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)

Page 21: No SQL MSATS MongoDB | SolidQ Summit 2014

22

Entidades: Tipos de datos de propiedades

• Byte[]• Bool• DateTime• Double• Guid• Int32/Int• Int64/long• String

Page 22: No SQL MSATS MongoDB | SolidQ Summit 2014

23

Entidades: Indexación (Primary Key)

• PartitionKey property• RowKey property• Timestamp property

Page 23: No SQL MSATS MongoDB | SolidQ Summit 2014

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.

Page 24: No SQL MSATS MongoDB | SolidQ Summit 2014

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

Page 25: No SQL MSATS MongoDB | SolidQ Summit 2014

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

Page 26: No SQL MSATS MongoDB | SolidQ Summit 2014

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’

Page 27: No SQL MSATS MongoDB | SolidQ Summit 2014

28

Particiones (nodos) MSATS

Page 28: No SQL MSATS MongoDB | SolidQ Summit 2014

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)

Page 29: No SQL MSATS MongoDB | SolidQ Summit 2014

30

DEMOAcceso a un sistema MSATS en producción

Icon de tecnologíaIcon de tecnologíaIcon de tecnología

Page 30: No SQL MSATS MongoDB | SolidQ Summit 2014

31

Table Storage Design

Define your modelKey selection

Page 31: No SQL MSATS MongoDB | SolidQ Summit 2014

32

Key selection: Considerations

Entity Group TransactionsScalabilityEfficient queries

Page 32: No SQL MSATS MongoDB | SolidQ Summit 2014

33

DEMOGestión de tablas con cliente Windows

Icon de tecnologíaIcon de tecnologíaIcon de tecnología

Page 33: No SQL MSATS MongoDB | SolidQ Summit 2014

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)

Page 34: No SQL MSATS MongoDB | SolidQ Summit 2014

35

Connection Strings in Visual Studio 2013

Double click on the Web/Worker role in the solution

© 2012 SolidQ

Page 35: No SQL MSATS MongoDB | SolidQ Summit 2014

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”)

Page 36: No SQL MSATS MongoDB | SolidQ Summit 2014

37

Entidades: Operaciones CRUD

Configurar las entidades (modelo de clases)Configurar un DataContext

Page 37: No SQL MSATS MongoDB | SolidQ Summit 2014

38

Configuración de las entidadesClass modeling

Page 38: No SQL MSATS MongoDB | SolidQ Summit 2014

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

Page 39: No SQL MSATS MongoDB | SolidQ Summit 2014

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

Page 40: No SQL MSATS MongoDB | SolidQ Summit 2014

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

Page 41: No SQL MSATS MongoDB | SolidQ Summit 2014

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

);

Page 42: No SQL MSATS MongoDB | SolidQ Summit 2014

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

);

Page 43: No SQL MSATS MongoDB | SolidQ Summit 2014

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

Page 44: No SQL MSATS MongoDB | SolidQ Summit 2014

45

DEMOProgramación de MSATS

Icon de tecnologíaIcon de tecnologíaIcon de tecnología

Page 45: No SQL MSATS MongoDB | SolidQ Summit 2014

NoSQL: Azure Table Storage & MongoDB

BDD Relacionales y NoSQLAlmacenamiento de table de Azure (MSATS)MongoDBEscenariosCostes

Page 46: No SQL MSATS MongoDB | SolidQ Summit 2014

47

MongoDBMotivación

• ¿”Problemas” en RDBMs tradicionales?• Transaciones• JOINs

• Prescindimos de ellos• Transacciones a nivel de documento• No dejamos hacer JOINs

Page 47: No SQL MSATS MongoDB | SolidQ Summit 2014

48

MongoDB

Unidad de Información es el Documento

Page 48: No SQL MSATS MongoDB | SolidQ Summit 2014

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!

Page 49: No SQL MSATS MongoDB | SolidQ Summit 2014

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

Page 50: No SQL MSATS MongoDB | SolidQ Summit 2014

51

DEMOMongoDB en Azure con correos electrónicos

Icon de tecnologíaIcon de tecnologíaIcon de tecnología

Page 51: No SQL MSATS MongoDB | SolidQ Summit 2014

NoSQL: Azure Table Storage & MongoDB

BDD Relacionales y NoSQLAlmacenamiento de table de Azure (MSATS)MongoDBEscenariosCostes

Page 52: No SQL MSATS MongoDB | SolidQ Summit 2014

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

Page 53: No SQL MSATS MongoDB | SolidQ Summit 2014

NoSQL: Azure Table Storage & MongoDB

BDD Relacionales y NoSQLAlmacenamiento de table de Azure (MSATS)MongoDBEscenariosCostes

Page 54: No SQL MSATS MongoDB | SolidQ Summit 2014

55

Costes

Microsoft Azure Table Storage

MongoDB on Azure

Page 55: No SQL MSATS MongoDB | SolidQ Summit 2014

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

Page 56: No SQL MSATS MongoDB | SolidQ Summit 2014

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