Пример #1
0
		public void LinqQueryWithIndexIsCaseInsensitive()
		{
			using (var store = this.NewDocumentStore())
			{
				var definition = new IndexDefinitionBuilder<Company>
				{
					Map = docs => from doc in docs
								  select new
								  {
									  doc.Name
								  }
				}.ToIndexDefinition(store.Conventions);
				store.DatabaseCommands.PutIndex("CompanyByName",
												definition);

				using (var session = store.OpenSession())
				{
					session.Store(new Company { Name = "Google" });
					session.Store(new Company
					{
						Name =
							"HibernatingRhinos"
					});
					session.SaveChanges();

					var company =
						session.Query<Company>("CompanyByName")
							.Customize(x=>x.WaitForNonStaleResults())
							.Where(x=>x.Name == "Google")
							.FirstOrDefault();

					Assert.NotNull(company);
				}
			}
		}
Пример #2
0
		public void LinqQueryWithStaticCallOnEnumerableIsCanBeCompiledAndRun()
		{
			var indexDefinition = new IndexDefinitionBuilder<Page>
			{
				Map = pages => from p in pages
							   from coAuthor in p.CoAuthors.DefaultIfEmpty()
							   select new
							   {
								   p.Id,
								   CoAuthorUserID = coAuthor != null ? coAuthor.UserId : -1
							   }
			}.ToIndexDefinition(new DocumentConvention());

			var mapInstance = new DynamicViewCompiler("testView",
													  indexDefinition, ".").
				GenerateInstance();

			var conventions = new DocumentConvention();
			var o = RavenJObject.FromObject(page,conventions.CreateSerializer());
			o["@metadata"] = new RavenJObject {{"Raven-Entity-Name", "Pages"}};
			dynamic dynamicObject = new DynamicJsonObject(o);

			var result = mapInstance.MapDefinitions[0](new[] { dynamicObject }).ToList<object>();
			Assert.Equal("{ Id = 0, CoAuthorUserID = 1, __document_id =  }", result[0].ToString());
			Assert.Equal("{ Id = 0, CoAuthorUserID = 2, __document_id =  }", result[1].ToString());
		}
Пример #3
0
        public void Convert_select_many_will_keep_doc_id()
        {
            IndexDefinition indexDefinition = new IndexDefinitionBuilder<Order>
            {
                Map = orders => from order in orders
                                from line in order.OrderLines
                                select new { line.ProductId }
            }.ToIndexDefinition(new DocumentConvention());
			var generator = new DynamicViewCompiler("test", indexDefinition,  ".")
                .GenerateInstance();


            var results = generator.MapDefinition(new[]
			{
				GetDocumentFromString(
				@"
                {
                    '@metadata': {'Raven-Entity-Name': 'Orders', '@id': 1},
                    'OrderLines': [{'ProductId': 2}, {'ProductId': 3}]
                }"),
				  GetDocumentFromString(
				@"
                {
                    '@metadata': {'Raven-Entity-Name': 'Orders', '@id': 2},
                    'OrderLines': [{'ProductId': 5}, {'ProductId': 4}]
                }")
			}).Cast<object>().ToArray();

            foreach (var result in results)
            {
                Assert.NotNull(TypeDescriptor.GetProperties(result).Find("__document_id", true));
            }
        }
Пример #4
0
		public void CanDefineHierarchicalIndexOnTheClient_WithLinq()
		{
			var indexDefinition = new IndexDefinitionBuilder<Person>
			{
				Map = people => from p in people
								from c in p.Hierarchy(x=>x.Children)
								select c.Name
			}.ToIndexDefinition(new DocumentConvention());

			Assert.Equal("docs.People\r\n\t.SelectMany(p => Hierarchy(p, \"Children\"), (p, c) => c.Name)", indexDefinition.Map);
		}
Пример #5
0
		public void WillNotForgetCastToNullableDateTime()
		{
			var indexDefinition = new IndexDefinitionBuilder<DanTurner.Person>
			{
				Map = persons => from p in persons select new {DateTime = (DateTime?) null}
			}.ToIndexDefinition(new DocumentConvention());

			const string expected = @"docs.People.Select(p => new {
    DateTime = ((DateTime ? ) null)
})";
			Assert.Equal(expected, indexDefinition.Map);
		}
Пример #6
0
        public void WillNotForgetCastToNullableDateTime()
        {
            var indexDefinition = new IndexDefinitionBuilder<Person>()
            {
                Map = persons => from p in persons select new {DateTime = (DateTime?) null}
            }.ToIndexDefinition(new DocumentConvention{PrettifyGeneratedLinqExpressions = false});

            const string expected = @"docs.People.Select(p => new {
    DateTime = ((DateTime ? ) null)
})";
            Assert.Equal(expected, indexDefinition.Map);
        }
Пример #7
0
		public void CanCompileComplexQuery()
		{
			var indexDefinition = new IndexDefinitionBuilder<Person>()
			{
				Map = people => from person in people
				                from role in person.Roles
				                where role == "Student"
				                select new { role }
			}.ToIndexDefinition(new DocumentConvention());

			new DynamicViewCompiler("test", indexDefinition,  ".")
                .GenerateInstance();
		}
Пример #8
0
		public void CanDefineHierarchicalIndexOnTheClient_WithLinq2()
		{
			var indexDefinition = new IndexDefinitionBuilder<Container>
			{
				Map = containers => from c in containers
									select new
									{
										Names = c.Hierarchy(x => x.Containers).Select(x => x.Name)
									}
			}.ToIndexDefinition(new DocumentConvention());

			Assert.Equal("docs.Containers\r\n\t.Select(c => new {Names = Hierarchy(c, \"Containers\")\r\n\t.Select(x => x.Name)})", indexDefinition.Map);
		}
Пример #9
0
		public void LinqQueryWithStaticCallOnEnumerableIsTranslatedToExtensionMethod()
		{
			var indexDefinition = new IndexDefinitionBuilder<Page>
			{
				Map = pages => from p in pages
							   from coAuthor in p.CoAuthors.DefaultIfEmpty()
							   select new
							   {
								   p.Id,
								   CoAuthorUserID = coAuthor != null ? coAuthor.UserId : -1
							   }
			}.ToIndexDefinition(new DocumentConvention());
			Assert.Contains("p.CoAuthors.DefaultIfEmpty()", indexDefinition.Map);
		}
