当前位置: 首页>>代码示例>>C#>>正文


C# IndexDefinition类代码示例

本文整理汇总了C#中IndexDefinition的典型用法代码示例。如果您正苦于以下问题:C# IndexDefinition类的具体用法?C# IndexDefinition怎么用?C# IndexDefinition使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


IndexDefinition类属于命名空间,在下文中一共展示了IndexDefinition类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Execute

        public void Execute(DocumentDatabase database)
        {
            if (!database.IsBundleActive("IndexedAttachments"))
                return;

            var index = new IndexDefinition
                        {
                            Map = @"from doc in docs
            where doc[""@metadata""][""Raven-Attachment-Key""] != null
            select new
            {
            AttachmentKey = doc[""@metadata""][""Raven-Attachment-Key""],
            Filename = doc[""@metadata""][""Raven-Attachment-Filename""],
            Text = doc.Text
            }",
                            TransformResults = @"from result in results
            select new
            {
            AttachmentKey = result[""@metadata""][""Raven-Attachment-Key""],
            Filename = result[""@metadata""][""Raven-Attachment-Filename""]
            }"
                        };

            // NOTE: The transform above is specifically there to keep the Text property
            //       from being returned.  The results could get very large otherwise.

            index.Indexes.Add("Text", FieldIndexing.Analyzed);
            index.Stores.Add("Text", FieldStorage.Yes);
            index.TermVectors.Add("Text", FieldTermVector.WithPositionsAndOffsets);

            database.PutIndex("Raven/Attachments", index);
        }
开发者ID:tzarger,项目名称:contrib,代码行数:32,代码来源:Startup.cs

示例2: LinqQueryWithIndexIsCaseInsensitive

        public void LinqQueryWithIndexIsCaseInsensitive()
        {
            using (var store = this.NewDocumentStore())
            {
                var definition = new IndexDefinition<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);
                }
            }
        }
开发者ID:philiphoy,项目名称:ravendb,代码行数:35,代码来源:QueryingFromIndex.cs

示例3: AddIndex

 public TableDefinition AddIndex(params string[] columns)
 {
     var def = new IndexDefinition();
     def.AddRange(columns);
     Indexes.Add(def);
     return this;
 }
开发者ID:purplecow,项目名称:media-library,代码行数:7,代码来源:TableDefinition.cs

示例4: LinqQueryWithStaticCallOnEnumerableIsCanBeCompiledAndRun

		public void LinqQueryWithStaticCallOnEnumerableIsCanBeCompiledAndRun()
		{
			var indexDefinition = new IndexDefinition<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, new AbstractDynamicCompilationExtension[] { }).
				GenerateInstance();

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

			var result = mapInstance.MapDefinition(new[] { dynamicObject }).ToList();
			Assert.Equal("{ Id = 0, CoAuthorUserID = 1, __document_id =  }", result[0].ToString());
			Assert.Equal("{ Id = 0, CoAuthorUserID = 2, __document_id =  }", result[1].ToString());
		}
开发者ID:ajaishankar,项目名称:ravendb,代码行数:28,代码来源:JsonSerializationBothWays.cs

示例5: CanUseNullCoalescingOperator

		public void CanUseNullCoalescingOperator()
		{
			using (var store = NewDocumentStore())
			{
				var indexDefinition = new IndexDefinition
				{
					Map = "from e in docs.Events select new { Tag = \"Event\", _ = SpatialGenerate(e.Latitude ?? 38.9103000, e.Longitude ?? -77.3942) }",
					Indexes = {
					{ "Tag", FieldIndexing.NotAnalyzed }
				}
				};

				store.DocumentDatabase.PutIndex("eventsByLatLng", indexDefinition);

				store.DocumentDatabase.Put("Events/1", null,
					RavenJObject.Parse(@"{""Venue"": ""Jimmy's Old Town Tavern"", ""Latitude"": null, ""Longitude"": null }"),
					RavenJObject.Parse("{'Raven-Entity-Name': 'Events'}"), null);

				using (var session = store.OpenSession())
				{
					var objects = session.Query<object>("eventsByLatLng")
						.Customize(x => x.WithinRadiusOf(6, 38.9103000, -77.3942))
						.Customize(x => x.WaitForNonStaleResults())
						.ToArray();

					Assert.Empty(store.DocumentDatabase.Statistics.Errors);

					Assert.Equal(1, objects.Length);
				}
			}

		}
