public IResponse Execute()
        {
            // create client connection
            var node = new Uri(ServerUrl);
            var conn = new ConnectionSettings(node, this.IndexName);
            var client = new ElasticClient(conn);

            // check index name existance
            var existenceResult = client.GetIndex(i => i.Index(IndexName));
            if (existenceResult.ConnectionStatus.Success)
            {
                // delete exist index
                var deleteResult = client.DeleteIndex(i => i.Index(IndexName));
                if (!deleteResult.Acknowledged)
                    return deleteResult;
            }

            // create index
            var createResult = client.CreateIndex(i => i.Index(IndexName));
            if (!createResult.Acknowledged)
                return createResult;

            // set analyzer
            SetAnalyzers(client);

            // put mapping
            var putResult = client.Map<TranslationMemory>(m => m.Index(this.IndexName).MapFromAttributes());
            //var putResult = client.Map<ElasticSearchProject>(m => m.Index(this.IndexName));
            return putResult;
        }
        static void Main(string[] args)
        {
            var context = new ElasticDBEntities();

            var artists = context.Artists.ToList();

            var node = "http://localhost:9200";

            var searchBoxUri = new Uri(node);
            var settings = new ConnectionSettings(searchBoxUri);
            //settings.SetDefaultIndex("sample");

            var client = new ElasticClient(settings);
            
            if (client.IndexExists("store").Exists)
            {
                client.DeleteIndex("store");
            }

            //client.CreateIndex("sample");

            foreach (var artist in artists)
            {
                //var index = client.Index(artist);
                var index = client.Index(artist, i => i.Index("store").Refresh());
            }

            // Index all documents
            //client.IndexMany<Artist>(artists);

        }
예제 #3
0
파일: Program.cs 프로젝트: jptoto/esdotnet
        static void Main(string[] args)
        {
            elasticSettings = new ConnectionSettings(new Uri("http://127.0.0.1:9200"))
            .SetDefaultIndex("people");

            client = new ElasticClient(elasticSettings);

            client.DeleteIndex("people");

            // Create an index
            client.CreateIndex("people", c => c
                                                  .NumberOfReplicas(0)
                                                  .NumberOfShards(1));

            client.MapFluent<Person>(m => m.IndexAnalyzer("standard")
                                                        .Properties(props => props
                                                            .String(s => s
                                                                .Name(p => p.Message)
                                                                .Index(FieldIndexOption.analyzed))
                                                            .Number(n => n
                                                                .Name(p => p.Age))
                                                            .String(s => s
                                                                .Name(p => p.FirstName))
                                                            .String(s => s
                                                                .Name(p => p.Sex))
                                                            .String(s => s
                                                                .Name(p => p.LastName))));

            //Add some people
            var jp = new Person { FirstName = "JP", LastName = "Smith", Age = 37, Message = "OMG yay ES!", Sex = "Male" };
            var matt = new Person { FirstName = "Matt", LastName = "Toto", Age = 32, Message = "I'm JPs brother", Sex = "Male" };
            var christine = new Person { FirstName = "Christine", LastName = "Toto", Age = 0, Message = "I'm JPs wife", Sex = "Female" };
            var kevin = new Person { FirstName = "Kevin", LastName = "Toto", Age = 26, Message = "I'm JPs other brother", Sex = "Male" };

            client.Index(jp);
            client.Index(matt);
            client.Index(christine);
            client.Index(kevin);

            client.Refresh();

            ///// ** Wildcard search
            var searchResults = client.Search<Person>(s => s
                .From(0)
                .Size(10)
                .Query(q => q
                    .Wildcard(f => f.LastName, "to*", Boost: 1.0)
                )
            );

            foreach (var result in searchResults.Documents)
            {
                Console.WriteLine("Found: {0}", result.FirstName + " " + result.LastName);
            }

            Console.ReadKey();
        }