Пример #10
0
		public void Can_define_index_with_WhereEntityIs()
		{
			var idxBuilder = new IndexDefinitionBuilder<object>
			{
				Map =
					docs =>
					from course in (IEnumerable<Course>) docs
					select new {course.Id, course},

				TransformResults =
					(database, docs) =>
					from course in (IEnumerable<Course>) docs
					select new
					{
						item = course.Name,
						id = course.Id,
						iconCls = "course",
						leaf = false,
						expanded = true,
						children =
						from unit in course.Syllabus
						select new
						{
							item = unit.Name,
							id = unit.Name,
							iconCls = "unit",
							leaf = false,
							expanded = true,
							children =
							from notebook in unit.Notebooks
							select new
							{
								item = notebook.Name,
								id = notebook.Id,
								courseId = course.Id,
								iconCls = "notebook",
								type = notebook.Type,
								leaf = true,
							}
						}
					}
			};

			using(var store = NewDocumentStore())
			{
				var indexDefinition = idxBuilder.ToIndexDefinition(store.Conventions);
				store.DatabaseCommands.PutIndex("test", indexDefinition);
			}
		}
		public void Id_on_member_should_not_be_converted_to_document_id()
		{
			var generated = new IndexDefinitionBuilder<SubCategory>
			{
				Map = subs => from subCategory in subs
							  select new
							  {
								  CategoryId = subCategory.Id,
								  SubCategoryId = subCategory.Parent.Id
							  }
			}.ToIndexDefinition(new DocumentConvention());
			
			Assert.Contains("CategoryId = subCategory.__document_id", generated.Map);
			Assert.Contains("SubCategoryId = subCategory.Parent.Id", generated.Map);
		}
Пример #12
0
		public void Can_project_Id_from_transformResults()
		{
			using (GetNewServer())
			using (var store = new DocumentStore {Url = "http://localhost:8079"})
			{
				store.Initialize();
				store.Conventions.FindIdentityProperty = (x => x.Name == "Id");
				var indexDefinition = new IndexDefinitionBuilder<Shipment1, Shipment1>()
				                      	{
				                      		Map = docs => from doc in docs
				                      		              select new
				                      		                     	{
				                      		                     		doc.Id
				                      		                     	},
				                      		TransformResults = (database, results) => from doc in results
				                      		                                          select new
				                      		                                                 	{
				                      		                                                 		Id = doc.Id,
				                      		                                                 		Name = doc.Name
				                      		                                                 	}

				                      	}.ToIndexDefinition(store.Conventions);
				store.DatabaseCommands.PutIndex(
					"AmazingIndex1",
					indexDefinition);


				using (var session = store.OpenSession())
				{
					session.Store(new Shipment1()
					              	{
					              		Id = "shipment1",
					              		Name = "Some shipment"
					              	});
					session.SaveChanges();

					var shipment = session.Query<Shipment1>("AmazingIndex1")
						.Customize(x => x.WaitForNonStaleResults())
						.Select(x => new Shipment1
						             	{
						             		Id = x.Id,
						             		Name = x.Name
						             	}).Take(1).SingleOrDefault();

					Assert.NotNull(shipment.Id);
				}
			}
		}
Пример #13
0
		public void Can_define_index_with_WhereEntityIs()
		{
			var idxBuilder = new IndexDefinitionBuilder<object>("test")
			{
				Map =
					docs =>
					from course in (IEnumerable<Course>) docs
					select new {course.Id, course},
			};

			using(var store = NewDocumentStore())
			{
				var indexDefinition = idxBuilder.ToIndexDefinition(store.Conventions);
				store.DatabaseCommands.PutIndex("test", indexDefinition);
			}
		}
Пример #14
0
		public void CanRunSpatialQueriesInMemory()
		{
			var documentStore = new EmbeddableDocumentStore { RunInMemory = true };
			documentStore.Initialize();
			var def = new IndexDefinitionBuilder<Listing>
			{
				Map = listings => from listingItem in listings
								  select new
								  {
									  listingItem.ClassCodes,
									  listingItem.Latitude,
									  listingItem.Longitude,
									  _ = SpatialIndex.Generate(listingItem.Latitude, listingItem.Longitude)
								  }
			};
			documentStore.DatabaseCommands.PutIndex("RadiusClassifiedSearch", def);
		}
		public void LinqQueryWithStaticCallOnEnumerableIsTranslatedToExtensionMethod()
		{
			var indexDefinition = new IndexDefinitionBuilder<Page>
			{
				Map = pages => from p in pages
							   from coAuthor in Enumerable.DefaultIfEmpty(p.CoAuthors)
							   select new
							   {
								   p.Id,
								   CoAuthorUserID = coAuthor != null ? coAuthor.UserId : -1
							   }
			}.ToIndexDefinition(new DocumentConvention());
			var expectedMapTranslation =
				@"docs.Pages
	.SelectMany(p => p.CoAuthors.DefaultIfEmpty(), (p, coAuthor) => new {Id = p.Id, CoAuthorUserID = coAuthor != null ? coAuthor.UserId : -1})";
			Assert.Equal(expectedMapTranslation, indexDefinition.Map);
		}
Пример #16
0
		public void DefaultIndexingBehaviourAllowStartsWith()
		{
			using (var store = this.NewDocumentStore())
			{
				var index = new IndexDefinitionBuilder<Blog, BlogTagItem>()
				{
					Map = docs => from doc in docs
								  from tag in doc.Tags
								  select new
								  {
									  tag.Name,
									  Count = 1
								  },
					Reduce = results => from result in results
										group result by result.Name into g
										select new
										{
											Name = g.Key,
											Count = g.Count()
										}

				}.ToIndexDefinition(store.Conventions);

				store.DatabaseCommands.PutIndex("TagInfo", index);


				using (var session = store.OpenSession())
				{
					var newBlog = new Blog()
					{
						Tags = new[]{
							 new BlogTag() { Name = "SuperCallaFragalisticExpealadocious" }
						}
					};
					session.Store(newBlog);
					session.SaveChanges();

					var result = session.Query<BlogTagItem>("TagInfo")
						.Customize(x => x.WaitForNonStaleResults())
						.Where(x => x.Name.StartsWith("Su"))
						.FirstOrDefault();

					Assert.NotNull(result);
				}
			}
		}
		public void CanProjectIdFromTransformResults()
		{
			using (var store = NewDocumentStore())
			{
				var indexDefinition = new IndexDefinitionBuilder<Shipment, Shipment>()
				                      	{
				                      		Map = docs => from doc in docs
				                      		              select new
				                      		                     	{
				                      		                     		doc.Id
				                      		                     	},
				                      		TransformResults = (database, results)  => from doc in results
				                      		                                           select new 
				                      		                                                  	{
				                      		                                                  		Id = doc.Id,
				                      		                                                  		Name = doc.Name
				                      		                                                  	}
												   
				                      	}.ToIndexDefinition(store.Conventions);
				store.DatabaseCommands.PutIndex(
					"AmazingIndex",
					indexDefinition);


				using (var session = store.OpenSession())
				{
					session.Store(new Shipment()
					{
						Id = "shipment1",
						Name = "Some shipment"
					});
					session.SaveChanges();

					var shipment = session.Query<Shipment>("AmazingIndex")
						.Customize(x=>x.WaitForNonStaleResults())
						.Select(x => new Shipment
						{
							Id = x.Id,
							Name = x.Name
						}).Take(1).SingleOrDefault();
					
					Assert.NotNull(shipment.Id);
				}
			}
		}
