no-sql, azure table storage y mongodb

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

Upload: eladio-rincon-herrera

Post on 23-Jul-2015

91 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: No-SQL, Azure Table Storage y MongoDB

NoSQL: Azure Table Storage & MongoDB

Alternativas y escenarios de uso NoSQL

@erincon Eladio Rincón

Director Relacional

MCT, MVP SQL Server

@augurarte Miguel López

Director Cloud | [email protected]

MCT, MCPD, MCTS, MCP

1

Page 2: No-SQL, Azure Table Storage y MongoDB

EN CUMPLIMIENTO CON LA LEY 15/1999 DE PROTECCION DE DATOS DE

CARÁCTER PERSONAL, PONEMOS EN TU CONOCIMIENTO QUE

ESTA SESIÓN VA A SER GRABADA

POR SOLIDQ Y QUE ESTA GRABACIÓN PODRÍA SER UTILIZADA COMO MATERIAL

DE MARKETING Y HACERSE PUBLICA A TRAVÉS DE DIVERSOS MEDIOS, COMO

POR EJEMPLO NUESTRA PAGINA WEB.

TENIENDO EN CUENTA QUE TU IMAGEN PUEDE APARECER EN ESA GRABACIÓN,

SI NO DESEAS APARECER, ROGAMOS NOS LO COMUNIQUES POR LOS MEDIOS

QUE YA CONOCES.

COMUNICADO

2

Page 3: No-SQL, Azure Table Storage y MongoDB

Agenda

Bases de datos relacionales y NoSQL

Microsoft 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

Escenarios

Evaluación de costes

3

Page 4: No-SQL, Azure Table Storage y MongoDB

NoSQL: Azure Table Storage & MongoDB

BDD Relacionales y NoSQL

Almacenamiento de table de Azure (MSATS)

MongoDB

Escenarios

Costes

Page 5: No-SQL, Azure Table Storage y MongoDB

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)

5© 2012 SolidQ

Page 6: No-SQL, Azure Table Storage y MongoDB

Donde gasta el tiempo RDBMS en TPCC

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

Page 7: No-SQL, Azure Table Storage y MongoDB

Teorema de CAP

7

Page 8: No-SQL, Azure Table Storage y MongoDB

Teorema de CAP: Selección de variables

8

Page 9: No-SQL, Azure Table Storage y MongoDB

Next Generation Databases mostly addressing

some of the points: being non-relational,

distributed, open-source and horizontally

scalable.

NoSQL

9http://NoSQL-database.org

Page 10: No-SQL, Azure Table Storage y MongoDB

• 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

10

Page 11: No-SQL, Azure Table Storage y MongoDB

Modelos de datos NoSQL

11

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

Page 12: No-SQL, Azure Table Storage y MongoDB

• 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

12

Page 13: No-SQL, Azure Table Storage y MongoDB

DEMO

13

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

Page 14: No-SQL, Azure Table Storage y MongoDB

NoSQL: Azure Table Storage & MongoDB

BDD Relacionales y NoSQL

Almacenamiento de table de Azure (MSATS)

MongoDB

Escenarios

Costes

Page 15: No-SQL, Azure Table Storage y MongoDB

Almacenamiento de table Azure

Windows Azure Table Service

Windows Azure tables

Designing Windows Azure Tables

Implementing Windows Azure Tables

Querying Windows Azure Tables

Accessing table storage

Table Storage Security

– Set container permissions.

– Use Shared Access Signatures (SAS)

– Stored Access Policies

15

Page 16: No-SQL, Azure Table Storage y MongoDB

Cuentas de almacenamiento MSA

User creates a globally unique storage account name

Choose the primary location to host storage account

Three regions:

– “North Central US”, “South Central US”

– “North Europe”, “Europe West”

– “South East Asia”, “East Asia”

Table Service:

http://myaccount.table.core.windows.net

16

Page 17: No-SQL, Azure Table Storage y MongoDB

DEMO

17

Aprovisionamiento de una cuenta de almacenamiento de Azure

Page 18: No-SQL, Azure Table Storage y MongoDB

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

18

Page 19: No-SQL, Azure Table Storage y MongoDB