예제 #4
0
 /// <summary>
 /// 删除索引
 /// </summary>
 public void DeleteIndex()
 {
     string espath = ConfigurationManager.AppSettings["ESPath"].ToString();
     string indexname = ConfigurationManager.AppSettings["IndexName"].ToString();
     string typename = ConfigurationManager.AppSettings["TypeName"].ToString();
     var node = new Uri(espath);
     var settings = new ConnectionSettings(node);
     var client = new ElasticClient(settings);
     client.DeleteIndex(new DeleteIndexRequest(new IndexNameMarker() { Name = indexname }));
 }
        public ElasticSearchTestSetup()
        {
            testIndex = string.Format("{0}-{1}", "log_test", DateTime.Now.ToString("yyyy-MM-dd"));

            elasticSettings = new ConnectionSettings(new Uri("http://127.0.0.1:9200"))
                .SetDefaultIndex(testIndex);
            
            client = new ElasticClient(elasticSettings);

            client.DeleteIndex(testIndex);
        }
        private static void deleteTestIndices()
        {
            var elastic = new ElasticClient(new ConnectionSettings(new UriBuilder("http", "localhost", 9200, "", "").Uri, remindersIndex));

            var indexExists = elastic.IndexExists(remindersIndex);
            if (indexExists.Exists)
            {
                var deleteResponse = elastic.DeleteIndex(remindersIndex, d => d.Index(remindersIndex));
                if (!deleteResponse.IsValid)
                    throw new Exception("Initialization failed");
            }
        }
        private  void deleteTestIndices()
        {
            var ci = ElasticStorageProvider.FromConnectionString<ConnectionInfo>(TEST_CONNECTION_STRING);
            var cs = new ConnectionSettings(new UriBuilder("http", ci.Host, ci.Port, "", "").Uri, ci.Index);
            var elastic = new ElasticClient(cs);

            var indexExists = elastic.IndexExists(ci.Index);
            if (indexExists.Exists)
            {
                var deleteResponse = elastic.DeleteIndex(ci.Index, d => d.Index(ci.Index));
                if (!deleteResponse.IsValid)
                    throw new Exception("Initialization failed");
            }
        }
예제 #8
0
        static void Main(string[] args)
        {
            var indexName = _IndexName;
              int numOfCountries = 1;
              //if (args.Length > 0 && args[0] == "full")
              {
            numOfCountries = 42;
            indexName += "-full";
              }

              settings = new ConnectionSettings(new Uri(esconnection))
            .SetDefaultIndex(indexName);
              client = new ElasticClient(settings);

              using (new Timed("CreateIndex"))
              {
            if (client.IndexExists(indexName).Exists)
            {
              client.DeleteIndex(indexName);
            }
            PricesInstaller.CreateIndex(client, indexName).AssertValid();
              }
              var accos = Timed.Do("Generating Accos", () => Generator.GenerateAccos(numOfCountries).ToList());

              using (new Timed(string.Format("Indexing {0} Accos", accos.Count)))
              {
            var sets = accos.InSetsOf(100);

            foreach (var accoSet in sets)
            {
              using (new Timed(string.Format("Indexing Acco {0}-{1}/{2}", accoSet.First().Id, accoSet.First().Id + 99, accos.Count)))
              {
            int pricesCount = 0;
            foreach (var acco in accoSet)
            {
              IndexAcco(acco);
              var accoAvailabilities = Generator.GenerateAccoAvailabilities(acco.HighSeasons);

              var prices = Generator.GeneratePrices(acco, accoAvailabilities);
              pricesCount += prices.Count;
              IndexPrices(acco, prices);
            }
            Console.WriteLine("Generated {0} prices for {1} accos", pricesCount, accoSet.Count);
              }
            }
              }
        }
예제 #9
0
		static void Main(string[] args)
		{
			var arguments = new Arguments();

			if (!arguments.Parse(args))
				return;

			TestClient.Configuration = new BenchmarkingTestConfiguration();

			using (var cluster = new BenchmarkingCluster())
			{
				var warmup = new HttpTester(cluster.Node.Port).RunTests(10);
				var times = arguments.Times;

				if (arguments.Interactive)
				{
					Console.WriteLine("Warmed up caches to start testing, press any key to start tests");
					Console.ReadKey();
				}
				else
				{
					Console.WriteLine("Warmed up caches to start testing");
				}

				var key = default(ConsoleKeyInfo);
				do
				{
					var results = Testers(cluster.Node.Port).Select(t => t.RunTests()).ToList();
					Console.WriteLine();
					foreach (var result in results)
						result.Write(Console.Out);

					--times;

					if (arguments.Interactive)
					{
						Console.WriteLine("\nPress r to index again or any other key to delete indices created by this tool.\n");
						key = Console.ReadKey();
					}

				} while ((arguments.Interactive && key.KeyChar == 'r') || (!arguments.Interactive && times > 0));

				var client = new ElasticClient();
				client.DeleteIndex(Tester.IndexPrefix + "*");
			}
		}