Пример #18
0
		public void with_index_and_some_entities(Action<IDocumentSession> action)
		{
			using (var store = NewDocumentStore(requestedStorage: "esent"))
			{
				var indexDefinition = new IndexDefinitionBuilder<Entity, EntityCount>()
				{
					Map = docs => docs.Select(doc => new { Name = doc.Name, NormalizedName = doc.Name, Count = 1 }),
					Reduce = docs => from doc in docs
									 group doc by new { doc.Name } into g
									 select new { Name = g.Key.Name, NormalizedName = g.Key.Name, Count = g.Sum(c => c.Count) },
					Indexes =
						{
							{e => e.Name, FieldIndexing.NotAnalyzed }
						}
				}.ToIndexDefinition(store.Conventions);

				indexDefinition.Analyzers = new Dictionary<string, string>()
				{
					{"NormalizedName", typeof (CustomAnalyzer).AssemblyQualifiedName}
				};

				store.DatabaseCommands.PutIndex("someIndex", indexDefinition);

				using (var session = store.OpenSession())
				{
					session.Store(new Entity() { Name = entityName });
					session.Store(new Entity() { Name = entityName });
					session.Store(new Entity() { Name = entityName });
					session.Store(new Entity() { Name = entityName });
					session.Store(new Entity() { Name = "someOtherName1" });
					session.Store(new Entity() { Name = "someOtherName2" });
					session.Store(new Entity() { Name = "someOtherName3" });
					session.SaveChanges();
				}
				
				// This wait should update the index with all changes...
				WaitForIndex(store, "someIndex");

				using (var session2 = store.OpenSession())
				{
					action(session2);
				}
			}
		}
Пример #19
0
        public void get_index_names()
        {
            using (IDocumentStore store = NewDocumentStore())
            {
                for (int i = 1; i <= 10; i++)
                {
                    using (var session = store.OpenSession())
                    {
                        session.Store(new Entity()
                        {
                            OrganizationId = 1,
                            HistoryCode = 2,
                            CaseId = 3
                        });
                        session.SaveChanges();
                    }
                }

                for (int i = 1; i <= 30; i++)
                {
                    IndexDefinitionBuilder<Entity> builder = new IndexDefinitionBuilder<Entity>
                    {
                        Map = entities => from e in entities
                            select new
                            {
                                Id = e.OrganizationId,
                                Code = e.HistoryCode,
                                Case = e.CaseId
                            }
                    };

                    store.DatabaseCommands.PutIndex("TestIndex/Numer"+i , builder.ToIndexDefinition(store.Conventions));
                }

                WaitForIndexing(store);

                using (var session = store.OpenSession())
                {
                    Task.Run(() => LoopResetIndex(session)).Wait();
                }
            }
        }
        public void Id_on_member_should_not_be_converted_to_document_id()
        {
            var generated = new IndexDefinitionBuilder<SubCategory>
            {
                Map = subs => from subCategory in subs
                              select new
                              {
                                  CategoryId = subCategory.Id,
                                  SubCategoryId = subCategory.Parent.Id
                              }
            }.ToIndexDefinition(new DocumentConvention());
            var original = new IndexDefinition
            {
                Map =
                    @"docs.SubCategories
	.Select(subCategory => new {CategoryId = subCategory.__document_id, SubCategoryId = subCategory.Parent.Id})"
            };

            Assert.Equal(original.Map, generated.Map);
        }
Пример #21
0
		public void TransformResultsFactoredIntoEqualityCheck()
		{
			IndexDefinition definitionOne = new IndexDefinitionBuilder<Blog, Blog>()
			{
				Map = docs => from doc in docs
							  select new { doc.Property },
				TransformResults = (database, results) => from result in results
														  select new
														  {
															  Property = result.Property
														  }
			}.ToIndexDefinition(new Client.Document.DocumentConvention());

			IndexDefinition definitionTwo = new IndexDefinitionBuilder<Blog, Blog>()
			{
				Map = docs => from doc in docs
							  select new { doc.Property }
			}.ToIndexDefinition(new Client.Document.DocumentConvention());

			Assert.False(definitionOne.Equals(definitionTwo));
		}
Пример #22
0
        public void Convert_using_id()
        {
            IndexDefinition generated = new IndexDefinitionBuilder <User, Named>
            {
                Map = users => from user in users
                      where user.Location == "Tel Aviv"
                      select new { user.Name, user.Id },
                Stores = { { user => user.Name, FieldStorage.Yes } }
            }.ToIndexDefinition(new DocumentConvention {
                PrettifyGeneratedLinqExpressions = false
            });
            var original = new IndexDefinition
            {
                Stores = { { "Name", FieldStorage.Yes } },
                Map    = @"docs.Users.Where(user => user.Location == ""Tel Aviv"").Select(user => new {
    Name = user.Name,
    Id = user.__document_id
})"
            };

            Assert.Equal(original.Map, generated.Map);
            Assert.Equal(original, generated);
        }
Пример #23
0
        private void Convert_map_reduce_query_with_map_(Expression <Func <IEnumerable <User>, IEnumerable> > mapExpression, string expectedIndexString)
        {
            IndexDefinition generated = new IndexDefinitionBuilder <User, LocationCount>
            {
                Map    = mapExpression,
                Reduce = counts => from agg in counts
                         group agg by agg.Location
                         into g
                         select new { Location = g.Key, Count = g.Sum(x => x.Count) },
            }.ToIndexDefinition(DocumentConventions.Default);

            var original = new IndexDefinition
            {
                Maps   = { expectedIndexString },
                Reduce = @"results.GroupBy(agg => agg.Location).Select(g => new {
    Location = g.Key,
    Count = Enumerable.Sum(g, x => ((int) x.Count))
})".Replace("\r\n", Environment.NewLine)
            };

            Assert.Equal(expectedIndexString, generated.Maps.First());
            Assert.Equal(original.Reduce, generated.Reduce);
        }
        public void Convert_map_reduce_query()
        {
            IndexDefinition generated = new IndexDefinitionBuilder <User, LocationCount>
            {
                Map = users => from user in users
                      select new { user.Location, Count = 1 },
                Reduce = counts => from agg in counts
                         group agg by agg.Location
                         into g
                         select new { Location = g.Key, Count = g.Sum(x => x.Count) },
            }.ToIndexDefinition(new DocumentConvention());
            var original = new IndexDefinition
            {
                Map    = @"docs.Users
	.Select(user => new {Location = user.Location, Count = 1})"    ,
                Reduce = @"results
	.GroupBy(agg => agg.Location)
	.Select(g => new {Location = g.Key, Count = g.Sum(x => ((System.Int32)(x.Count)))})"
            };

            Assert.Equal(original.Map, generated.Map);
            Assert.Equal(original.Reduce, generated.Reduce);
        }
Пример #25
0
        public void CannotPutIndexWithNameClash()
        {
            using (var store = GetDocumentStore())
            {
                var indexDefBuilder1 = new IndexDefinitionBuilder <Order>()
                {
                    Map = docs => from doc in docs select new { Index = doc.Company },
                };

                var indexDefinition1 = indexDefBuilder1.ToIndexDefinition(store.Conventions);
                indexDefinition1.Name = "Index_With_Name_Clash";

                var indexDefBuilder2 = new IndexDefinitionBuilder <Order>()
                {
                    Map = docs => from doc in docs select new { Index = doc.Company },
                };

                var indexDefinition2 = indexDefBuilder2.ToIndexDefinition(store.Conventions);
                indexDefinition2.Name = "Index/With/Name/Clash";

                Assert.Throws <IndexCreationException>(() => store.Maintenance.Send(new PutIndexesOperation(indexDefinition1, indexDefinition2)));
            }
        }