开发者ID:arelee,项目名称:ravendb,代码行数:32,代码来源:BrainV.cs

示例6: CanPerformSpatialSearch

		public void CanPerformSpatialSearch()
		{
			var indexDefinition = new IndexDefinition
			{
				Map = "from e in docs.Events select new { Tag = \"Event\", _ = SpatialGenerate(e.Latitude, e.Longitude) }",
				Indexes = {
					{ "Tag", FieldIndexing.NotAnalyzed }
				}
			};

			db.PutIndex("eventsByLatLng", indexDefinition);

			var events = SpatialIndexTestHelper.GetEvents();

			for (int i = 0; i < events.Length; i++)
			{
				db.Put("Events/" + (i + 1), null,
					RavenJObject.FromObject(events[i]),
					RavenJObject.Parse("{'Raven-Entity-Name': 'Events'}"), null);
			}

			const double lat = 38.96939, lng = -77.386398;
			const double radiusInKm = 6.0*1.609344;
			QueryResult queryResult;
			do
			{
				queryResult = db.Query("eventsByLatLng", new SpatialIndexQuery()
				{
					Query = "Tag:[[Event]]",
					QueryShape = SpatialIndexQuery.GetQueryShapeFromLatLon(lat, lng, radiusInKm),
					SpatialRelation = SpatialRelation.Within,
					SpatialFieldName = Constants.DefaultSpatialFieldName,
					SortedFields = new[] { new SortedField("__distance"), }
				});
				if (queryResult.IsStale)
					Thread.Sleep(100);
			} while (queryResult.IsStale);

			var expected = events.Count(e => Raven.Database.Indexing.SpatialIndex.GetDistance(lat, lng, e.Latitude, e.Longitude) <= radiusInKm);

			Assert.Equal(expected, queryResult.Results.Count);
			Assert.Equal(7, queryResult.Results.Count);

			double previous = 0;
			foreach (var r in queryResult.Results)
			{
				Event e = r.JsonDeserialization<Event>();

				double distance = Raven.Database.Indexing.SpatialIndex.GetDistance(lat, lng, e.Latitude, e.Longitude);
				Console.WriteLine("Venue: " + e.Venue + ", Distance " + distance);

				Assert.True(distance < radiusInKm);
				Assert.True(distance >= previous);
				previous = distance;
			}
		}
开发者ID:Trebornide,项目名称:ravendb,代码行数:56,代码来源:SpatialIndexTest.cs

示例7: IndexHasChanged

        public IndexHasChanged()
		{
			using (var store = new DocumentStore())
			{
                IndexDefinition indexDefinition = new IndexDefinition();
                #region index_has_changed_2
                store.DatabaseCommands.IndexHasChanged("Orders/Totals", indexDefinition);
				#endregion
			}
		}
开发者ID:modulexcite,项目名称:docs-8,代码行数:10,代码来源:IndexHasChanged.cs