예제 #10
0
파일: Program.cs 프로젝트: jptoto/esdotnet
        static void Main(string[] args)
        {
            elasticSettings = new ConnectionSettings(new Uri("http://127.0.0.1:9200"))
                .SetDefaultIndex("people");

            client = new ElasticClient(elasticSettings);

            client.DeleteIndex("people");

            // Create an index
            client.CreateIndex("people", c => c
                                    .NumberOfReplicas(0)
                                    .NumberOfShards(1)
                                    .AddMapping<Person>(m => m.MapFromAttributes()));

            // Add some people
            var jp = new Person { FirstName = "JP", LastName = "Toto", Age = 37, Message = "OMG yay ES!", Sex = "Male" };
            var matt = new Person { FirstName = "Matt", LastName = "Toto", Age = 32, Message = "I'm JPs brother", Sex = "Male" };
            var christine = new Person { FirstName = "Christine", LastName = "Toto", Age = 0, Message = "I'm JPs wife", Sex = "Female" };
            var kevin = new Person { FirstName = "Kevin", LastName = "Toto", Age = 26, Message = "I'm JPs other brother", Sex = "Male" };

            client.Index(jp);
            client.Index(matt);
            client.Index(christine);
            client.Index(kevin);

            client.Refresh();

            var searchResults = client.Search<Person>(s => s
                .From(0)
                .Size(10)
                .Fields(f => f.FirstName, f => f.LastName)
                .Query(q => q
                    .MatchPhrase(j => j.OnField("Message").QueryString("i'm jps brother"))
                )
            );

            foreach (var result in searchResults.Documents)
            {
                Console.WriteLine("Found: {0}", result.FirstName + " " + result.LastName);
            }

            Console.ReadKey();
        }
예제 #11
0
 public void Execute(IJobExecutionContext context)
 {
     ILog log = LogManager.GetLogger(this.GetType());
     JobDataMap data = context.JobDetail.JobDataMap;
     var esUrl = data.GetString("eshost");
     var esIndex = data.GetString("defaultindex");
     var needRebuild = data.ContainsKey("needrebuild") ? data.GetBooleanValue("needrebuild") : false;
     var benchDate = BenchDate(context) ;
     
     var client = new ElasticClient(new ConnectionSettings(new Uri(esUrl))
                             .SetDefaultIndex(esIndex)
                             .SetMaximumAsyncConnections(10));
     ConnectionStatus connectionStatus;
     if (!client.TryConnect(out connectionStatus))
     {
         log.Fatal(string.Format("Could not connect to {0}:\r\n{1}",
             esUrl, connectionStatus.Error.OriginalException.Message));
         return;
     }
     if (needRebuild)
     {
         var response = client.DeleteIndex(esIndex);
         if (response.OK)
         {
             log.Info(string.Format("index:{0} is deleted!", esIndex));
             _isActiveOnly = true;
         }
         else
         {
             log.Info("remove index failed");
         }
     }
     IndexBrand(client, benchDate);
     IndexHotwork(client, benchDate);
     IndexStore(client, benchDate);
     IndexTag(client, benchDate);
     IndexUser(client, benchDate);
     IndexResource(client, benchDate);
     IndexProds(client, benchDate,null);
     IndexPros(client,benchDate,null);
     IndexBanner(client, benchDate);
     IndexSpecialTopic(client, benchDate,null);
     IndexStorePromotion(client, benchDate);
 }
예제 #12
0
        private static void CreateIndex(string name, ElasticClient client)
        {
            if (client.IndexExists(x => x.Index(name)).Exists)
            {
                Log.Logger.Information("Delete index {indexName}", name);

                client.DeleteIndex(x => x.Index(name));
            }

            Log.Logger.Information("Create index {indexName}", name);
            client.CreateIndex(name, c => c
                .NumberOfReplicas(0)
                .NumberOfShards(1)
                .AddMapping<Book>(m => m.MapFromAttributes())
                .AddMapping<CD>(m => m.MapFromAttributes()));
            Log.Logger.Information("Index {indexName} created", name);

            Log.Logger.Information("Closing index {indexName}", name);

            Thread.Sleep(30000);
            var closeRes = client.CloseIndex(x => x.Index(name));

            
            if (!closeRes.Acknowledged)
                Log.Logger.Error("Could not close index: {message}",closeRes.ServerError.Error);

            Log.Logger.Information("Add analyzer to index {indexName}", name);
            var res = client.Raw.IndicesPutSettings(name, File.ReadAllText("Analyzer.json"));

            if (!res.Success)
                Log.Logger.Error("Could not create analyzer: {error}", res.OriginalException.ToString());


            Log.Logger.Information("Open index {indexName}", name);
            client.OpenIndex(x => x.Index(name));

            RandomBooks(1000, name, client);
            RandomCDs(1000, name, client);
        }