Пример #26
0
        public void WillNotSkipDuplicates()
        {
            using (var store = GetDocumentStore())
            {
                var indexDefinition = new IndexDefinitionBuilder <BlogPost>
                {
                    Map = posts => from post in posts
                          from tag in post.Tags
                          select new { Tag = tag }
                }.ToIndexDefinition(store.Conventions);
                indexDefinition.Name = "BlogPosts/PostsCountByTag";
                store.Maintenance.Send(new PutIndexesOperation(new[] { indexDefinition }));



                using (var session = store.OpenSession())
                {
                    session.Store(new BlogPost
                    {
                        Tags = new[] { "Daniel", "Oren" }
                    });

                    session.SaveChanges();

                    Indexes.WaitForIndexing(store);

                    using (var commands = store.Commands())
                    {
                        var result = commands.Query(new IndexQuery()
                        {
                            Query = "FROM INDEX 'BlogPosts/PostsCountByTag'", SkipDuplicateChecking = true
                        });
                        Assert.Equal(2, result.Results.Length);
                    }
                }
            }
        }
Пример #27
0
        public void LinqQueryWithIndexIsCaseInsensitive()
        {
            using (var store = this.NewDocumentStore())
            {
                var definition = new IndexDefinitionBuilder <Company>
                {
                    Map = docs => from doc in docs
                          select new
                    {
                        doc.Name
                    }
                }.ToIndexDefinition(store.Conventions);
                store.DatabaseCommands.PutIndex("CompanyByName",
                                                definition);

                using (var session = store.OpenSession())
                {
                    session.Store(new Company {
                        Name = "Google"
                    });
                    session.Store(new Company
                    {
                        Name =
                            "HibernatingRhinos"
                    });
                    session.SaveChanges();

                    var company =
                        session.Query <Company>("CompanyByName")
                        .Customize(x => x.WaitForNonStaleResults())
                        .Where(x => x.Name == "Google")
                        .FirstOrDefault();

                    Assert.NotNull(company);
                }
            }
        }
Пример #28
0
        public void LuceneQueryWithIndexIsCaseInsensitive()
        {
            using (var store = GetDocumentStore())
            {
                var definition = new IndexDefinitionBuilder <Company>("CompanyByName")
                {
                    Map = docs => from doc in docs
                          select new
                    {
                        doc.Name
                    }
                }.ToIndexDefinition(store.Conventions);

                store.Admin.Send(new PutIndexesOperation(definition));

                using (var session = store.OpenSession())
                {
                    session.Store(new Company {
                        Name = "Google"
                    });
                    session.Store(new Company
                    {
                        Name =
                            "HibernatingRhinos"
                    });
                    session.SaveChanges();

                    var company =
                        session.Advanced.DocumentQuery <Company>("CompanyByName")
                        .WhereEquals("Name", "Google")
                        .WaitForNonStaleResults()
                        .FirstOrDefault();

                    Assert.NotNull(company);
                }
            }
        }
        public void SelectIdFromDocumentWithIndexedQuery()
        {
            using (var store = GetDocumentStore())
            {
                var indexDefinition = new IndexDefinitionBuilder <Shipment>()
                {
                    Map = docs => from doc in docs
                          select new
                    {
                        doc.Id
                    }
                }.ToIndexDefinition(store.Conventions);
                indexDefinition.Name = "AmazingIndex";
                store.Admin.Send(new PutIndexesOperation(new[] { indexDefinition }));


                using (var session = store.OpenSession())
                {
                    session.Store(new Shipment()
                    {
                        Id   = "shipment1",
                        Name = "Some shipment"
                    });
                    session.SaveChanges();

                    var shipment = session.Query <Shipment>("AmazingIndex")
                                   .Customize(x => x.WaitForNonStaleResults())
                                   .Select(x => new Shipment
                    {
                        Id   = x.Id,
                        Name = x.Name
                    }).Take(1).SingleOrDefault();

                    Assert.NotNull(shipment.Id);
                }
            }
        }
Пример #30
0
        public void Multitenancy_Test()
        {
            DoNotReuseServer();
            using (var store = GetDocumentStore())
            {
                var doc = new DatabaseRecord("Test");
                store.Admin.Server.Send(new CreateDatabaseOperation(doc));
                store.Database = "Test";

                var indexDefinition = new IndexDefinitionBuilder <Test, Test>("TestIndex")
                {
                    Map = movies => from movie in movies
                          select new { movie.Name }
                }.ToIndexDefinition(new DocumentConventions());
                indexDefinition.Name = "TestIndex";
                store.Admin.ForDatabase("Test").Send(new PutIndexesOperation(new[] { indexDefinition }));

                using (var session = store.OpenSession())
                {
                    session.Store(new Test {
                        Name = "xxx"
                    });

                    session.SaveChanges();
                }

                using (var session = store.OpenSession())
                {
                    var result = session.Query <Test>("TestIndex")
                                 .Customize(x => x.WaitForNonStaleResults())
                                 .Where(x => x.Name == "xxx")
                                 .FirstOrDefault();

                    Assert.NotNull(result);
                }
            }
        }
Пример #31
0
        public void Convert_map_reduce_query_with_map_(Expression <Func <IEnumerable <User>, IEnumerable> > mapExpression, string expectedIndexString)
        {
            IndexDefinition generated = new IndexDefinitionBuilder <User, LocationCount>
            {
                Map    = mapExpression,
                Reduce = counts => from agg in counts
                         group agg by agg.Location
                         into g
                         select new { Location = g.Key, Count = g.Sum(x => x.Count) },
            }.ToIndexDefinition(new DocumentConvention {
                PrettifyGeneratedLinqExpressions = false
            });
            var original = new IndexDefinition
            {
                Map    = expectedIndexString,
                Reduce = @"results.GroupBy(agg => agg.Location).Select(g => new {
    Location = g.Key,
    Count = Enumerable.Sum(g, x => ((int) x.Count))
})"
            };

            Assert.Equal(expectedIndexString, generated.Map);
            Assert.Equal(original.Reduce, generated.Reduce);
        }
Пример #32
0
        public void CanCreateIndexByTwoProperties()
        {
            using (var store = GetDocumentStore())
                using (var session = store.OpenSession())
                {
                    session.Store(new Foo {
                        Id = "1", Value = "foo"
                    });


                    session.Store(new Foo {
                        Id = "2", Value = "bar"
                    });


                    session.SaveChanges();
                    var index = new IndexDefinitionBuilder <Foo>("FeedSync/TwoProperties")
                    {
                        Map = ids => from id in ids
                              select new { id.Id, id.Value },
                    }.ToIndexDefinition(new DocumentConventions());
                    store.Admin.Send(new PutIndexesOperation(index));
                }
        }
