TDC2016POA | Trilha Banco de Dados - RavenDB: um banco de dados NoSQL de segunda geração

Preview:

Citation preview

Conhecendo RavenDBElemar Júnior

@elemarjrelemarjr@ravendb.netelemarjr@gmail.com

elemarjr.com

Olá, eu sou Elemar Jr

...

RavenDBMas, vamos falar de

@ayende

{ "Company": "companies/86", "Employee": "employees/4", "OrderedAt": "1996-11-07T00:00:00.0000000", "RequireAt": "1996-12-05T00:00:00.0000000", "ShippedAt": "1996-11-15T00:00:00.0000000", "ShipTo": { "Line1": "Adenauerallee 900", "Line2": null, "City": "Stuttgart", "Region": null, "PostalCode": "70563", "Country": "Germany" }, "ShipVia": "shippers/2", "Freight": 0.78, "Lines": [ { "Product": "products/1", "ProductName": "Chai", "PricePerUnit": 14.4, "Quantity": 15, "Discount": 0.15 }, { "Product": "products/23", "ProductName": "Tunnbröd", "PricePerUnit": 7.2, "Quantity": 25, "Discount": 0 } ]}

using Raven.Client.Document;

namespace Northwind{ class Program { static void Main() { var documentStore = new DocumentStore { Url = "http://localhost:8080", DefaultDatabase = "Northwind" };

documentStore.Initialize();

using (var session = documentStore.OpenSession()) { var p = session.Load<dynamic>("products/1"); System.Console.WriteLine(p.Name); } } }}

public class Product{ public string Name { get; set; } public string Supplier { get; set; } public string Category { get; set; } public string QuantityPerUnit { get; set; } public float PricePerUnit { get; set; } public int UnitsInStock { get; set; } public int UnitsOnOrder { get; set; } public bool Discontinued { get; set; } public int ReorderLevel { get; set; }}

using Raven.Client.Document;

namespace Northwind{ class Program { static void Main() { var documentStore = new DocumentStore { Url = "http://localhost:8080", DefaultDatabase = "Northwind" };

documentStore.Initialize();

using (var session = documentStore.OpenSession()) { var p = session.Load<Product>("products/1"); System.Console.WriteLine(p.Name); } } }}

public static class DocumentStoreHolder{ private static readonly Lazy<IDocumentStore> LazyStore = new Lazy<IDocumentStore>(() => { var store = new DocumentStore { Url = "http://localhost:8080", DefaultDatabase = "Northwind" };

return store.Initialize(); });

public static IDocumentStore Store => LazyStore.Value;}

string categoryId;using (var session = DocumentStoreHolder.Store.OpenSession()){ var newCategory = new Category { Name = "My New Category", Description = "Description of the new category" };

session.Store(newCategory); categoryId = newCategory.Id; session.SaveChanges();}

using (var session = DocumentStoreHolder.Store.OpenSession()){ var storedCategory = session .Load<Category>(categoryId);

storedCategory.Name = "abcd";

session.SaveChanges();}

using (var session = DocumentStoreHolder.Store.OpenSession()){ session.Delete(categoryId); session.SaveChanges();}

Product[] products = session.Load<Product>(new[] { "products/1", "products/2", "products/3"});

var p = session .Include<Product>(x => x.Category) .Load(1);

var c = session.Load<Category>(p.Category);

var order = session .Include<Order>(o => o.Company) .Include(o => o.Employee) .Include(o => o.Lines.Select(l => l.Product)) .Load("orders/1");

{ "Company": "companies/86", "Employee": "employees/4", "OrderedAt": "1996-11-07T00:00:00.0000000", "RequireAt": "1996-12-05T00:00:00.0000000", "ShippedAt": "1996-11-15T00:00:00.0000000", "ShipTo": { "Line1": "Adenauerallee 900", "Line2": null, "City": "Stuttgart", "Region": null, "PostalCode": "70563", "Country": "Germany" }, "ShipVia": "shippers/2", "Freight": 0.78, "Lines": [ { "Product": "products/1", "ProductName": "Chai", "PricePerUnit": 14.4, "Quantity": 15, "Discount": 0.15 }, { "Product": "products/23", "ProductName": "Tunnbröd", "PricePerUnit": 7.2, "Quantity": 25, "Discount": 0 } ]}

var order = session .Include<Order>(o => o.Company) .Include(o => o.Employee) .Include(o => o.Lines.Select(l => l.Product)) .Load("orders/1");

private static void QueryCompanyOrders(int companyId){ using (var session = DocumentStoreHolder.Store.OpenSession()) { var orders = ( from order in session.Query<Order>() .Include(o => o.Company) where order.Company == $"companies/{companyId}" select order ).ToList();

var company = session.Load<Company>(companyId);

if (company == null) { WriteLine("Company not found."); return; }

WriteLine($"Orders for {company.Name}");

foreach (var order in orders) { WriteLine($" {order.Id} - {order.OrderedAt}"); } }}

