no-sql, azure table storage y mongodb

Post on 23-Jul-2015

87 Views

Category:

Technology

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

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 | mlopez@solidq.com

MCT, MCPD, MCTS, MCP

1

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

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

NoSQL: Azure Table Storage & MongoDB

BDD Relacionales y NoSQL

Almacenamiento de table de Azure (MSATS)

MongoDB

Escenarios

Costes

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

Donde gasta el tiempo RDBMS en TPCC

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

Teorema de CAP

7

Teorema de CAP: Selección de variables

8

Next Generation Databases mostly addressing

some of the points: being non-relational,

distributed, open-source and horizontally

scalable.

NoSQL

9http://NoSQL-database.org

• 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

Modelos de datos NoSQL

11

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

• 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

DEMO

13

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

NoSQL: Azure Table Storage & MongoDB

BDD Relacionales y NoSQL

Almacenamiento de table de Azure (MSATS)

MongoDB

Escenarios

Costes

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

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

DEMO

17

Aprovisionamiento de una cuenta de almacenamiento de Azure

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

Abstracciones MSATS

19

DEMO

20

Aplicaciónhttps://haveibeenpwned.com/

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

Entidades: Tipos de datos de propiedades

• Byte[]

• Bool

• DateTime

• Double

• Guid

• Int32/Int

• Int64/long

• String

22

Entidades: Indexación (Primary Key)

• PartitionKey property

• RowKey property

• Timestamp property

23

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

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

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

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

Particiones (nodos) MSATS

28

Partitions and Partition Ranges

DEMO

30

Acceso a un sistema MSATS en producción

Table Storage Design

Define your model

Key selection

31

Key selection: Considerations

Entity Group Transactions

Scalability

Efficient queries

32

DEMO

33

Gestión de tablas con clienteWindows

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

Connection Strings in Visual Studio 2013

Double click on the Web/Worker role in the solution

35© 2012 SolidQ

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

Entidades: Operaciones CRUD

Configurar las entidades (modelo de clases)

Configurar un DataContext

37

Configuración de las entidadesClass modeling

38

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

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

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

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

);

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

);

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

DEMO

45

Programación de MSATS

NoSQL: Azure Table Storage & MongoDB

BDD Relacionales y NoSQL

Almacenamiento de table de Azure (MSATS)

MongoDB

Escenarios

Costes

MongoDBMotivación

47

• ¿”Problemas” en RDBMs tradicionales?

• Transaciones

• JOINs

• Prescindimos de ellos

• Transacciones a nivel de documento

• No dejamos hacer JOINs

MongoDB

48

Unidad de Información es el Documento

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!

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

DEMO

51

MongoDB en Azure con correos electrónicos

NoSQL: Azure Table Storage & MongoDB

BDD Relacionales y NoSQL

Almacenamiento de table de Azure (MSATS)

MongoDB

Escenarios

Costes

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

NoSQL: Azure Table Storage & MongoDB

BDD Relacionales y NoSQL

Almacenamiento de table de Azure (MSATS)

MongoDB

Escenarios

Costes

Costes

Microsoft Azure Table Storage

MongoDB on Azure

55

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

¿Preguntas?

57

¡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

top related