Пример #33
0
        public void Can_perform_First_and_FirstOrDefault_Query()
        {
            using (var store = GetDocumentStore())
            {
                store.Initialize();

                string indexName = "UserIndex";
                using (var session = store.OpenSession())
                {
                    AddData(session);
                    var indexDefinition = new IndexDefinitionBuilder <User, User>()
                    {
                        Map = docs => from doc in docs
                              select new { doc.Name, doc.Age },
                    }.ToIndexDefinition(store.Conventions);
                    indexDefinition.Name = indexName;
                    store.Maintenance.Send(new PutIndexesOperation(new[] { indexDefinition }));

                    WaitForQueryToComplete(session);

                    var firstItem = session.Query <User>(indexName).OrderBy(x => x.Name)
                                    .First();
                    Assert.Equal(firstUser, firstItem);

                    //This should pull out the 1st parson ages 60, i.e. "Bob"
                    var firstAgeItem = session.Query <User>(indexName)
                                       .First(x => x.Age == 60);
                    Assert.Equal("Bob", firstAgeItem.Name);

                    //No-one is aged 15, so we should get null
                    var firstDefaultItem = session.Query <User>(indexName)
                                           .FirstOrDefault(x => x.Age == 15);
                    Assert.Null(firstDefaultItem);
                }
            }
        }
Пример #34
0
        public void with_index_and_some_entities(Action <IDocumentSession> action)
        {
            using (var store = NewDocumentStore(requestedStorage: "esent"))
            {
                var indexDefinition = new IndexDefinitionBuilder <Entity, EntityCount>()
                {
                    Map    = docs => docs.Select(doc => new { Name = doc.Name, NormalizedName = doc.Name, Count = 1 }),
                    Reduce = docs => from doc in docs
                             group doc by new { doc.Name } into g
                    select new { Name = g.Key.Name, NormalizedName = g.Key.Name, Count = g.Sum(c => c.Count) },
                    Indexes =
                    {
                        { e => e.Name, FieldIndexing.NotAnalyzed }
                    }
                }.ToIndexDefinition(store.Conventions);

                indexDefinition.Analyzers = new Dictionary <string, string>()
                {
                    { "NormalizedName", typeof(CustomAnalyzer).AssemblyQualifiedName }
                };

                store.DatabaseCommands.PutIndex("someIndex", indexDefinition);

                using (var session = store.OpenSession())
                {
                    session.Store(new Entity()
                    {
                        Name = entityName
                    });

                    session.Store(new Entity()
                    {
                        Name = entityName
                    });
                    session.Store(new Entity()
                    {
                        Name = entityName
                    });
                    session.Store(new Entity()
                    {
                        Name = entityName
                    });
                    session.Store(new Entity()
                    {
                        Name = "someOtherName1"
                    });
                    session.Store(new Entity()
                    {
                        Name = "someOtherName2"
                    });
                    session.Store(new Entity()
                    {
                        Name = "someOtherName3"
                    });
                    session.SaveChanges();
                }

                // This wait should update the index with all changes...
                WaitForIndex(store, "someIndex");

                using (var session2 = store.OpenSession())
                {
                    action(session2);
                }
            }
        }
Пример #35
0
        public async Task Sample()
        {
            using (var store = new DocumentStore())
            {
                #region indexes_2
                // deploy index to `DefaultDatabase` for given `DocumentStore`
                // using store `Conventions`
                new Orders_Totals().Execute(store);

                // deploy asynchronously index to `DefaultDatabase` for given `DocumentStore`
                // using store `Conventions`
                await new Orders_Totals().ExecuteAsync(store.AsyncDatabaseCommands, store.Conventions);
                #endregion

                #region indexes_3
                // deploy index to `Northwind` database
                // using store `Conventions`
                new Orders_Totals().Execute(store.DatabaseCommands.ForDatabase("Northwind"), store.Conventions);
                #endregion

                #region indexes_4
                // deploy all indexes (and transformers)
                // from assembly where `Orders_Totals` is found
                // to `DefaultDatabase` for given `DocumentStore`
                IndexCreation.CreateIndexes(typeof(Orders_Totals).Assembly, store);
                #endregion

                #region indexes_5
                store
                .DatabaseCommands
                .PutIndex("Orders/Totals", new IndexDefinition
                {
                    Map = @"from order in docs.Orders
							select new { order.Employee,  order.Company, Total = order.Lines.Sum(l => (l.Quantity * l.PricePerUnit) * (1 - l.Discount)) }"
                });
                #endregion

                #region indexes_6
                IndexDefinitionBuilder <Order> builder = new IndexDefinitionBuilder <Order>();
                builder.Map = orders => from order in orders
                              select new
                {
                    order.Employee,
                    order.Company,
                    Total = order.Lines.Sum(l => (l.Quantity * l.PricePerUnit) * (1 - l.Discount))
                };

                store
                .DatabaseCommands
                .PutIndex("Orders/Totals", builder.ToIndexDefinition(store.Conventions));
                #endregion

                using (var session = store.OpenSession())
                {
                    #region indexes_7
                    List <Employee> employees = session
                                                .Query <Employee>()
                                                .Where(x => x.FirstName == "Robert" && x.LastName == "King")
                                                .ToList();
                    #endregion
                }
            }
        }
Пример #36
0
 /// <summary>
 /// Puts the index for the specified name
 /// </summary>
 /// <typeparam name="TDocument">The type of the document.</typeparam>
 /// <typeparam name="TReduceResult">The type of the reduce result.</typeparam>
 /// <param name="name">The name.</param>
 /// <param name="indexDef">The index def.</param>
 /// <param name="overwrite">if set to <c>true</c> [overwrite].</param>
 public string PutIndex <TDocument, TReduceResult>(string name, IndexDefinitionBuilder <TDocument, TReduceResult> indexDef, bool overwrite)
 {
     return(PutIndex(name, indexDef.ToIndexDefinition(convention), overwrite));
 }
Пример #37
0
		public void Convert_simple_query_with_char_literal()
		{
			IndexDefinition generated = new IndexDefinitionBuilder<User> {
				Map = users => from user in users
							   where user.Name.Contains('C')
							   select user
			}.ToIndexDefinition(new DocumentConvention());
			var original = new IndexDefinition {
				Map = @"docs.Users
	.Where(user => user.Name.Contains('C'))"
			};
			Assert.Equal(original, generated);
		}