예제 #13
0
        static void Main(string[] args)
        {
            var warmup = new HttpTester().RunTests(10);

            Console.WriteLine("Warmed up caches to start testing, press any key to start tests");
            Console.ReadLine();

            ConsoleKeyInfo key;
            do
            {
                var results = Testers().Select(t => t.RunTests()).ToList();
                Console.WriteLine();
                foreach(var r in results)
                    PrintRunResults(r);

                Console.WriteLine("\nPress r to index again or any other key to delete indices created by this tool.\n");
                key = Console.ReadKey();
            } while (key.KeyChar == 'r');

            var client = new ElasticClient();
            client.DeleteIndex(d => d.Index(Tester.INDEX_PREFIX + "*"));
        }
예제 #14
0
        static void Main(string[] args)
        {
            var reader = new StreamReader("C:/data/logs/FritzLog.csv");
            var csv = new CsvReader(reader);
            csv.Parser.Configuration.Delimiter = ";";
            csv.Configuration.HasHeaderRecord = true;
            csv.Configuration.IgnoreHeaderWhiteSpace = true;

            var records = csv.GetRecords<LogEntry>();

            var node = new Uri("http://localhost:9200");
            var settings = new ConnectionSettings(node);
            settings.SetDefaultIndex("phonelog");
          
            var client = new ElasticClient(settings);
            client.DeleteIndex("phonelog");
            client.CreateIndex(ci => ci.Index("phonelog").AddMapping<LogEntry>(m => m.MapFromAttributes()));
            foreach (var record in records)
            {
                var result = client.Index(record);
                Console.WriteLine(record + ", Result: " + result);
            }

        }
        private void WipeIndex(ElasticClient esClient, string indexName)
        {
            var indexExistsRequest = new IndexExistsRequest(indexName);
            var indexExistsResult = esClient.IndexExists(indexExistsRequest);

            if (indexExistsResult.Exists == true)
            {
                esClient.DeleteIndex(new DeleteIndexRequest(indexName));
            }

            EnsureIndexExists(esClient, indexName);
        }
예제 #16
0
        public bool DeleteAll()
        {
            var connectionSettings = new ConnectionSettings(MainVariables.conElasticSearch);
            connectionSettings.SetDefaultIndex("advertisement");
            var elasticClient = new ElasticClient(connectionSettings);

            var index = elasticClient.DeleteIndex("advertisement");
            if (index.ServerError == null) return true;
            else return false;
        }
        public ActionResult ReIndexAll()
        {
            var documents = db.DocumentModels.ToList();

            var uriString = ConfigurationManager.AppSettings["SEARCHBOX_URL"];
            var searchBoxUri = new Uri(uriString);

            var settings = new ConnectionSettings(searchBoxUri);
            settings.SetDefaultIndex(indexName);

            var client = new ElasticClient(settings);

            // delete index if exists at startup
            if (client.IndexExists(indexName).Exists)
            {
                client.DeleteIndex(indexName);
            }

            // Create a new "sample" index with default settings
            //client.CreateIndex("sample", new IndexSettings());
            ICreateIndexRequest iCreateIndexReq = new CreateIndexRequest(indexName);
            iCreateIndexReq.IndexSettings = new IndexSettings();
            iCreateIndexReq.IndexSettings.NumberOfReplicas = 10;

            //client.CreateIndex(iCreateIndexReq);

            var resCreate = client.CreateIndex(indexName, s => s.AddMapping<DocumentModel>(f => f.MapFromAttributes()).NumberOfReplicas(1).NumberOfShards(10));

            //client.CreateIndex()
            // Index all documents
            client.IndexMany<DocumentModel>(documents);
            //client.Index()

            ViewBag.Message = "Reindexing all database is complete!";

            return RedirectToAction("Index");
        }
예제 #18
0
파일: Index.cs 프로젝트: alecrt/FormEditor
 public void Delete()
 {
     // create a client for the base index uri and delete the entire index by name.
     var uri = GetConnectionUri();
     var client = new ElasticClient(new ConnectionSettings(uri));
     client.DeleteIndex(IndexName());
 }