示例8: CanSuccessfullyDoSpatialQueryOfNearbyLocations

		//Failing test from http://groups.google.com/group/ravendb/browse_thread/thread/7a93f37036297d48/
		public void CanSuccessfullyDoSpatialQueryOfNearbyLocations()
		{
			// These items is in a radius of 4 miles (approx 6,5 km)
			var areaOneDocOne = new DummyGeoDoc(55.6880508001, 13.5717346673);
			var areaOneDocTwo = new DummyGeoDoc(55.6821978456, 13.6076183965);
			var areaOneDocThree = new DummyGeoDoc(55.673251569, 13.5946697607);

			// This item is 12 miles (approx 19 km) from the closest in areaOne 
			var closeButOutsideAreaOne = new DummyGeoDoc(55.8634157297, 13.5497731987);

			// This item is about 3900 miles from areaOne
			var newYork = new DummyGeoDoc(40.7137578228, -74.0126901936);

			using (var documentStore = new EmbeddableDocumentStore { RunInMemory = true }.Initialize())
			using (var session = documentStore.OpenSession())
			{

				session.Store(areaOneDocOne);
				session.Store(areaOneDocTwo);
				session.Store(areaOneDocThree);
				session.Store(closeButOutsideAreaOne);
				session.Store(newYork);
				session.SaveChanges();

				var indexDefinition = new IndexDefinition
				                      	{
				                      		Map = "from doc in docs select new { _ = SpatialIndex.Generate(doc.Latitude, doc.Longitude) }"
				                      	};

				documentStore.DatabaseCommands.PutIndex("FindByLatLng", indexDefinition);

				// Wait until the index is built
				session.Advanced.LuceneQuery<DummyGeoDoc>("FindByLatLng")
					.WaitForNonStaleResults()
					.ToArray();

				const double lat = 55.6836422426, lng = 13.5871808352; // in the middle of AreaOne
				const double radius = 5.0;

				// Expected is that 5.0 will return 3 results
				var nearbyDocs = session.Advanced.LuceneQuery<DummyGeoDoc>("FindByLatLng")
					.WithinRadiusOf(radius, lat, lng)
					.WaitForNonStaleResults()
					.ToArray();

				Assert.NotEqual(null, nearbyDocs);
				Assert.Equal(3, nearbyDocs.Length);

				//TODO
				//var dist = DistanceUtils.GetInstance();
				//Assert.Equal(true, nearbyDocs.All(x => dist.GetDistanceMi(x.Latitude, x.Longitude, lat, lng) < radius));

				session.Dispose();
			}
		}
开发者ID:neiz,项目名称:ravendb,代码行数:56,代码来源:SpatialQueries.cs

示例9: CanDefineHierarchicalIndexOnTheClient_WithLinq

        public void CanDefineHierarchicalIndexOnTheClient_WithLinq()
        {
            var indexDefinition = new IndexDefinition<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);
        }
开发者ID:jaircazarin,项目名称:ravendb,代码行数:11,代码来源:HierarchyFromClient.cs

示例10: DynamicViewCompiler

		public DynamicViewCompiler(string name, IndexDefinition indexDefinition, OrderedPartCollection<AbstractDynamicCompilationExtension> extensions, string basePath, InMemoryRavenConfiguration configuration)
		{
			this.indexDefinition = indexDefinition;
			this.extensions = extensions;
			if (configuration.RunInMemory == false)
			{
				this.basePath = Path.Combine(basePath, "TemporaryIndexDefinitionsAsSource");
				if (Directory.Exists(this.basePath) == false)
					Directory.CreateDirectory(this.basePath);
			}
			this.name = MonoHttpUtility.UrlEncode(name);
		    RequiresSelectNewAnonymousType = true;
		}
开发者ID:neiz,项目名称:ravendb,代码行数:13,代码来源:DynamicViewCompiler.cs

示例11: CreateDeleteCreateIndex

		public void CreateDeleteCreateIndex()
		{
			using (var store = NewDocumentStore(requestedStorage:"esent"))
			{
				var indexDefinition = new IndexDefinition
				{
					Map = "from d in docs select new {}"
				};
				store.DatabaseCommands.PutIndex("test", indexDefinition);
				store.DatabaseCommands.DeleteIndex("test");
				store.DatabaseCommands.PutIndex("test", indexDefinition);
			}
		}
开发者ID:remcoros,项目名称:ravendb,代码行数:13,代码来源:RavenDb505.cs