Пример #38
0
        public void Can_perform_DateTime_Comparison_Queries()
        {
            DateTime firstTime  = SystemTime.UtcNow;
            DateTime secondTime = firstTime.AddMonths(1);  // use .AddHours(1) to get a second bug, timezone related
            DateTime thirdTime  = secondTime.AddMonths(1); // use .AddHours(1) to get a second bug, timezone related

            using (var store = GetDocumentStore())
            {
                string indexName = "UserIndex";
                using (var session = store.OpenSession())
                {
                    session.Store(new User {
                        Name = "First", Created = firstTime
                    });
                    session.Store(new User {
                        Name = "Second", Created = secondTime
                    });
                    session.Store(new User {
                        Name = "Third", Created = thirdTime
                    });
                    session.SaveChanges();

                    var indexDefinition = new IndexDefinitionBuilder <User, User>()
                    {
                        Map = docs => from doc in docs
                              select new
                        {
                            doc.Name,
                            doc.Created
                        },
                    }.ToIndexDefinition(store.Conventions);
                    indexDefinition.Name = indexName;
                    store.Maintenance.Send(new PutIndexesOperation(new[] { indexDefinition }));


                    WaitForIndexing(store);

                    Assert.Equal(3, session.Query <User>(indexName).ToArray().Length);

                    var testQuery = session.Query <User>(indexName)
                                    .Where(x => x.Created > secondTime)
                                    .ToArray();
                    Assert.Equal(1, testQuery.Count());
                    Assert.True(testQuery.Select(q => q.Name).Contains("Third"));

                    testQuery = session.Query <User>(indexName)
                                .Where(x => x.Created >= secondTime)
                                .ToArray();
                    Assert.Equal(2, testQuery.Count());
                    Assert.True(testQuery.Select(q => q.Name).Contains("Third"));
                    Assert.True(testQuery.Select(q => q.Name).Contains("Second"));

                    testQuery = session.Query <User>(indexName)
                                .Where(x => x.Created < secondTime)
                                .ToArray();
                    Assert.Equal(1, testQuery.Count());
                    Assert.True(testQuery.Select(q => q.Name).Contains("First"));

                    testQuery = session.Query <User>(indexName)
                                .Where(x => x.Created <= secondTime)
                                .ToArray();
                    Assert.Equal(2, testQuery.Count());
                    Assert.True(testQuery.Select(q => q.Name).Contains("First"));
                    Assert.True(testQuery.Select(q => q.Name).Contains("Second"));

                    testQuery = session.Query <User>(indexName)
                                .Where(x => x.Created == secondTime)
                                .ToArray();
                    Assert.Equal(1, testQuery.Count());
                    Assert.True(testQuery.Select(q => q.Name).Contains("Second"));
                }
            }
        }
Пример #39
0
        public async Task Sample()
        {
            using (var store = new DocumentStore())
            {
                #region indexes_2
                // deploy index to database defined in `DocumentStore.Database` property
                // using default DocumentStore `Conventions`
                new Orders_Totals().Execute(store);

                // deploy asynchronously index to database defined in `DocumentStore.Database` property
                // using default DocumentStore `Conventions`
                await new Orders_Totals().ExecuteAsync(store, store.Conventions);
                #endregion

                #region indexes_3
                // deploy index to `Northwind` database
                // using default DocumentStore `Conventions`
                new Orders_Totals().Execute(store, store.Conventions, "Northwind");
                #endregion

                #region indexes_4
                // deploy all indexes
                // from assembly where `Orders_Totals` is found
                // to database defined in `DocumentStore.Database` property
                IndexCreation.CreateIndexes(typeof(Orders_Totals).Assembly, store);
                #endregion

                #region indexes_5
                store
                .Maintenance
                .Send(new PutIndexesOperation(new IndexDefinition
                {
                    Name = "Orders/Totals",
                    Maps =
                    {
                        @"from order in docs.Orders	
                              select new 
                              { 
                                  order.Employee, 
                                  order.Company,
                                  Total = order.Lines.Sum(l => (l.Quantity * l.PricePerUnit) * (1 - l.Discount))
                              }"
                    }
                }));
                #endregion

                #region indexes_6
                IndexDefinitionBuilder <Order> builder = new IndexDefinitionBuilder <Order>();
                builder.Map = orders => from order in orders
                              select new
                {
                    order.Employee,
                    order.Company,
                    Total = order.Lines.Sum(l => (l.Quantity * l.PricePerUnit) * (1 - l.Discount))
                };

                store
                .Maintenance
                .Send(new PutIndexesOperation(builder.ToIndexDefinition(store.Conventions)));
                #endregion

                using (var session = store.OpenSession())
                {
                    #region indexes_7
                    List <Employee> employees = session
                                                .Query <Employee>()
                                                .Where(x => x.FirstName == "Robert" && x.LastName == "King")
                                                .ToList();
                    #endregion
                }
            }
        }
Пример #40
0
		public void With_parantesis()
		{
			IndexDefinition generated = new IndexDefinitionBuilder<User, Named>
			{
				Map = users => from user in users
							   where user.Location == "Tel Aviv"
							   select new { Age = user.Age - (20 - user.Age) },
				Stores = { { user => user.Name, FieldStorage.Yes } }
			}.ToIndexDefinition(new DocumentConvention());
			var original = new IndexDefinition
			{
				Stores = { { "Name", FieldStorage.Yes } },
				Map = @"docs.Users.Where(user => user.Location == ""Tel Aviv"").Select(user => new {
    Age = user.Age - (20 - user.Age)
})"
			};

			Assert.Equal(original.Map, generated.Map);
		}
Пример #41
0
        public void DocumentQuerySelectFields()
        {
            using (var store = GetDocumentStore())
            {
                var definition = new IndexDefinitionBuilder <Order>("OrderByCompanyCountryIndex")
                {
                    Map = docs => from doc in docs
                          select new
                    {
                        doc.Company,
                        ShipTo_Country = doc.ShipTo.Country
                    }
                }.ToIndexDefinition(store.Conventions);
                store.Maintenance.Send(new PutIndexesOperation(definition));

                using (var session = store.OpenSession())
                {
                    session.Store(new Order
                    {
                        Company = "companies/1",
                        ShipTo  = new Address()
                        {
                            Country = "Sweden",
                            City    = "Stockholm"
                        }
                    });
                    session.Store(new Order
                    {
                        Company = "companies/1",
                        ShipTo  = new Address()
                        {
                            Country = "Germany",
                            City    = "Berlin"
                        }
                    });

                    session.Store(new Company
                    {
                        Name = "HR"
                    }, "companies/1");
                    session.SaveChanges();
                }

                WaitForIndexing(store);

                using (var session = store.OpenSession())
                {
                    var docQuery = session.Advanced
                                   .DocumentQuery <Order>("OrderByCompanyCountryIndex")
                                   .WhereEquals(x => x.ShipTo.Country, "Sweden")
                                   .SelectFields <OrderResult>(QueryData.CustomFunction(
                                                                   alias: "o",
                                                                   func: "{ Order : o, Company : load(o.Company) }")
                                                               );

                    Assert.Equal("from index 'OrderByCompanyCountryIndex' as o where ShipTo_Country = $p0 " +
                                 "select { Order : o, Company : load(o.Company) }", docQuery.ToString());

                    var result = docQuery.ToList();

                    Assert.Equal(1, result.Count);
                    Assert.Equal("HR", result[0].Company.Name);
                }
            }
        }
Пример #42
0
 public string PutIndex <TDocument, TReduceResult>(string name,
                                                   IndexDefinitionBuilder <TDocument, TReduceResult> indexDef)
 {
     return(AsyncHelpers.RunSync(() => asyncServerClient.PutIndexAsync(name, indexDef, default(CancellationToken))));
 }