예제 #19
0
파일: Program.cs 프로젝트: jptoto/esdotnet
        static void Main(string[] args)
        {
            elasticSettings = new ConnectionSettings(new Uri("http://127.0.0.1:9200"))
                .SetDefaultIndex("people");

            client = new ElasticClient(elasticSettings);

            client.DeleteIndex("people");

            // Create an index

            client.MapFluent<Person>(m => m.IndexAnalyzer("standard")
                                                        .Properties(props => props
                                                            .String(s => s
                                                                .Name(p => p.Message)
                                                                .Index(FieldIndexOption.analyzed))
                                                            .Number(n => n
                                                                .Name(p => p.Age))
                                                            .String(s => s
                                                                .Name(p => p.FirstName))
                                                            .String(s => s
                                                                .Name(p => p.Sex))
                                                            .String(s => s
                                                                .Name(p => p.LastName))));

            // Add some people
            var jp = new Person { FirstName = "JP", LastName = "Smith", Age = 37, Message = "OMG yay ES!", Sex = "Male" };
            var matt = new Person { FirstName = "Matt", LastName = "boosting", Age = 32, Message = "test", Sex = "Male" };
            var christine = new Person { FirstName = "Christine", LastName = "Toto", Age = 0, Message = "I'm JPs wife", Sex = "Female" };
            var kevin = new Person { FirstName = "Kevin", LastName = "boosting", Age = 26, Message = "I'm JPs other boosting", Sex = "Male" };

            client.Index(jp);
            client.Index(matt);
            client.Index(christine);
            client.Index(kevin);

            client.Refresh();

            ///// ** Basic search with QueryString
            var searchResults = client.Search<Person>(s => s.Query(q => q.
                            QueryString(x => x.Query("boosting"))));

            foreach (var result in searchResults.Documents)
            {
                Console.WriteLine("Found: {0}", result.FirstName + " " + result.LastName);
            }

            Console.ReadKey();

            // Boosting

            client.DeleteIndex("people");

            // Create an index

            client.MapFluent<Person>(m => m.IndexAnalyzer("standard")
                                                        .Properties(props => props
                                                            .String(s => s
                                                                .Name(p => p.Message)
                                                                .Index(FieldIndexOption.analyzed).Boost(2.0))
                                                            .Number(n => n
                                                                .Name(p => p.Age))
                                                            .String(s => s
                                                                .Name(p => p.FirstName))
                                                            .String(s => s
                                                                .Name(p => p.Sex))
                                                            .String(s => s
                                                                .Name(p => p.LastName))));

            // Add some people
            var jp1 = new Person { FirstName = "JP", LastName = "Smith", Age = 37, Message = "OMG yay ES!", Sex = "Male" };
            var matt1 = new Person { FirstName = "Matt", LastName = "boosting", Age = 32, Message = "boosting", Sex = "Male" };
            var christine1 = new Person { FirstName = "Christine", LastName = "Toto", Age = 0, Message = "I'm JPs wife", Sex = "Female" };
            var kevin1 = new Person { FirstName = "Kevin", LastName = "boosting", Age = 26, Message = "I'm JPs other test", Sex = "Male" };

            client.Index(jp1);
            client.Index(matt1);
            client.Index(christine1);
            client.Index(kevin1);

            client.Refresh();

            ///// ** Basic search with QueryString
            var searchResults2 = client.Search<Person>(s => s.Query(q => q.
                            QueryString(x => x.Query("boosting"))));

            foreach (var result in searchResults2.Documents)
            {
                Console.WriteLine("Found: {0}", result.FirstName + " " + result.LastName);
            }

            Console.ReadKey();
        }
