private void DoTest <TIndex>() where TIndex : AbstractIndexCreationTask, new() { using (var store = GetDocumentStore()) { store.ExecuteIndex(new TIndex()); using (var session = store.OpenSession()) { session.Store(new Client { Name = "A", ImportStatuses = new List <ImportStatusMessage> { new ImportStatusMessage { Status = ImportStatus.Waiting, TimeStamp = new DateTime(2013, 1, 1, 0, 0, 0) }, new ImportStatusMessage { Status = ImportStatus.Running, TimeStamp = new DateTime(2013, 1, 1, 1, 0, 0) }, new ImportStatusMessage { Status = ImportStatus.Complete, TimeStamp = new DateTime(2013, 1, 1, 2, 0, 0) }, new ImportStatusMessage { Status = ImportStatus.Waiting, TimeStamp = new DateTime(2013, 2, 2, 0, 0, 0) }, new ImportStatusMessage { Status = ImportStatus.Running, TimeStamp = new DateTime(2013, 2, 2, 1, 0, 0) }, new ImportStatusMessage { Status = ImportStatus.Complete, TimeStamp = new DateTime(2013, 2, 2, 2, 0, 0) }, } }); session.Store(new Client { Name = "B", ImportStatuses = new List <ImportStatusMessage> { new ImportStatusMessage { Status = ImportStatus.Waiting, TimeStamp = new DateTime(2013, 1, 1, 0, 0, 0) }, new ImportStatusMessage { Status = ImportStatus.Running, TimeStamp = new DateTime(2013, 1, 1, 1, 0, 0) }, new ImportStatusMessage { Status = ImportStatus.Complete, TimeStamp = new DateTime(2013, 1, 1, 2, 0, 0) }, new ImportStatusMessage { Status = ImportStatus.Waiting, TimeStamp = new DateTime(2013, 2, 2, 0, 0, 0) }, new ImportStatusMessage { Status = ImportStatus.Running, TimeStamp = new DateTime(2013, 2, 2, 1, 0, 0) }, new ImportStatusMessage { Status = ImportStatus.Complete, TimeStamp = new DateTime(2013, 2, 2, 2, 0, 0) }, } }); session.SaveChanges(); } WaitForIndexing(store); RavenTestHelper.AssertNoIndexErrors(store); using (var session = store.OpenSession()) { var results = Queryable.OrderBy(session.Query <ImportSummary, TIndex>(), summary => summary.Date) .ToArray(); Assert.Equal(2, results.Length); Assert.Equal(2, results[0].Count); Assert.Equal(ImportStatus.Complete, results[0].Status); Assert.Equal(new DateTime(2013, 1, 1), results[0].Date); Assert.Equal(2, results[1].Count); Assert.Equal(ImportStatus.Complete, results[1].Status); Assert.Equal(new DateTime(2013, 2, 2), results[1].Date); } } }
public void QueryIndex_Success() { using (var store = GetDocumentStore()) { new ResourceViewModels_ByTag().Execute(store); using (var session = store.OpenSession()) { var p1 = "abracadabra"; var p2 = "abracadabra2"; var p3 = "abracadabra3"; var res1 = new Resource { AliasIds = new List <string> { p1 }, Caption = "Awesome test test", Comments = new List <Comment> { new Comment { Author = "Vasia", Text = "This is #awesome" }, new Comment { Author = "Vasia", Text = "This is #awesome" }, new Comment { Author = "Vasia", Text = "This is #awesome" }, new Comment { Author = "Vasia", Text = "This is #bad" }, } }; var res2 = new Resource { AliasIds = new List <string> { p2 }, Caption = "Bad test test", Comments = new List <Comment> { new Comment { Author = "Vasia", Text = "This is #bad" }, new Comment { Author = "Vasia", Text = "This is #bad" }, new Comment { Author = "Vasia", Text = "This is #bad" }, new Comment { Author = "Vasia", Text = "This is #awesome" }, } }; var res3 = new Resource { AliasIds = new List <string> { p3 }, Caption = "No test test", Comments = new List <Comment> { new Comment { Author = "Vasia", Text = "This is no" }, new Comment { Author = "Vasia", Text = "This is no" }, new Comment { Author = "Vasia", Text = "This is no" }, new Comment { Author = "Vasia", Text = "This is no" }, } }; session.Store(res1); session.Store(res2); session.Store(res3); var alias1 = new Alias { Id = p1, Criteria = new Criteria { CountryCode = "64" }, Declaration = "newzealand", Resource = new Resource { Id = res1.Id } }; var alias2 = new Alias { Id = p2, Criteria = new Criteria { CountryCode = "7" }, Declaration = "russia", Resource = new Resource { Id = res2.Id } }; var alias3 = new Alias { Id = p3, Criteria = new Criteria { CountryCode = "380" }, Declaration = "ukraine", Resource = new Resource { Id = res3.Id } }; session.Store(alias1); session.Store(alias2); session.Store(alias3); session.SaveChanges(); WaitForIndexing(store); var result = session.Query <ResourceViewModel, ResourceViewModels_ByTag>().ToList(); RavenTestHelper.AssertNoIndexErrors(store); Assert.NotEmpty(result); } } }
public void CanSelectLoadsInsideLetClause() { using (var store = GetDocumentStore()) { using (var session = store.OpenSession()) { session.Store(new Order { Lines = new List <OrderLine> { new OrderLine { Product = "products/1" }, new OrderLine { Product = "products/2" } } }); session.Store(new Order { Lines = new List <OrderLine> { new OrderLine { Product = "products/3" }, new OrderLine { Product = "products/4" } } }); session.Store(new Product { Name = "a" }, "products/1"); session.Store(new Product { Name = "b" }, "products/2"); session.Store(new Product { Name = "c" }, "products/3"); session.Store(new Product { Name = "d" }, "products/4"); session.SaveChanges(); } using (var session = store.OpenSession()) { var q = from doc in session.Query <Order>() let p = doc.Lines.Select(y => RavenQuery.Load <Product>(y.Product)) select new { p }; RavenTestHelper.AssertEqualRespectingNewLines( @"declare function output(doc) { var p = doc.Lines.map(function(y){return load(y.Product);}); return { p : p }; } from 'Orders' as doc select output(doc)", q.ToString()); var result = q.ToList(); Assert.Equal(2, result.Count); var products = result[0].p.ToList(); Assert.Equal(2, products.Count); Assert.Equal("a", products[0].Name); Assert.Equal("b", products[1].Name); products = result[1].p.ToList(); Assert.Equal(2, products.Count); Assert.Equal("c", products[0].Name); Assert.Equal("d", products[1].Name); } } }
public void Physical_store_test() { List <Car> cars; using (var documentStore = GetDocumentStore()) { documentStore.Initialize(); new CarIndex().Execute(documentStore); using (var session = documentStore.OpenSession()) { foreach (CarLot doc in Docs) { session.Store(doc); } session.SaveChanges(); } string targetLeasee = CarLeasees[0].Id; using (var session = documentStore.OpenSession()) { //Synchronize indexes session.Query <CarLot, CarIndex>().Customize(x => x.WaitForNonStaleResults(TimeSpan.FromMinutes(2))).FirstOrDefault(); var query = session.Query <CarLot, CarIndex>() .Where(carLot => carLot.Cars.Any(car => car.LeaseHistory.Any(leasee => leasee.Id == targetLeasee))) .Take(1024); var deserializer = session.Advanced.DocumentStore.Conventions.CreateSerializer(); var indexQuery = RavenTestHelper.GetIndexQuery(query); using (var commands = documentStore.Commands()) { var queryResult = commands.Query(indexQuery); var carLots = queryResult .Results .Select(x => { using (var reader = new BlittableJsonReader()) { reader.Init((BlittableJsonReaderObject)x); return(deserializer.Deserialize <CarLot>(reader)); } }) .ToArray(); foreach (var carLot in carLots) { Assert.NotNull(carLot.Cars); Assert.NotEmpty(carLot.Cars); } cars = carLots .SelectMany(x => x.Cars) .Where(car => car.LeaseHistory.Any(leasee => leasee.Id == targetLeasee)) .ToList(); } } } Assert.NotNull(cars); Assert.NotEmpty(cars); foreach (Car car in cars) { Assert.NotNull(car.LeaseHistory); Assert.NotEmpty(car.LeaseHistory); } }
public void CanIndexWithNoErrors_Datetime() { using (var store = GetDocumentStore()) { using (var commands = store.Commands()) { var json = commands.ParseJson(LinuxTestUtils.Dos2Unix(@"{ '$type': 'Domain.Model.Clicks.ClickAllocation, Domain', 'AccountId': 'accounts/4', 'Quantity': 90, 'Date': '2011-12-12T08:47:44.0706445', 'Key': null, 'OrderNumber': null, 'PurchaseOrderNumber': null, 'PurchaseDate': '0001-01-01T00:00:00.0000000-05:00', 'ReorderQuantity': 0, 'Type': 'Dealer', 'LastSavedDate': '2011-12-12T08:47:44.1643945-05:00', 'LastSavedUser': '******', 'SourceId': '00000000-0000-0000-0000-000000000000' }")); commands.Put("test/1", null, json, new Dictionary <string, object> { { Constants.Documents.Metadata.Collection, "ClickAllocations" } }); json = commands.ParseJson(LinuxTestUtils.Dos2Unix(@"{ '$type': 'Domain.Model.Clicks.ClickAllocation, Domain', 'AccountId': 'accounts/4', 'Quantity': 20, 'Date': '2012-02-28T16:05:18.7359910', 'Key': null, 'OrderNumber': null, 'PurchaseOrderNumber': null, 'PurchaseDate': '0001-01-01T00:00:00.0000000', 'ReorderQuantity': 5, 'Type': 'Dealer', 'LastSavedDate': '2012-02-28T16:05:19.3609910', 'LastSavedUser': '******', 'SourceId': '00000000-0000-0000-0000-000000000000' }")); commands.Put("test/2", null, json, new Dictionary <string, object> { { Constants.Documents.Metadata.Collection, "ClickAllocations" } }); } store.Maintenance.Send(new PutIndexesOperation(new[] { new IndexDefinition { Name = "test", Maps = { LinuxTestUtils.Dos2Unix(@"docs.ClickAllocations .Select(doc => new {AccountId = doc.AccountId, Date = doc.Date, Id = Id(doc), Key = doc.Key, LastSavedDate = doc.LastSavedDate, LastSavedUser = doc.LastSavedUser, OrderNumber = doc.OrderNumber, PurchaseDate = doc.PurchaseDate, PurchaseOrderNumber = doc.PurchaseOrderNumber, Quantity = doc.Quantity, ReorderQuantity = doc.ReorderQuantity, Type = doc.Type}) ") }, Reduce = LinuxTestUtils.Dos2Unix(@"results .GroupBy(result => result.AccountId) .Select(a => new {a = a, clickAllocation = a.OrderByDescending(x => x.Date).FirstOrDefault()}) .Select(__h__TransparentIdentifier0 => new {AccountId = __h__TransparentIdentifier0.clickAllocation.AccountId, Date = __h__TransparentIdentifier0.clickAllocation.Date, Id = __h__TransparentIdentifier0.clickAllocation.Id, Key = __h__TransparentIdentifier0.clickAllocation.Key, LastSavedDate = __h__TransparentIdentifier0.clickAllocation.LastSavedDate, LastSavedUser = __h__TransparentIdentifier0.clickAllocation.LastSavedUser, OrderNumber = __h__TransparentIdentifier0.clickAllocation.OrderNumber, PurchaseDate = __h__TransparentIdentifier0.clickAllocation.PurchaseDate, PurchaseOrderNumber = __h__TransparentIdentifier0.clickAllocation.PurchaseOrderNumber, Quantity = __h__TransparentIdentifier0.clickAllocation.Quantity, ReorderQuantity = __h__TransparentIdentifier0.clickAllocation.ReorderQuantity, Type = __h__TransparentIdentifier0.clickAllocation.Type})") } })); WaitForIndexing(store); RavenTestHelper.AssertNoIndexErrors(store); } }
public void CanProjectWithWrappedParameterAndLet() { using (var store = GetDocumentStore()) { using (var session = store.OpenSession()) { session.Store(new Order { Lines = new List <OrderLine> { new OrderLine { ProductName = "Coffee", PricePerUnit = 15, Quantity = 2 }, new OrderLine { ProductName = "Milk", PricePerUnit = 7, Quantity = 10 } } }); session.Store(new Company { Name = "HR" }, "companies/1"); session.SaveChanges(); } using (var session = store.OpenSession()) { var line = new OrderLine { PricePerUnit = 15, ProductName = "Coffee", Discount = (decimal)0.25 }; var myOrder = new Order { Company = "companies/1" }; var query = from o in session.Query <Order>() let totalSpentOnOrder = (Func <Order, decimal>)(order => order.Lines.Sum(x => x.PricePerUnit * x.Quantity * (1 - line.Discount))) select new { Sum = totalSpentOnOrder(o), Any = o.Lines.Any(x => x.ProductName == line.ProductName), NestedQuery = o.Lines.Where(x => x.PricePerUnit < line.PricePerUnit).Select(y => y.ProductName).ToList(), Company = RavenQuery.Load <Company>(myOrder.Company).Name, }; RavenTestHelper.AssertEqualRespectingNewLines( @"declare function output(o, $p0, $p1, $p2, $p3) { var totalSpentOnOrder = function(order){return order.Lines.map(function(x){return x.PricePerUnit*x.Quantity*(1-$p0);}).reduce(function(a, b) { return a + b; }, 0);}; return { Sum : totalSpentOnOrder(o), Any : o.Lines.some(function(x){return x.ProductName===$p1;}), NestedQuery : o.Lines.filter(function(x){return x.PricePerUnit<$p2;}).map(function(y){return y.ProductName;}), Company : load($p3).Name }; } from 'Orders' as o select output(o, $p0, $p1, $p2, $p3)", query.ToString()); var result = query.ToList(); Assert.Equal(1, result.Count); Assert.Equal(75, result[0].Sum); Assert.True(result[0].Any); Assert.Equal(1, result[0].NestedQuery.Count); Assert.Equal("Milk", result[0].NestedQuery[0]); Assert.Equal("HR", result[0].Company); } } }
public void ChildrenHasMultipleTransports_Raven() { using (var store = GetDocumentStore()) { // Create Index new TransportsIndex().Execute(store); using (var session = store.OpenSession()) { // Store two children session.Store(new Child { Id = "B1", Name = "Thor Arne" }); session.Store(new Child { Id = "B2", Name = "Ståle" }); // Store four Transports session.Store(new Transport { Id = "A1", ChildId = "B1" }); session.Store(new Transport { Id = "A2", ChildId = "B1" }); session.Store(new Transport { Id = "A3", ChildId = "B2" }); session.Store(new Transport { Id = "A4", ChildId = "B2" }); session.SaveChanges(); var transports = session.Query <JoinedChildTransport, TransportsIndex>() .Customize(x => x.WaitForNonStaleResults(TimeSpan.FromMinutes(100))) .OrderBy(x => x.TransportId) .OrderBy(x => x.ChildId) .ProjectFromIndexFieldsInto <JoinedChildTransport>() .ToList(); RavenTestHelper.AssertNoIndexErrors(store); Assert.Equal(4, transports.Count); // skyssavtaler for B1 Assert.Equal("A1", transports[0].TransportId); Assert.Equal("B1", transports[0].ChildId); Assert.Equal("Thor Arne", transports[0].Name); Assert.Equal("A2", transports[1].TransportId); Assert.Equal("B1", transports[1].ChildId); Assert.Equal("Thor Arne", transports[0].Name); // skyssavtaler for B2 Assert.Equal("A3", transports[2].TransportId); Assert.Equal("B2", transports[2].ChildId); Assert.Equal("Ståle", transports[2].Name); Assert.Equal("A4", transports[3].TransportId); Assert.Equal("B2", transports[3].ChildId); Assert.Equal("Ståle", transports[3].Name); } } }
public void Can_Use_Let_with_Multipule_Aliases_that_are_Reserved_Words_in_RQL() { using (var store = GetDocumentStore()) { using (var session = store.OpenSession()) { session.Store(new Employee { FirstName = "Jerry" }, "employees/1-A"); session.Store(new Employee { FirstName = "Bob" }, "employees/2-A"); session.Store(new Company { Name = "GD", AccountsReceivable = 2.0m, EmployeesIds = new List <string> { "employees/1-A", "employees/2-A" } }, "companies/1-A"); session.Store(new Order { Company = "companies/1-A", Lines = new List <OrderLine> { new OrderLine { PricePerUnit = 10, Quantity = 5 }, new OrderLine { PricePerUnit = 20, Quantity = 10 } } }); session.SaveChanges(); } using (var session = store.OpenSession()) { //the from-alias is also a reserved word var query = from order in session.Query <Order>() let include = order.Company let load = session.Load <Company>(include) let update = RavenQuery.Load <Employee>(load.EmployeesIds) let sum = order.Lines.Sum(l => l.PricePerUnit * l.Quantity * load.AccountsReceivable) select new { Comapny = load, Sum = sum, Employees = update.Select(e => e.FirstName).ToList() }; RavenTestHelper.AssertEqualRespectingNewLines( @"declare function output(__alias0) { var order = __alias0; var include = order.Company; var _load = load(include); var update = load(_load.EmployeesIds); var sum = order.Lines.map(function(l){return l.PricePerUnit*l.Quantity*_load.AccountsReceivable;}).reduce(function(a, b) { return a + b; }, 0); return { Comapny : _load, Sum : sum, Employees : update.map(function(e){return e.FirstName;}) }; } from Orders as __alias0 select output(__alias0)", query.ToString()); var result = query.ToList(); Assert.Equal("GD", result[0].Comapny.Name); Assert.Equal(500, result[0].Sum); Assert.Equal(2, result[0].Employees.Count); Assert.Equal("Jerry", result[0].Employees[0]); Assert.Equal("Bob", result[0].Employees[1]); } } }
public void SpatialOnAutoIndex() { var databaseName = $"{nameof(SpatialOnAutoIndex)}-{Guid.NewGuid()}"; var path = NewDataPath(); using (var store = GetDocumentStore(new Options { Path = path, ModifyDatabaseName = s => databaseName, DeleteDatabaseOnDispose = false })) { using (var session = store.OpenSession()) { session.Store(new Item { Latitude = 10, Longitude = 20, Latitude2 = 10, Longitude2 = 20, ShapeWkt = "POINT(20 10)", Name = "Name1" }); session.SaveChanges(); } using (var session = store.OpenSession()) { var q = session.Query <Item>() .Spatial(factory => factory.Point(x => x.Latitude, x => x.Longitude), factory => factory.WithinRadius(10, 10, 20)); var iq = RavenTestHelper.GetIndexQuery(q); Assert.Equal("from Items where spatial.within(spatial.point(Latitude, Longitude), spatial.circle($p0, $p1, $p2))", iq.Query); var dq = session.Advanced.DocumentQuery <Item>() .Spatial(factory => factory.Point(x => x.Latitude, x => x.Longitude), factory => factory.WithinRadius(10, 10, 20)); iq = dq.GetIndexQuery(); Assert.Equal("from Items where spatial.within(spatial.point(Latitude, Longitude), spatial.circle($p0, $p1, $p2))", iq.Query); dq = session.Advanced.DocumentQuery <Item>() .Spatial(factory => factory.Wkt(x => x.ShapeWkt), factory => factory.WithinRadius(10, 10, 20)); iq = dq.GetIndexQuery(); Assert.Equal("from Items where spatial.within(spatial.wkt(ShapeWkt), spatial.circle($p0, $p1, $p2))", iq.Query); } using (var session = store.OpenSession()) { var results = session.Query <Item>() .Statistics(out var stats) .Spatial(factory => factory.Point(x => x.Latitude, x => x.Longitude), factory => factory.WithinRadius(10, 10, 20)) .ToList(); Assert.Equal(1, results.Count); Assert.Equal("Auto/Items/BySpatial.point(Latitude|Longitude)", stats.IndexName); } } using (var store = GetDocumentStore(new Options { Path = path, ModifyDatabaseName = s => databaseName, CreateDatabase = false })) { var indexes = store.Maintenance.Send(new GetIndexesOperation(0, 10)); // checking it index survived restart Assert.Equal(1, indexes.Length); Assert.Equal("Auto/Items/BySpatial.point(Latitude|Longitude)", indexes[0].Name); using (var session = store.OpenSession()) // validating matching { var results = session.Query <Item>() .Statistics(out var stats) .Spatial(factory => factory.Point(x => x.Latitude, x => x.Longitude), factory => factory.WithinRadius(10, 10, 20)) .ToList(); Assert.Equal(1, results.Count); Assert.Equal("Auto/Items/BySpatial.point(Latitude|Longitude)", stats.IndexName); } using (var session = store.OpenSession()) // validating extending { var results = session.Query <Item>() .Statistics(out var stats) .Spatial(factory => factory.Point(x => x.Latitude2, x => x.Longitude2), factory => factory.WithinRadius(10, 10, 20)) .ToList(); Assert.Equal(1, results.Count); Assert.Equal("Auto/Items/BySpatial.point(Latitude|Longitude)AndSpatial.point(Latitude2|Longitude2)", stats.IndexName); results = session.Query <Item>() .Statistics(out stats) .Spatial(factory => factory.Wkt(x => x.ShapeWkt), factory => factory.WithinRadius(10, 10, 20)) .ToList(); Assert.Equal(1, results.Count); Assert.Equal("Auto/Items/BySpatial.point(Latitude|Longitude)AndSpatial.point(Latitude2|Longitude2)AndSpatial.wkt(ShapeWkt)", stats.IndexName); } } }
public void CreateAndQuerySimpleIndexWithSortingAndCustomCollateral() { using (var store = GetDocumentStore()) { new Companies_SortByName().Execute(store); using (var session = store.OpenSession()) { session.Store(new Company { Name = "C" }); session.Store(new Company { Name = "a" }); session.Store(new Company { Name = "ć" }); session.Store(new Company { Name = "ą" }); session.Store(new Company { Name = "A" }); session.Store(new Company { Name = "c" }); session.Store(new Company { Name = "Ą" }); session.Store(new Company { Name = "D" }); session.Store(new Company { Name = "d" }); session.Store(new Company { Name = "b" }); session.SaveChanges(); Indexes.WaitForIndexing(store); RavenTestHelper.AssertNoIndexErrors(store); var companies = session.Query <Company, Companies_SortByName>() .OrderBy(c => c.Name) .ToArray(); Assert.Equal(10, companies.Length); Assert.Equal("a", companies[0].Name); Assert.Equal("A", companies[1].Name); Assert.Equal("ą", companies[2].Name); Assert.Equal("Ą", companies[3].Name); Assert.Equal("b", companies[4].Name); Assert.Equal("c", companies[5].Name); Assert.Equal("C", companies[6].Name); Assert.Equal("ć", companies[7].Name); Assert.Equal("d", companies[8].Name); Assert.Equal("D", companies[9].Name); } } }
public void ShouldCompileAndWork() { using (var store = GetDocumentStore()) { store.Maintenance.Send(new PutIndexesOperation(new IndexDefinition { Name = "Index1", Maps = { @" from doc in docs.Users where doc.Name.Contains(""missing"") || (doc.FirstName.Contains(""missing"") || doc.LastName.Contains(""missing"")) select new { doc.Id }" } })); store.Maintenance.Send(new PutIndexesOperation(new IndexDefinition { Name = "Index2", Maps = { @"docs.Users.Where(doc => doc.Name.Contains(""missing"") || (doc.FirstName.Contains(""missing"") || doc.LastName.Contains(""missing""))).Select(doc => new { doc.Id });" } })); using (var commands = store.Commands()) { commands.Put("users/1", null, new { Name = "John" }, new Dictionary <string, object> { { Constants.Documents.Metadata.Collection, "Users" } }); commands.Put("users/2", null, new { LastName = "missing" }, new Dictionary <string, object> { { Constants.Documents.Metadata.Collection, "Users" } }); } WaitForIndexing(store); RavenTestHelper.AssertNoIndexErrors(store); using (var session = store.OpenSession()) { var count = session.Query <User>("Index1") .Count(); Assert.Equal(1, count); count = session.Query <User>("Index2") .Count(); Assert.Equal(1, count); } } }
public void CanUseTryConvertInIndex() { using (var store = GetDocumentStore()) { var index = new ConvertIndex(); index.Execute(store); using (var session = store.OpenSession()) { session.Store(new Item { DblNullValue = 1.1, DblValue = 2.1, FltNullValue = 3.1f, FltValue = 4.1f, IntNullValue = 5, IntValue = 6, LngNullValue = 7, LngValue = 8, ObjValue = new Company { Name = "HR" }, StgValue = "str" }, "items/1"); session.SaveChanges(); } WaitForIndexing(store); RavenTestHelper.AssertNoIndexErrors(store); var terms = store.Maintenance.Send(new GetTermsOperation(index.IndexName, nameof(Item.DblNullValue), fromValue: null)); Assert.Equal(1, terms.Length); Assert.True(double.Parse(terms[0], CultureInfo.InvariantCulture).AlmostEquals(1.1)); terms = store.Maintenance.Send(new GetTermsOperation(index.IndexName, nameof(Item.DblValue), fromValue: null)); Assert.Equal(1, terms.Length); Assert.True(double.Parse(terms[0], CultureInfo.InvariantCulture).AlmostEquals(2.1)); terms = store.Maintenance.Send(new GetTermsOperation(index.IndexName, nameof(Item.FltNullValue), fromValue: null)); Assert.Equal(1, terms.Length); Assert.True(float.Parse(terms[0], CultureInfo.InvariantCulture).AlmostEquals(3.1f)); terms = store.Maintenance.Send(new GetTermsOperation(index.IndexName, nameof(Item.FltValue), fromValue: null)); Assert.Equal(1, terms.Length); Assert.True(float.Parse(terms[0], CultureInfo.InvariantCulture).AlmostEquals(4.1f)); terms = store.Maintenance.Send(new GetTermsOperation(index.IndexName, nameof(Item.IntNullValue), fromValue: null)); Assert.Equal(1, terms.Length); Assert.Equal("5", terms[0]); terms = store.Maintenance.Send(new GetTermsOperation(index.IndexName, nameof(Item.IntValue), fromValue: null)); Assert.Equal(1, terms.Length); Assert.Equal("6", terms[0]); terms = store.Maintenance.Send(new GetTermsOperation(index.IndexName, nameof(Item.LngNullValue), fromValue: null)); Assert.Equal(1, terms.Length); Assert.Equal("7", terms[0]); terms = store.Maintenance.Send(new GetTermsOperation(index.IndexName, nameof(Item.LngValue), fromValue: null)); Assert.Equal(1, terms.Length); Assert.Equal("8", terms[0]); terms = store.Maintenance.Send(new GetTermsOperation(index.IndexName, nameof(Item.ObjValue), fromValue: null)); Assert.Equal(1, terms.Length); Assert.Equal("-1", terms[0]); terms = store.Maintenance.Send(new GetTermsOperation(index.IndexName, nameof(Item.StgValue), fromValue: null)); Assert.Equal(1, terms.Length); Assert.Equal("-1", terms[0]); } }
private static string GetLuceneQuery(IQueryable <User> query, JsonOperationContext context, JsonSerializer jsonSerializer) { var indexQuery = RavenTestHelper.GetIndexQuery(query); return(GetLuceneQuery(indexQuery, context, jsonSerializer)); }
public void FloatArrayIndexTest() { using (var store = GetDocumentStore()) { store.ExecuteIndex(new RatingByCategoryIndex()); using (var session = store.OpenSession()) { session.Store(new Book { Category = Categories.Fiction, Name = "Book 1", Ratings = new[] { new Rating { User = "******", Rate = 1.5F, }, new Rating { User = "******", Rate = 3.5F, } } }); session.Store(new Book { Category = Categories.Fiction, Name = "Book 2", Ratings = new[] { new Rating { User = "******", Rate = 2.5F, }, new Rating { User = "******", Rate = 4.5F, } } }); session.SaveChanges(); } WaitForIndexing(store); RavenTestHelper.AssertNoIndexErrors(store); using (var session = store.OpenSession()) { var categories = session .Query <IndexResult, RatingByCategoryIndex>() .Customize(x => x.WaitForNonStaleResults()) .ToList(); Assert.NotNull(categories); Assert.Equal(1, categories.Count); var books = categories[0].Books; Assert.NotNull(books); Assert.Equal(2, books.Length); foreach (var book in books) { Assert.True(book.MinRating > 1F); Assert.True(book.MaxRating > book.MinRating); Assert.False(string.IsNullOrEmpty(book.Name)); } } } }
public void Should_put_projected_fields_into_select() { using (var store = GetDocumentStore()) { new Companies_ByContact().Execute(store); using (var session = store.OpenSession()) { session.Store(new Company() { Phone = "1", Contact = new Contact() { Name = "a" } }); session.SaveChanges(); var query = session.Query <Company, Companies_ByContact>() .ProjectInto <ContactDetails>() .Customize(x => x.WaitForNonStaleResults()); Assert.Equal("from index 'Companies/ByContact' select Name, Phone", RavenTestHelper.GetIndexQuery(query).Query); var results = query .ToList(); Assert.Equal(1, results.Count); Assert.Equal("1", results[0].Phone); Assert.Equal("a", results[0].Name); } } }
public void CanRetrieveFacetCounts() { using (var store = GetDocumentStore()) { using (var session = store.OpenSession()) { var item1 = new AccItem { Lat = 52.156161, Lon = 1.602483, Name = "House one", Bedrooms = 2 }; item1.Attributes.Add(Tag.HasGarden); item1.Attributes.Add(Tag.HasPool); var item2 = new AccItem { Lat = 52.156161, Lon = 1.602483, Name = "House two", Bedrooms = 2 }; item2.Attributes.Add(Tag.HasGarden); var item3 = new AccItem { Lat = 52.156161, Lon = 1.602483, Name = "Bungalow three", Bedrooms = 3 }; item3.Attributes.Add(Tag.HasGarden); item3.Attributes.Add(Tag.HasPool); item3.Attributes.Add(Tag.HasTennis); session.Store(item1); session.Store(item2); session.Store(item3); var _facets = new List <Facet> { new Facet { FieldName = "Attributes" } }; session.Store(new FacetSetup { Id = "facets/AttributeFacets", Facets = _facets }); session.SaveChanges(); session.SaveChanges(); } new AccItems_Spatial().Execute(store); new AccItems_Attributes().Execute(store); Indexes.WaitForIndexing(store); using (var session = store.OpenSession()) { var query = session.Query <AccItem, AccItems_Spatial>() .Customize(customization => customization.WaitForNonStaleResults()) .Spatial("Distance", x => x.WithinRadius(10, 52.156161, 1.602483)) .Where(x => x.Bedrooms == 2); var partialFacetResults = query .AggregateUsing("facets/AttributeFacets") .Execute(); var fullFacetResults = session.Query <AccItem, AccItems_Attributes>() .AggregateUsing("facets/AttributeFacets") .Execute(); RavenTestHelper.AssertNoIndexErrors(store); var partialGardenFacet = partialFacetResults["Attributes"].Values.First( x => x.Range.Contains("hasgarden")); Assert.Equal(2, partialGardenFacet.Count); var fullGardenFacet = fullFacetResults["Attributes"].Values.First( x => x.Range.Contains("hasgarden")); Assert.Equal(3, fullGardenFacet.Count); RavenTestHelper.AssertNoIndexErrors(store); } } }
public void CanWriteBigTransactions(int transactionSizeInGb) { var tmpFile = RavenTestHelper.NewDataPath(nameof(CanWriteBigTransactions), transactionSizeInGb, forceCreateDir: true); try { Directory.Delete(tmpFile, true); } catch (Exception) { // ignored } try { var storageEnvironmentOptions = StorageEnvironmentOptions.ForPath(tmpFile); storageEnvironmentOptions.ManualFlushing = true; using (var env = new StorageEnvironment(storageEnvironmentOptions)) { var value = new byte[HalfGb]; var random = new Random(); //var seed = random.Next(); //Console.WriteLine(seed); new Random(240130173).NextBytes(value); value[0] = 11; value[HalfGb - 1] = 22; value[(HalfGb / 3) * 2] = 33; value[HalfGb / 2] = 44; value[HalfGb / 3] = 55; using (var tx = env.WriteTransaction()) { var tree = tx.CreateTree("bigTree"); for (int i = 0; i < transactionSizeInGb * 2; i++) { var ms1 = new MemoryStream(value); ms1.Position = 0; tree.Add("bigTreeKey" + i, ms1); } ValidateTree(transactionSizeInGb, tree); tx.Commit(); } using (var tx = env.WriteTransaction()) { var tree = tx.CreateTree("AddtionalTree"); var ms1 = new MemoryStream(value); ms1.Position = 0; tree.Add("treeKey1", ms1); var ms2 = new MemoryStream(value); ms2.Position = 0; tree.Add("treeKey2", ms2); tx.Commit(); } using (var snapshot = env.ReadTransaction()) { var tree = snapshot.ReadTree("bigTree"); ValidateTree(transactionSizeInGb, tree); } } } finally { Directory.Delete(tmpFile, true); } }
public void StrangeReduceOnNestedItems() { using (var store = GetDocumentStore()) { new TasksCount_ForPerson().Execute(store); var userA = new Person { Id = "person/1", Name = "User A" }; var userB = new Person { Id = "person/2", Name = "User B" }; using (var session = store.OpenSession()) { session.Store(userA); session.Store(userB); session.Store(new Project { Name = "Proj A", Activities = new List <Activity> { new Activity { Name = "Activity A", Tasks = new List <Task> { new Task { Name = "Task A", Owner = userA }, new Task { Name = "Task B", Owner = userA }, } }, new Activity { Name = "Activity B", Tasks = new List <Task> { new Task { Name = "Task C", Owner = userA }, new Task { Name = "Task D for userB", Owner = userB }, } }, } }); session.SaveChanges(); } int tasksForUserA = 3; int tasksForUserB = 1; using (var session = store.OpenSession()) { var result = session.Query <TasksCount_ForPerson.Result, TasksCount_ForPerson>() .Customize(c => c.WaitForNonStaleResults()) .ToList(); RavenTestHelper.AssertNoIndexErrors(store); Assert.Equal(tasksForUserA, result.Single(s => s.OwnerId == userA.Id).Count); Assert.Equal(tasksForUserB, result.Single(s => s.OwnerId == userB.Id).Count); } using (var session = store.OpenSession()) { var project = session.Query <Project>().First(); // I only change the name of the tasks, which should not cause the counts to go up project.Activities.ElementAt(0).Tasks.ElementAt(0).Name = "Touch task"; project.Activities.ElementAt(0).Tasks.ElementAt(1).Name = "Touch task 2"; project.Activities.ElementAt(1).Tasks.ElementAt(0).Name = "Touch Task 3"; project.Activities.ElementAt(1).Tasks.ElementAt(1).Name = "Touch task 4"; session.SaveChanges(); } using (var session = store.OpenSession()) { var result = session.Query <TasksCount_ForPerson.Result, TasksCount_ForPerson>().Customize(c => c.WaitForNonStaleResults()). ToList(); // these two will fail. Assert.Equal(tasksForUserA, result.Single(s => s.OwnerId == userA.Id).Count); Assert.Equal(tasksForUserB, result.Single(s => s.OwnerId == userB.Id).Count); } } }
public void CanDeleteIndexErrors() { using (var store = GetDocumentStore()) { RavenTestHelper.AssertNoIndexErrors(store); store.Maintenance.Send(new DeleteIndexErrorsOperation()); Assert.Throws <IndexDoesNotExistException>(() => store.Maintenance.Send(new DeleteIndexErrorsOperation(new[] { "DoesNotExist" }))); store.Maintenance.Send(new PutIndexesOperation(new[] { new IndexDefinition { Name = "Index1", Maps = { "from doc in docs let x = 0 select new { Total = 3/x };" } } })); store.Maintenance.Send(new PutIndexesOperation(new[] { new IndexDefinition { Name = "Index2", Maps = { "from doc in docs let x = 0 select new { Total = 4/x };" } } })); store.Maintenance.Send(new PutIndexesOperation(new[] { new IndexDefinition { Name = "Index3", Maps = { "from doc in docs let x = 0 select new { Total = 5/x };" } } })); Indexes.WaitForIndexing(store); RavenTestHelper.AssertNoIndexErrors(store); store.Maintenance.Send(new DeleteIndexErrorsOperation()); store.Maintenance.Send(new DeleteIndexErrorsOperation(new[] { "Index1", "Index2", "Index3" })); Assert.Throws <IndexDoesNotExistException>(() => store.Maintenance.Send(new DeleteIndexErrorsOperation(new[] { "Index1", "DoesNotExist" }))); using (var session = store.OpenSession()) { session.Store(new Company()); session.Store(new Company()); session.Store(new Company()); session.SaveChanges(); } Indexes.WaitForIndexingErrors(store, new [] { "Index1", "Index2", "Index3" }); store.Maintenance.Send(new StopIndexingOperation()); var indexErrors1 = store.Maintenance.Send(new GetIndexErrorsOperation(new[] { "Index1" })); var indexErrors2 = store.Maintenance.Send(new GetIndexErrorsOperation(new[] { "Index2" })); var indexErrors3 = store.Maintenance.Send(new GetIndexErrorsOperation(new[] { "Index3" })); Assert.NotEmpty(indexErrors1.SelectMany(x => x.Errors)); Assert.NotEmpty(indexErrors2.SelectMany(x => x.Errors)); Assert.NotEmpty(indexErrors3.SelectMany(x => x.Errors)); store.Maintenance.Send(new DeleteIndexErrorsOperation(new[] { "Index2" })); indexErrors1 = store.Maintenance.Send(new GetIndexErrorsOperation(new[] { "Index1" })); indexErrors2 = store.Maintenance.Send(new GetIndexErrorsOperation(new[] { "Index2" })); indexErrors3 = store.Maintenance.Send(new GetIndexErrorsOperation(new[] { "Index3" })); Assert.NotEmpty(indexErrors1.SelectMany(x => x.Errors)); Assert.Empty(indexErrors2.SelectMany(x => x.Errors)); Assert.NotEmpty(indexErrors3.SelectMany(x => x.Errors)); store.Maintenance.Send(new DeleteIndexErrorsOperation()); indexErrors1 = store.Maintenance.Send(new GetIndexErrorsOperation(new[] { "Index1" })); indexErrors2 = store.Maintenance.Send(new GetIndexErrorsOperation(new[] { "Index2" })); indexErrors3 = store.Maintenance.Send(new GetIndexErrorsOperation(new[] { "Index3" })); Assert.Empty(indexErrors1.SelectMany(x => x.Errors)); Assert.Empty(indexErrors2.SelectMany(x => x.Errors)); Assert.Empty(indexErrors3.SelectMany(x => x.Errors)); RavenTestHelper.AssertNoIndexErrors(store); } }
public void ShouldWork_TimeSeries() { const int numberOfCompanies = 77; const int numberOfTimeSeriesEntriesPerCompany = 333; var now = DateTime.UtcNow; using (var store = GetDocumentStore(new Options { ModifyDocumentStore = s => s.Conventions.MaxNumberOfRequestsPerSession = int.MaxValue })) { new SimpleTimeSeriesMapReduce().Execute(store); using (var session = store.OpenSession()) { for (var i = 0; i < numberOfCompanies; i++) { var company = new Company { Name = $"C_{i}" }; session.Store(company, $"companies/{i}"); var companyTimeSeries = session.TimeSeriesFor(company, "StockPrice"); for (var j = 0; j < numberOfTimeSeriesEntriesPerCompany; j++) { companyTimeSeries.Append(now.AddMinutes(j), j); } session.SaveChanges(); } } for (var i = 0; i < numberOfCompanies; i++) { Indexes.WaitForIndexing(store); RavenTestHelper.AssertNoIndexErrors(store); AssertCompanies(numberOfCompanies - i); using (var session = store.OpenSession()) { session.Delete($"companies/{i}"); session.SaveChanges(); } } void AssertCompanies(int count) { using (var session = store.OpenSession()) { var results = session .Query <SimpleTimeSeriesMapReduce.Result, SimpleTimeSeriesMapReduce>() .ToList(); Assert.Equal(count, results.Count); foreach (var result in results) { Assert.NotNull(result.DocumentId); Assert.Equal(numberOfTimeSeriesEntriesPerCompany, result.Count); } } } } }