Пример #43
0
        public void Convert_map_reduce_query()
        {
            IndexDefinition generated = new IndexDefinitionBuilder<User, LocationCount>
            {
                Map = users => from user in users
                               select new { user.Location, Count = 1 },
                Reduce = counts => from agg in counts
                                   group agg by agg.Location
                                       into g
                                       select new { Location = g.Key, Count = g.Sum(x => x.Count) },
            }.ToIndexDefinition(new DocumentConvention());
            var original = new IndexDefinition
            {
                Map = @"docs.Users
	.Select(user => new {Location = user.Location, Count = 1})",
                Reduce = @"results
	.GroupBy(agg => agg.Location)
	.Select(g => new {Location = g.Key, Count = g.Sum(x => x.Count)})"
            };

            Assert.Equal(original, generated);
        }
Пример #44
0
        public void Convert_map_reduce_query_with_map_(Expression<Func<IEnumerable<User>, IEnumerable>> mapExpression, string expectedIndexString)
        {
            IndexDefinition generated = new IndexDefinitionBuilder<User, LocationCount>
            {
                Map = mapExpression,
                Reduce = counts => from agg in counts
                                   group agg by agg.Location
                                       into g
                                       select new { Location = g.Key, Count = g.Sum(x => x.Count) },
            }.ToIndexDefinition(new DocumentConvention());
            var original = new IndexDefinition
            {
                Map = expectedIndexString,
                Reduce = @"results
	.GroupBy(agg => agg.Location)
	.Select(g => new {Location = g.Key, Count = g.Sum(x => x.Count)})"
            };

            Assert.Equal(original, generated);
        }
Пример #45
0
		public void Convert_simple_query()
		{
			IndexDefinition generated = new IndexDefinitionBuilder<User, Named>
			{
				Map = users => from user in users
							   where user.Location == "Tel Aviv"
							   select new { user.Name },
				Stores = { { user => user.Name, FieldStorage.Yes } }
			}.ToIndexDefinition(new DocumentConvention());
			var original = new IndexDefinition
			{
				Stores = { { "Name", FieldStorage.Yes } },
				Map = @"docs.Users
	.Where(user => user.Location == ""Tel Aviv"")
	.Select(user => new {Name = user.Name})"
			};

			Assert.Equal(original, generated);
		}
Пример #46
0
 /// <summary>
 /// Puts the index for the specified name
 /// </summary>
 /// <typeparam name="TDocument">The type of the document.</typeparam>
 /// <typeparam name="TReduceResult">The type of the reduce result.</typeparam>
 /// <param name="name">The name.</param>
 /// <param name="indexDef">The index def.</param>
 /// <param name="overwrite">if set to <c>true</c> [overwrite].</param>
 /// <returns></returns>
 public string PutIndex <TDocument, TReduceResult>(string name,
                                                   IndexDefinitionBuilder <TDocument, TReduceResult> indexDef, bool overwrite)
 {
     return(asyncServerClient.PutIndexAsync(name, indexDef, overwrite).ResultUnwrap());
 }
Пример #47
0
		public void Convert_simple_query_with_not_operator_and_nested_braces()
		{
			IndexDefinition generated = new IndexDefinitionBuilder<User, Named>
			{
				Map = users => from user in users
				               where !(user.Location == "Te(l) (A)viv")
				               select new {user.Name},
				Stores = {{user => user.Name, FieldStorage.Yes}}
			}.ToIndexDefinition(new DocumentConvention());
			var original = new IndexDefinition
			{
				Stores = {{"Name", FieldStorage.Yes}},
				Map = @"docs.Users.Where(user => !(user.Location == ""Te(l) (A)viv"")).Select(user => new {
    Name = user.Name
})"
			};

			Assert.Equal(original.Map, generated.Map);
			Assert.Equal(original, generated);
		}
Пример #48
0
 public string PutIndex <TDocument, TReduceResult>(string name,
                                                   IndexDefinitionBuilder <TDocument, TReduceResult> indexDef)
 {
     return(asyncServerClient.PutIndexAsync(name, indexDef, default(CancellationToken)).ResultUnwrap());
 }
Пример #49
0
 public string PutIndex <TDocument, TReduceResult>(string name,
                                                   IndexDefinitionBuilder <TDocument, TReduceResult> indexDef, bool overwrite)
 {
     return(AsyncHelpers.RunSync(() => asyncServerClient.PutIndexAsync(name, indexDef, overwrite)));
 }
Пример #50
0
        public void Can_Use_Where()
        {
            using (var store = GetDocumentStore())
            {
                const string indexName = "CommitByRevision";
                using (var session = store.OpenSession())
                {
                    AddData(session);
                    var indexDefinition = new IndexDefinitionBuilder <CommitInfo, CommitInfo>
                    {
                        Map = docs => from doc in docs
                              select new { doc.Revision },
                    }.ToIndexDefinition(store.Conventions);
                    indexDefinition.Name = indexName;
                    store.Admin.Send(new PutIndexesOperation(new[] { indexDefinition }));

                    WaitForIndexing(store);

                    var results = session.Query <CommitInfo>(indexName)
                                  .Where(x => x.Revision == 1);
                    //There is one CommitInfo with Revision == 1
                    Assert.Equal(1, results.ToArray().Count());

                    results = session.Query <CommitInfo>(indexName)
                              .Where(x => x.Revision == 0);
                    //There is not CommitInfo with Revision = 0 so hopefully we do not get any result
                    Assert.Equal(0, results.ToArray().Count());

                    results = session.Query <CommitInfo>(indexName)
                              .Where(x => x.Revision < 1);
                    //There are 0 CommitInfos which has Revision <1
                    Assert.Equal(0, results.ToArray().Count());

                    results = session.Query <CommitInfo>(indexName)
                              .Where(x => x.Revision < 2);
                    //There is one CommitInfo with Revision < 2
                    Assert.Equal(1, results.ToArray().Count());
                    //Revision of resulted CommitInfo has to be 1
                    var cinfo = results.ToArray()[0];
                    Assert.Equal(1, cinfo.Revision);

                    results = session.Query <CommitInfo>(indexName)
                              .Where(x => x.Revision <= 2);
                    //There are 2 CommitInfos which has Revision <=2
                    Assert.Equal(2, results.ToArray().Count());


                    results = session.Query <CommitInfo>(indexName)
                              .Where(x => x.Revision > 7);
                    //There are 0 CommitInfos which has Revision >7
                    Assert.Equal(0, results.ToArray().Count());

                    results = session.Query <CommitInfo>(indexName)
                              .Where(x => x.Revision > 6);
                    //There are 1 CommitInfos which has Revision >6
                    Assert.Equal(1, results.ToArray().Count());

                    results = session.Query <CommitInfo>(indexName)
                              .Where(x => x.Revision >= 6);
                    //There are 2 CommitInfos which has Revision >=6
                    Assert.Equal(2, results.ToArray().Count());

                    results = session.Query <CommitInfo>(indexName)
                              .Where(x => x.Revision > 6 && x.Revision < 6);
                    //There are 0 CommitInfos which has Revision >6 && <6
                    Assert.Equal(0, results.ToArray().Count());

                    results = session.Query <CommitInfo>(indexName)
                              .Where(x => x.Revision >= 6 && x.Revision <= 6);
                    //There are 1 CommitInfos which has Revision >=6 && <=6
                    Assert.Equal(1, results.ToArray().Count());

                    results = session.Query <CommitInfo>(indexName)
                              .Where(x => x.Revision >= 6 && x.Revision < 6);
                    //There are 0 CommitInfos which has Revision >=6 && <6
                    Assert.Equal(0, results.ToArray().Count());

                    results = session.Query <CommitInfo>(indexName)
                              .Where(x => x.Revision > 6 && x.Revision <= 6);
                    //There are 0 CommitInfos which has Revision >6 && <=6
                    Assert.Equal(0, results.ToArray().Count());

                    results = session.Query <CommitInfo>(indexName)
                              .Where(x => x.Revision >= 7 && x.Revision <= 1);
                    //There are 0 CommitInfos which has Revision >=7  && <= 1
                    Assert.Equal(0, results.ToArray().Count());

                    results = session.Query <CommitInfo>(indexName)
                              .Where(x => x.Revision > 7 && x.Revision < 1);
                    //There are 0 CommitInfos which has Revision >7  && < 1
                    Assert.Equal(0, results.ToArray().Count());


                    results = session.Query <CommitInfo>(indexName)
                              .Where(x => x.Revision > 7 || x.Revision < 1);
                    //There are 0 CommitInfos which has Revision >7  || < 1
                    Assert.Equal(0, results.ToArray().Count());

                    results = session.Query <CommitInfo>(indexName)
                              .Where(x => x.Revision >= 7 || x.Revision < 1);
                    //There are 1 CommitInfos which has Revision >=7  || < 1
                    Assert.Equal(1, results.ToArray().Count());

                    results = session.Query <CommitInfo>(indexName)
                              .Where(x => x.Revision > 7 || x.Revision <= 1);
                    //There are 1 CommitInfos which has Revision >7  || <= 1
                    Assert.Equal(1, results.ToArray().Count());

                    results = session.Query <CommitInfo>(indexName)
                              .Where(x => x.Revision >= 7 || x.Revision <= 1);
                    //There are 2 CommitInfos which has Revision >=7  || <= 1
                    Assert.Equal(2, results.ToArray().Count());
                }
            }
        }