示例12: CreateIndexDefinition

        public override IndexDefinition CreateIndexDefinition()
        {
            var index = new IndexDefinition();
            index.Name = this.IndexName;
            index.Map = @"from doc in docs
            let DocumentType = ((dynamic)doc)[""@metadata""][""Raven-Entity-Name""]
            let Id = doc[""@metadata""][""Id""]
            let LastModified = doc[""@metadata""][""Last-Modified""]
            select new {DocumentType = ((dynamic)doc)[""@metadata""][""Raven-Entity-Name""], Id, LastModified}";

            index.TransformResults = @"from result in results
            select new {Id = result.Id, DocumentType = result.DocumentType, LastModified = result.LastModified}";

            return index;
        }
开发者ID:dhrobbins,项目名称:RavenMaintenance,代码行数:15,代码来源:AllDocsByTypeIndex.cs

示例13: Index_replication_with_side_by_side_indexes_should_not_propagate_replaced_index_tombstones

        public async Task Index_replication_with_side_by_side_indexes_should_not_propagate_replaced_index_tombstones()
        {
            using (var source = CreateStore())
            using (var destination = CreateStore())
            {
                var oldIndexDef = new IndexDefinition
                {
                    Map = "from person in docs.People\nselect new {\n\tFirstName = person.FirstName\n}"
                };
                var testIndex = new RavenDB_3232.TestIndex();

                var sourceDatabase = await servers[0].Server.GetDatabaseInternal(source.DefaultDatabase);
                sourceDatabase.StopBackgroundWorkers();

                source.DatabaseCommands.PutIndex(testIndex.IndexName, oldIndexDef);

                using (var session = source.OpenSession())
                {
                    session.Store(new RavenDB_3232.Person { FirstName = "John", LastName = "Doe" });
                    session.SaveChanges();
                }
                var sourceReplicationTask = sourceDatabase.StartupTasks.OfType<ReplicationTask>().First();
                sourceReplicationTask.IndexReplication.TimeToWaitBeforeSendingDeletesOfIndexesToSiblings = TimeSpan.FromSeconds(0);

                sourceReplicationTask.Pause(); //pause replciation task _before_ setting up replication

                SetupReplication(source.DatabaseCommands, destination);

                var mre = new ManualResetEventSlim();

                sourceDatabase.Notifications.OnIndexChange += (database, notification) =>
                {
                    if (notification.Type == IndexChangeTypes.SideBySideReplace)
                        mre.Set();
                };

                shouldRecordRequests = true;
                testIndex.SideBySideExecute(source);

                sourceDatabase.SpinBackgroundWorkers();
                WaitForIndexing(source); //now old index should be a tombstone and side-by-side replaced it.
                mre.Wait();
                sourceReplicationTask.IndexReplication.Execute();

                Assert.Equal(0, requestLog.Count(x => x.Method.Method == "DELETE"));
            }
        }
开发者ID:IdanHaim,项目名称:ravendb,代码行数:47,代码来源:RavenDB_3574.cs

示例14: TransformGeoIndexes

        private static string TransformGeoIndexes(string value, IndexDefinition definition, DocumentConvention conventions)
        {
            if (value == null)
                return null;

            return Regex.Replace(value, @"GeoIndex\((?<pre>[^.]+)[.](?<prop>[^),]+)(?<remainder>[^)]*)[)]", match =>
            {
                var fieldPrefix = match.Groups["prop"].Value.Replace(".", "_");
                return string.Format("SpatialGenerate(\"{0}_{1}\", {2}.{3}.{1}{4})",
                        match.Groups["prop"].Value.Replace(".", "_"),
                        SpatialField.Name,
                        match.Groups["pre"].Value,
                        match.Groups["prop"].Value,
                        match.Groups["remainder"].Value
                    );
            });
        }
开发者ID:spadger,项目名称:Geo,代码行数:17,代码来源:GeoIndexTranformer.cs

示例15: CanRunSpatialQueriesInMemory

 public void CanRunSpatialQueriesInMemory()
 {
     var documentStore = new EmbeddableDocumentStore { RunInMemory = true };
     documentStore.Initialize();
     var def = new IndexDefinition<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);
 }
开发者ID:jaircazarin,项目名称:ravendb,代码行数:17,代码来源:SpatialQueries.cs


注:本文中的IndexDefinition类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。