var orders = ( from order in session.Query<Order>() where order.Company == "companies/1" orderby order.OrderedAt select order ).ToList();

var results = new List<Order>();

foreach (var o in GetDocumentsFor("Orders")){ if (o.Company == "companies/1") results.Add(o);}

var orderedResults = results.Sort((a, b) => a.OrderedAt.CompareTo(b.OrderedAt));

public class Employees_ByFirstAndLastName : AbstractIndexCreationTask<Employee>{ public Employees_ByFirstAndLastName() { Map = (employees) => from employee in employees select new { FirstName = employee.FirstName, LastName = employee.LastName }; }}

public class People_Search : AbstractMultiMapIndexCreationTask<People_Search.Result>{ public class Result { public string SourceId { get; set; } public string Name { get; set; } public string Type { get; set; } }

public People_Search() { AddMap<Company>(companies => from company in companies select new Result { SourceId = company.Id, Name = company.Contact.Name, Type = "Company's contact" } );

...

AddMap<Supplier>(suppliers => from supplier in suppliers select new Result { SourceId = supplier.Id, Name = supplier.Contact.Name, Type = "Supplier's contact" } );

AddMap<Employee>(employees => from employee in employees select new Result { SourceId = employee.Id, Name = $"{employee.FirstName} {employee.LastName}", Type = "Employee" } );

...

Index(entry => entry.Name, FieldIndexing.Analyzed);

Store(entry => entry.SourceId, FieldStorage.Yes); Store(entry => entry.Name, FieldStorage.Yes); Store(entry => entry.Type, FieldStorage.Yes);

}}

public static IEnumerable<People_Search.Result> Search( IDocumentSession session, string searchTerms ){ var results = session.Query<People_Search.Result, People_Search>() .Search(r => r.Name, searchTerms, escapeQueryOptions: EscapeQueryOptions.AllowAllWildcards) .ProjectFromIndexFieldsInto<People_Search.Result>() .ToList();

return results;}

static void Main(string[] args){ Console.Title = "Multi-map sample"; using (var session = DocumentStoreHolder.Store.OpenSession()) { while (true) { Console.Write("\nSearch terms: "); var searchTerms = Console.ReadLine();

foreach (var result in Search(session, searchTerms)) { Console.WriteLine($"{result.SourceId}\t{result.Type}\t{result.Name}"); } } }}

public class Products_ByCategory : AbstractIndexCreationTask<Product, Products_ByCategory.Result>{ public class Result { public string Category { get; set; } public int Count { get; set; } }

public Products_ByCategory() { Map = products => from product in products select new { Category = product.Category, Count = 1 };

Reduce = results => from result in results group result by result.Category into g select new { Category = g.Key, Count = g.Sum(x => x.Count) }; }}

public class Employees_SalesPerMonth : AbstractIndexCreationTask<Order, Employees_SalesPerMonth.Result>{ public class Result { public string Employee { get; set; } public string Month { get; set; } public int TotalSales { get; set; } }

public Employees_SalesPerMonth() {

}}

Map = orders => from order in orders select new { order.Employee, Month = order.OrderedAt.ToString("yyyy-MM"), TotalSales = 1 };

Reduce = results => from result in results group result by new { result.Employee, result.Month } into g select new { g.Key.Employee, g.Key.Month, TotalSales = g.Sum(x => x.TotalSales) };

using (var session = DocumentStoreHolder.Store.OpenSession()){ var query = session .Query<Employees_SalesPerMonth.Result, Employees_SalesPerMonth>() .Include(x => x.Employee);

var results = ( from result in query where result.Month == "1998-03" orderby result.TotalSales descending select result ).ToList();

foreach (var result in results) { var employee = session.Load<Employee>(result.Employee); Console.WriteLine($"{employee.FirstName} {employee.LastName} made {result.TotalSales} sales."); }}

public class Products_ByCategory : AbstractIndexCreationTask<Product, Products_ByCategory.Result>{ public class Result { public string Category { get; set; } public int Count { get; set; } }

public Products_ByCategory() { Map = products => from product in products let categoryName = LoadDocument<Category>(product.Category).Name select new { Category = categoryName, Count = 1 };

Reduce = results => from result in results group result by result.Category into g select new { Category = g.Key, Count = g.Sum(x => x.Count) }; }}

public class Products_ProductAndSupplierName : AbstractTransformerCreationTask<Product>{ public class Result { public string ProductName { get; set; } public string SupplierName { get; set; } }

public Products_ProductAndSupplierName() { TransformResults = products => from product in products let category = LoadDocument<Supplier>(product.Supplier) select new { ProductName = product.Name, SupplierName = category.Name }; }}

elemarjr.com@elemarjrlinkedin.com/in/elemarjr

elemarjr@ravendb.netelemarjr@gmail.com

Mantenha contato!

Conhecendo RavenDBElemar Júnior

@elemarjrelemarjr@ravendb.netelemarjr@gmail.com

elemarjr.com