예제 #20
0
        public void Setup()
        {
            settings = new ConnectionSettings(new Uri(esconnection))
            .SetDefaultIndex(indexName)
            .UsePrettyResponses();
              client = new ElasticClient(settings);

              if (client.IndexExists(indexName).Exists)
            client.DeleteIndex(indexName);

              PricesInstaller.CreateIndex(client, indexName).AssertValid();

              client.Index(new Acco { Id = 1, LocationCode = "AA" }).AssertValid();
              client.Index(new Acco { Id = 2, LocationCode = "BB" }).AssertValid();
              client.Index(new Acco { Id = 3, LocationCode = "CC" }).AssertValid();

              client.Index(new Price { Id = 1, CareType = "AI", DepartureDate = DateTime.Today, DurationDays = 10, PricePerPerson = 100, TransportFrom = "AMS", TransportType = "EV" }, new IndexParameters { Parent = 1.ToString(CultureInfo.InvariantCulture) }).AssertValid();
              client.Index(new Price { Id = 2, CareType = "HP", DepartureDate = DateTime.Today, DurationDays = 11, PricePerPerson = 100, TransportFrom = "AMS", TransportType = "EV" }, new IndexParameters { Parent = 1.ToString(CultureInfo.InvariantCulture) }).AssertValid();
              client.Index(new Price { Id = 3, CareType = "AI", DepartureDate = DateTime.Today, DurationDays = 12, PricePerPerson = 100, TransportFrom = "AMS", TransportType = "EV" }, new IndexParameters { Parent = 2.ToString(CultureInfo.InvariantCulture) }).AssertValid();
              client.Refresh().AssertValid();
        }
예제 #21
0
파일: Program.cs 프로젝트: jptoto/esdotnet
        static void Main(string[] args)
        {
            elasticSettings = new ConnectionSettings(new Uri("http://127.0.0.1:9200"))
            .SetDefaultIndex("people");

            client = new ElasticClient(elasticSettings);

            client.DeleteIndex("people");

            // Create an index
            client.CreateIndex("people", c => c
                                                  .NumberOfReplicas(0)
                                                  .AddMapping<Person>(m => m.MapFromAttributes())
                                                  .NumberOfShards(1));

            //client.MapFluent<Person>(m => m.IndexAnalyzer("standard")
            //                                            .Properties(props => props
            //                                                .String(s => s
            //                                                    .Name(p => p.Message)
            //                                                    .Index(FieldIndexOption.analyzed))
            //                                                .Number(n => n
            //                                                    .Name(p => p.Age))
            //                                                .String(s => s
            //                                                    .Name(p => p.FirstName))
            //                                                .String(s => s
            //                                                    .Name(p => p.Sex))
            //                                                .String(s => s
            //                                                    .Name(p => p.LastName))));

            // Add some people
            var jp = new Person { FirstName = "JP", LastName = "Toto", Age = 37, Message = "OMG yay ES!", Sex = "Male" };
            var matt = new Person { FirstName = "Matt", LastName = "Toto", Age = 37, Message = "I'm JPs brother", Sex = "Male" };
            var christine = new Person { FirstName = "Christine", LastName = "Toto", Age = 0, Message = "I'm JPs wife", Sex = "Female" };
            var kevin = new Person { FirstName = "Kevin", LastName = "Smith", Age = 26, Message = "I'm JPs other brother", Sex = "Male" };

            client.Index(jp);
            client.Index(matt);
            client.Index(christine);
            client.Index(kevin);

            client.Flush(true);

            var results = client.Search<Person>(s => s
                            .MatchAll()
                            .FacetStatistical(fs => fs
                                .OnField(f => f.Age)
                            ));

            var facet = results.Facet<StatisticalFacet>(f => f.Age);

            Console.WriteLine("Statistical Facets");
            Console.WriteLine("");
            Console.WriteLine("Max: {0}", facet.Max);
            Console.WriteLine("Min: {0}", facet.Min);
            Console.WriteLine("Std Dev: {0}", facet.StandardDeviation);
            Console.WriteLine("Total: {0}", facet.Total);

            Console.ReadKey();

            Console.Clear();

            Console.WriteLine("Histogram Facets");
            Console.WriteLine("");
            var facetResults = client.Search<Person>(s => s
                            .MatchAll()
                            .FacetHistogram(fs => fs
                                .OnField(f => f.Age)
                                .Interval(1)
                            ));

            var facet2 = facetResults.Facet<HistogramFacet>(f => f.Age);

            foreach (var item in facet2.Items)
            {
                Console.WriteLine("Key: {0}  Count: {1}", item.Key, item.Count);
            }

            Console.ReadKey();

            Console.Clear();

            Console.WriteLine("Term Facets");
            Console.WriteLine("");
            var facetResults2 = client.Search<Person>(s => s
                .From(0)
                .Size(10)
                .MatchAll()
                .FacetTerm(t => t.OnField(f => f.LastName).Size(20))
            );

            var facet3 = facetResults2.Facet<TermFacet>(f => f.LastName);
            foreach (var item in facet3.Items)
            {
                Console.WriteLine("Key: {0}  Count: {1}", item.Term, item.Count);
            }

            Console.ReadKey();
        }