Abstracciones MSATS

19

Page 20: No-SQL, Azure Table Storage y MongoDB

DEMO

20

Aplicaciónhttps://haveibeenpwned.com/

Page 21: No-SQL, Azure Table Storage y MongoDB

Entidades del MSATS

Entities are the basic data item stored in a table

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

21

Page 22: No-SQL, Azure Table Storage y MongoDB

Entidades: Tipos de datos de propiedades

• Byte[]

• Bool

• DateTime

• Double

• Guid

• Int32/Int

• Int64/long

• String

22

Page 23: No-SQL, Azure Table Storage y MongoDB

Entidades: Indexación (Primary Key)

• PartitionKey property

• RowKey property

• Timestamp property

23

Page 24: No-SQL, Azure Table Storage y MongoDB

Características de las propiedades PK

• Tablas particionadas para soportar balanceo de cargaentre nodos de almacenamiento.

• Las entidades se organizan por partición.

• Una partición es un rango consecutive de entidadescon la misma clave de partición.

• Partition key: Identificador único de partición dentrode una tabla.

• PK es la primera parte de la clave principal de unaentidad.

• PK puede ser una cadena de hasta 1KB de tamaño.

• Incluir PartitionKey property en cada insert, update, y delete.

24

Page 25: No-SQL, Azure Table Storage y MongoDB

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

25

Page 26: No-SQL, Azure Table Storage y MongoDB

MSATS es una BDD sin esquema

26

PartitionKey: str

2012102517USR91

P

V

RowKey: str

jobid0121

P

V

TimeStamp: dt

201210251715

P

V

Name: st

User_91

P

V

PartitionKey: str

2012102517USR10

P

V

RowKey: str

jobid0121

P

V

TimeStamp: dt

201210251735

P

V

Status: st

Processing

P

V

Name: st

User_10

P

V

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

P

V

RowKey: str

jobid0001

P

V

TimeStamp: dt

201210251755

P

V

Name: st

User_13

P

V

Status: st

Aborted

P

V

TABLE JOBEXECUTION

Page 27: No-SQL, Azure Table Storage y MongoDB

Consulta del servicio de tabla

27

PartitionKey: str

2012102517USR91

P

V

RowKey: str

jobid0121

P

V

TimeStamp: dt

201210251715

P

V

Name: st

User_91

P

V

PartitionKey: str

2012102517USR10

P

V

RowKey: str

jobid0121

P

V

TimeStamp: dt

201210251735

P

V

Status: st

Processing

P

V

Name: st

User_10

P

V

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

P

V

RowKey: str

jobid0001

P

V

TimeStamp: dt

201210251755

P

V

Name: st

User_13

P

V

Status: st

Aborted

P

V

TABLE JOBEXECUTION

Page 28: No-SQL, Azure Table Storage y MongoDB

Particiones (nodos) MSATS

28

Page 29: No-SQL, Azure Table Storage y MongoDB

Partitions and Partition Ranges

Page 30: No-SQL, Azure Table Storage y MongoDB

DEMO

30

Acceso a un sistema MSATS en producción

Page 31: No-SQL, Azure Table Storage y MongoDB

Table Storage Design

Define your model

Key selection

31

Page 32: No-SQL, Azure Table Storage y MongoDB

Key selection: Considerations

Entity Group Transactions

Scalability

Efficient queries

32

Page 33: No-SQL, Azure Table Storage y MongoDB

DEMO

33

Gestión de tablas con clienteWindows

Page 34: No-SQL, Azure Table Storage y MongoDB

Modelo de programación

Windows Azure Storage: Connection Strings

Managing tables in WATS

Entities: CRUD operations (Create, read, update, delete)

Querying tables

Perform Entity Group Transactions (EGT)

34

Page 35: No-SQL, Azure Table Storage y MongoDB

Connection Strings in Visual Studio 2013

Double click on the Web/Worker role in the solution

35© 2012 SolidQ

Page 36: No-SQL, Azure Table Storage y MongoDB

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 WATS

For example, to create a table called ‘Products’:

36

using Microsoft.WindowsAzure;using Microsoft.WindowsAzure.StorageClient;