Пример #51
0
        public void CanPerformQueryWithDashesInTerm()
        {
            using (var store = NewDocumentStore())
            {
                var indexDefinition = new IndexDefinitionBuilder <Product>()
                {
                    Map = products => from product in products
                          select new
                    {
                        Query = new object[]
                        {
                            product.ItemNumber,
                            product.ItemDescription,
                        },
                        product.ProductId
                    },
                    Indexes =
                    {
                        { x => x.Query, FieldIndexing.Analyzed }
                    },
                    Analyzers =
                    {
                        { x => x.Query, typeof(LowerCaseWhitespaceAnalyzer).AssemblyQualifiedName }
                    }
                }.ToIndexDefinition(store.Conventions);

                store.DatabaseCommands.PutIndex("someIndex", indexDefinition);


                var prodOne = new Product
                {
                    ProductId       = "one",
                    ItemNumber      = "Q9HT180-Z-Q",
                    ItemDescription = "PILLOW PROTECTOR QUEEN"
                };
                var prodTwo = new Product
                {
                    ProductId       = "two",
                    ItemNumber      = "Q9HT180-Z-U",
                    ItemDescription = "PILLOW PROTECTOR STANDARD"
                };
                var prodThree = new Product
                {
                    ProductId       = "three",
                    ItemNumber      = "Q9HT180-Z-K",
                    ItemDescription = "PILLOW PROTECTOR KING"
                };

                using (var session = store.OpenSession())
                {
                    session.Store(prodOne);
                    session.Store(prodTwo);
                    session.Store(prodThree);
                    session.SaveChanges();
                }

                using (var session = store.OpenSession())
                {
                    var prods = session.Advanced.DocumentQuery <Product>("someIndex")
                                .WaitForNonStaleResults()
                                .WhereStartsWith(x => x.Query, "Q9HT180-Z-K")
                                .ToList();

                    Assert.Equal(1, prods.Count);
                }
            }
        }
        public override IndexDefinition CreateIndexDefinition()
        {
            var foo = new IndexDefinitionBuilder<Package, Package>() {
                Map = pkgs => from p in pkgs
                              select new {
                                  Tags = p.Tags
                              },
                Indexes = { { x => x.Tags, FieldIndexing.Analyzed } }
            };

            return foo.ToIndexDefinition(this.Conventions);
        }
Пример #53
0
        public void Convert_map_reduce_query()
        {
            IndexDefinition generated = new IndexDefinitionBuilder<User, LocationCount>
            {
                Map = users => from user in users
                               select new { user.Location, Count = 1 },
                Reduce = counts => from agg in counts
                                   group agg by agg.Location
                                       into g
                                       select new { Location = g.Key, Count = g.Sum(x => x.Count) },
            }.ToIndexDefinition(new DocumentConvention{PrettifyGeneratedLinqExpressions = false});
            var original = new IndexDefinition
            {
                Map = @"docs.Users.Select(user => new {
            Location = user.Location,
            Count = 1
            })",
                Reduce = @"results.GroupBy(agg => agg.Location).Select(g => new {
            Location = g.Key,
            Count = Enumerable.Sum(g, x => ((int) x.Count))
            })"
            };

            Assert.Equal(original.Map, generated.Map);
            Assert.Equal(original.Reduce, generated.Reduce);
        }
		public void CanPerformQueryWithDashesInTerm()
		{
			using (var store = NewDocumentStore())
			{
				var indexDefinition = new IndexDefinitionBuilder<Product>()
				{
					Map = products => from product in products
										select new
										{
											Query = new object[]
											{
												product.ItemNumber,
												product.ItemDescription,

											},
											product.ProductId

										},
					Indexes =
					{
						{x => x.Query, FieldIndexing.Analyzed}
					},
					Analyzers =
					{
						{x => x.Query, typeof (LowerCaseWhitespaceAnalyzer).AssemblyQualifiedName}
					}

				}.ToIndexDefinition(store.Conventions);

				store.DatabaseCommands.PutIndex("someIndex", indexDefinition);


				var prodOne = new Product
				{
					ProductId = "one",
					ItemNumber = "Q9HT180-Z-Q",
					ItemDescription = "PILLOW PROTECTOR QUEEN"
				};
				var prodTwo = new Product
				{
					ProductId = "two",
					ItemNumber = "Q9HT180-Z-U",
					ItemDescription = "PILLOW PROTECTOR STANDARD"
				};
				var prodThree = new Product
				{
					ProductId = "three",
					ItemNumber = "Q9HT180-Z-K",
					ItemDescription = "PILLOW PROTECTOR KING"
				};

				using (var session = store.OpenSession())
				{
					session.Store(prodOne);
					session.Store(prodTwo);
					session.Store(prodThree);
					session.SaveChanges();
				}

				using (var session = store.OpenSession())
				{
					var prods = session.Advanced.LuceneQuery<Product>("someIndex")
						.WaitForNonStaleResults()
						.WhereStartsWith(x => x.Query, "Q9HT180-Z-K")
						.ToList();

					Assert.Equal(1, prods.Count);
				}
			}
		}