예제 #22
0
        private static async Task<Boolean> ReseedDB()
        {
            _logger.Info("Purging all MSMQ queues...");
            var msmques = MessageQueue.GetPrivateQueuesByMachine(".");
            foreach (var queue in msmques)
                queue.Purge();
            _logger.Info("Done");

            _logger.Info("Deleting all Databases...");
            {
                _logger.Info("Deleting all documents in RavenDB...");

                var connectionString = ConfigurationManager.ConnectionStrings["Raven"];
                if (connectionString == null)
                    throw new ArgumentException("No Raven connection string found");

                var data = connectionString.ConnectionString.Split(';');

                var url = data.FirstOrDefault(x => x.StartsWith("Url", StringComparison.CurrentCultureIgnoreCase));
                if (url == null)
                    throw new ArgumentException("No URL parameter in elastic connection string");
                var db = data.FirstOrDefault(x => x.StartsWith("Database", StringComparison.CurrentCultureIgnoreCase));
                if (db.IsNullOrEmpty())
                    throw new ArgumentException("No Database parameter in elastic connection string");

                db = db.Substring(9);



                using (var store = new DocumentStore { ConnectionStringName = "Raven" }.Initialize())
                {
                    store.DatabaseCommands.GlobalAdmin.EnsureDatabaseExists(db);

                    using (var session = store.OpenSession())
                    {
                        session.Advanced.DocumentStore.DatabaseCommands.DeleteByIndex("Raven/DocumentsByEntityName",
                            new IndexQuery { Query = "Tag:*" }
                        );
                    }
                }
                _logger.Info("Done");
            }
            {
                _logger.Info("Deleting ElasticSearch index...");

                var connectionString = ConfigurationManager.ConnectionStrings["Elastic"];
                if (connectionString == null)
                    throw new ArgumentException("No elastic connection string found");

                var data = connectionString.ConnectionString.Split(';');

                var url = data.FirstOrDefault(x => x.StartsWith("Url", StringComparison.CurrentCultureIgnoreCase));
                if (url == null)
                    throw new ArgumentException("No URL parameter in elastic connection string");
                var index = data.FirstOrDefault(x => x.StartsWith("DefaultIndex", StringComparison.CurrentCultureIgnoreCase));
                if (index.IsNullOrEmpty())
                    throw new ArgumentException("No DefaultIndex parameter in elastic connection string");

                index = index.Substring(13);

                var node = new Uri(url.Substring(4));

                var settings = new ConnectionSettings(node);
                var client = new ElasticClient(settings);

                client.DeleteIndex(index);

                client.CreateIndex(index, i => i
                        .Analysis(analysis => analysis
                            .TokenFilters(f => f
                                .Add("ngram", new Nest.NgramTokenFilter { MinGram = 2, MaxGram = 15 })
                                )
                            .Analyzers(a => a
                                .Add(
                                    "default",
                                    new Nest.CustomAnalyzer
                                    {
                                        Tokenizer = "standard",
                                        Filter = new[] { "standard", "lowercase", "asciifolding", "kstem", "ngram" }
                                    }
                                )
                                .Add(
                                    "suffix",
                                    new Nest.CustomAnalyzer
                                    {
                                        Tokenizer = "keyword",
                                        Filter = new[] { "standard", "lowercase", "asciifolding", "reverse" }
                                    }
                                )
                            )
                        ));

                _logger.Info("Done");
            }

            await ImportCategory("configuration");

            return true;
        }
        public ActionResult ReIndexAll()
        {
            var documents = db.Documents.ToList();

            var uriString = ConfigurationManager.AppSettings["SEARCHBOX_URL"];
            var searchBoxUri = new Uri(uriString);

            var settings = new ConnectionSettings(searchBoxUri);
            settings.SetDefaultIndex("sample");

            var client = new ElasticClient(settings);

            // delete index if exists at startup
            if (client.IndexExists("sample").Exists)
            {
                client.DeleteIndex("sample");
            }

            // Create a new "sample" index with default settings
            client.CreateIndex("sample", new IndexSettings());

            // Index all documents
            client.IndexMany<Document>(documents);

            ViewBag.Message = "Reindexing all database is complete!";

            return RedirectToAction("Index");
        }