var clAccount;clAccount = CloudStorageAccount.FromConfigurationSettings(“ProductStorage") var tableClient = clAccount.CreateCloudTableClient();

tableClient.CreateTableIfNotExists(“Products”)

Page 37: No-SQL, Azure Table Storage y MongoDB

Entidades: Operaciones CRUD

Configurar las entidades (modelo de clases)

Configurar un DataContext

37

Page 38: No-SQL, Azure Table Storage y MongoDB

Configuración de las entidadesClass modeling

38

Page 39: No-SQL, Azure Table Storage y MongoDB

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

39

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 40: No-SQL, Azure Table Storage y MongoDB

Entities CRUD operationsList, Add, Update

40

// List (read) operation for GE06LEntry entities

public IEnumerable<GE06LEntry> GetGE06LEntries() {var results = from g in this.context.GE06LEntrywhere 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 == rowKeyselect g;

var entry = results.FirstOrDefault<GE06LEntry>();entry.FilelUrl = fileUrl;this.context.UpdateObject(entry);this.context.SaveChanges(); }

Page 41: No-SQL, Azure Table Storage y MongoDB

Consultar MSATSSingle Entity (a.k.a. Point Queries)

41

var q = (

from pais in context.CreateQuery<Pais>(tableName)

where pais.PartitionKey == “Paises“ &&

pais.RowKey == “España"

select movie);

Page 42: No-SQL, Azure Table Storage y MongoDB

Consultar MSATSRange Queries - Row Range Scan

42© 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 43: No-SQL, Azure Table Storage y MongoDB

Consultar MSATSRange Queries - Partition Range Scan

43

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 44: No-SQL, Azure Table Storage y MongoDB

Consultar MSATSFull Table Scan

44

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 45: No-SQL, Azure Table Storage y MongoDB

DEMO

45

Programación de MSATS

Page 46: No-SQL, Azure Table Storage y MongoDB

NoSQL: Azure Table Storage & MongoDB

BDD Relacionales y NoSQL

Almacenamiento de table de Azure (MSATS)

MongoDB

Escenarios

Costes

Page 47: No-SQL, Azure Table Storage y MongoDB

MongoDBMotivación

47

• ¿”Problemas” en RDBMs tradicionales?

• Transaciones

• JOINs

• Prescindimos de ellos

• Transacciones a nivel de documento

• No dejamos hacer JOINs

Page 48: No-SQL, Azure Table Storage y MongoDB

MongoDB

48

Unidad de Información es el Documento

Page 49: No-SQL, Azure Table Storage y MongoDB

MongoDB: Otro Paradigma

49

• 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 50: No-SQL, Azure Table Storage y MongoDB

MongoDB: Conceptos Clave

50

• 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 51: No-SQL, Azure Table Storage y MongoDB

DEMO

51

MongoDB en Azure con correos electrónicos

Page 52: No-SQL, Azure Table Storage y MongoDB

NoSQL: Azure Table Storage & MongoDB

BDD Relacionales y NoSQL

Almacenamiento de table de Azure (MSATS)

MongoDB

Escenarios

Costes

Page 53: No-SQL, Azure Table Storage y MongoDB

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

53

Page 54: No-SQL, Azure Table Storage y MongoDB

NoSQL: Azure Table Storage & MongoDB

BDD Relacionales y NoSQL

Almacenamiento de table de Azure (MSATS)

MongoDB

Escenarios

Costes

Page 55: No-SQL, Azure Table Storage y MongoDB

Costes

Microsoft Azure Table Storage

MongoDB on Azure

55

Page 56: No-SQL, Azure Table Storage y MongoDB

NoSQL: Azure Table Storage & MongoDB

Bases de datos relacionales y NoSQL

Microsoft 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

Escenarios

Evaluación de costes

56

Page 57: No-SQL, Azure Table Storage y MongoDB

¿Preguntas?

57

Page 58: No-SQL, Azure Table Storage y MongoDB

¡Gracias!

Siéntate a comer con nosotros o tómate un café y aclara tus

dudas

@augurarte Miguel López

@erincon Eladio Rincón

58