public static void GenerateLookupDocumentLists(ElasticClient client)
 {
     foreach (var skill in SampleDatasets.SkillsCollection)
         client.Index(skill);
     
     foreach (var cert in SampleDatasets.CertificationCollection)
         client.Index(cert);   
 }
예제 #2
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();
        }
예제 #3
0
        public void RebuildIndex(string userId, int? noteId)
        {
            if (!string.IsNullOrWhiteSpace(userId))
            {
                var notes = new List<NoteModel>();

                if (noteId.HasValue)
                    notes.Add(Repository.GetById(noteId.Value));
                else
                    notes = Repository.GetByUserId(userId).ToList();
                

                var settings = new ConnectionSettings(new Uri("http://localhost:9200"), "mapnotes");
                var client = new ElasticClient(settings);


                var indexExists = client.IndexExists("mapnotes");
                if (!indexExists.Exists)
                {
                    client.CreateIndex(descriptor => descriptor.Index("mapnotes")
                            .AddMapping<NoteIndex>(m => m.Properties(p => p.GeoPoint(d => d.Name(f => f.Location).IndexLatLon()))));
                }

                foreach (var note in notes)
                {
                    client.Index(new NoteIndex
                    {
                        Id = note.Id,
                        UserId = note.UserId,
                        Title = note.Title,
                        Location = new Location(note.Latitude, note.Longitude)
                    });
                }
            }
        }
        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);

        }
        /// <summary>
        /// Add a log event to the ElasticSearch Repo
        /// </summary>
        /// <param name="loggingEvent"></param>
        protected override void Append(Core.LoggingEvent loggingEvent)
        {
            if (string.IsNullOrEmpty(ConnectionString))
            {
                var exception = new InvalidOperationException("Connection string not present.");
                ErrorHandler.Error("Connection string not included in appender.", exception, ErrorCode.GenericFailure);

                return;
            }

            client = new ElasticClient(ConnectionBuilder.BuildElsticSearchConnection(ConnectionString));
            
            LogEvent logEvent = new LogEvent();
            
            if (logEvent == null)
            {
                throw new ArgumentNullException("logEvent");
            }

            logEvent.LoggerName = loggingEvent.LoggerName;
            logEvent.Domain = loggingEvent.Domain;
            logEvent.Identity = loggingEvent.Identity;
            logEvent.ThreadName = loggingEvent.ThreadName;
            logEvent.UserName = loggingEvent.UserName;
            logEvent.MessageObject = loggingEvent.MessageObject == null ? "" : loggingEvent.MessageObject.ToString();
            logEvent.TimeStamp = loggingEvent.TimeStamp;
            logEvent.Exception = loggingEvent.ExceptionObject == null ? "" : loggingEvent.MessageObject.ToString();
            logEvent.Message = loggingEvent.RenderedMessage;
            logEvent.Fix = loggingEvent.Fix.ToString();

            if (loggingEvent.Level != null)
            {
                logEvent.Level = loggingEvent.Level.DisplayName;
            }

            if (loggingEvent.LocationInformation != null)
            {
                logEvent.ClassName = loggingEvent.LocationInformation.ClassName;
                logEvent.FileName = loggingEvent.LocationInformation.FileName;
                logEvent.LineNumber = loggingEvent.LocationInformation.LineNumber;
                logEvent.FullInfo = loggingEvent.LocationInformation.FullInfo;
                logEvent.MethodName = loggingEvent.LocationInformation.MethodName;
            }

            logEvent.Properties = loggingEvent.Properties.GetKeys().ToDictionary(key => key, key => logEvent.Properties[key].ToString());

            if (client.IsValid)
            {
                var results = client.Index(logEvent);    
            }
            else
            {
                var exception = new InvalidOperationException("Connection to ElasticSearch is invalid.");
                ErrorHandler.Error("Invalid connection to ElasticSearch", exception, ErrorCode.GenericFailure);

                return;
            }
        }
예제 #6
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();
        }
예제 #7
0
        public IEnumerable<Message> GetMessages()
        {
            client = this.Connect();

            foreach (var m in messages)
            {
                client.Index(m);
            }
            return messages;
        }
        async Task IEventProcessor.ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages)
        {
            try
            {
                foreach (EventData eventData in messages)
                {
                    var data = Encoding.UTF8.GetString(eventData.GetBytes());
                    
                  
                    var items = data.Split(new string[]{"##"}, StringSplitOptions.None);

                    var apiManagementLogEvent = new ApiManagementLogEvent
                    {
                        Timestamp = Convert.ToDateTime(items[0]),
                        ServiceName = items[1],
                        UserId = items[2],
                        Region = items[3],
                        RequestId = items[4],
                        IpAddress = items[5],
                        Operation = items[6],
                        Status = items[7],
                        Body = items[8]

                    };
                    
                    
                    //Console.WriteLine(items[8]);
                    var esnode = new Uri(Constants.ElasticsearchUrl);
                    var settings = new ConnectionSettings(
                            esnode, "apim-" + DateTime.Now.ToString("yyyy.MM.dd")
                     );

                    var client = new ElasticClient(settings);
                    client.Index(apiManagementLogEvent);

                }
                
                //Call checkpoint every 5 minutes, so that worker can resume processing from the 5 minutes back if it restarts.
                if (this.checkpointStopWatch.Elapsed > TimeSpan.FromMinutes(5))
                {
                    await context.CheckpointAsync();
                    this.checkpointStopWatch.Restart();
                }
            }
            catch (Exception e)
            {
                Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); Trace.WriteLine(e.InnerException);

            }

        }
예제 #9
0
        public static void UpsertContact(ElasticClient client, Contacts contact)
        {
            var RecordInserted = client.Index(contact);
            

            if (RecordInserted.ToString() != "")
            {
                Console.WriteLine("Indexing Successful !");
            }
            else
            {
                Console.WriteLine("Transaction Failed");
            }
        }
        public static string GenerateRandomEmployeeDocuments(ElasticClient client, string namesDbPath)
        {
            var db = new SQLiteConnection(namesDbPath);
            var female = db.Table<female>().ToList();
            var surname = db.Table<surname>().ToList();

            var rng = new Random();

            const int numEmployeesToCreate = 300;
            var numSkillsGenerated = 0;
            var numCertsGenerated = 0;
            for (var i = 0; i <= numEmployeesToCreate; i++)
            {
                var emp = new EmployeeSkillsDocument()
                {
                    Id = i,
                    FirstName = female[rng.Next(0, female.Count - 1)].name,
                    LastName = surname[rng.Next(0, surname.Count - 1)].name,
                    Skills = new List<Skill>(),
                    Certifications = new List<Certification>()
                };

                for (var j = 0; j <= 10; j++)
                {
                    var candidate = SampleDatasets.SkillsCollection[rng.Next(0, SampleDatasets.SkillsCollection.Count - 1)];
                    if (!emp.Skills.Contains(candidate))
                    {
                        emp.Skills.Add(candidate);
                        numSkillsGenerated++;
                    }
                }

                var numCerts = rng.Next(1, 10);
                for (var k = 0; k <= numCerts; k++)
                {
                    var candidate = SampleDatasets.CertificationCollection[rng.Next(0, SampleDatasets.CertificationCollection.Count - 1)];
                    if (!emp.Certifications.Contains(candidate))
                    {
                        emp.Certifications.Add(candidate);
                        numCertsGenerated++;    
                    }
                }

                client.Index(emp);
            }

            return string.Format("Created {0} employee records with {1} skills and {2} certs in index '{3}'",
                numEmployeesToCreate, numSkillsGenerated, numCertsGenerated, EsIndexName);
        }
예제 #11
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);

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

            // 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);
        }
예제 #12
0
        //Migration blog
        public static bool blogMigration(ElasticClient elastic)
        {
            using (var context = new YoupDEVEntities())
            {
                var blogs = (from b in context.BLOG_Blog
                             select b).ToList<BLOG_Blog>();
                foreach (var blog in blogs)
                {
                    Blog blogElastic = new Blog(blog.Blog_id.ToString(), blog.TitreBlog, blog.Theme_id.ToString());
                    var indexB = elastic.Index(blogElastic);
                    /* var visits = (from v in context.BLOG_Visite
                                  where v.Blog_Id == blog.Blog_id
                                  select v).Count();*/

                    var articles = (from a in context.BLOG_Article
                                    where a.Blog_id == blog.Blog_id
                                    select a).ToList<BLOG_Article>();

                    foreach (var article in articles)
                    {
                        BlogPost articleElastic = new BlogPost(article.Article_id.ToString(), article.ContenuArticle, blog.Utilisateur_id.ToString(), article.TitreArticle);
                        var indexA = elastic.Index(articleElastic);

                        var comments = (from c in context.BLOG_Commentaire
                                        where c.Article_id == article.Article_id
                                        select c).ToList<BLOG_Commentaire>();
                        foreach (var comment in comments)
                        {
                            BlogPostComment commentElastic = new BlogPostComment(comment.Commentaire_id.ToString(), comment.ContenuCommentaire, comment.Utilisateur_id.ToString());
                            var indexBPC = elastic.Index(commentElastic);
                        }
                    }
                }
            }
            return true;
        }
        public void Can_insert_data()
        {
            using (var elasticsearch = new Elasticsearch())
            {
                ////Arrange
                var client = new ElasticClient(new ConnectionSettings(elasticsearch.Url));

                ////Act
                client.Index(new { id = "tester"}, i => i.Index("test-index"));

                ////Assert
                var result = client.Get<dynamic>("tester", "test-index");
                Assert.That(result, Is.Not.Null);
            }
        }
        public HttpResponseMessage CreateDocument(FormDataCollection postData)
        {
            SampleConfiguration config = new SampleConfiguration();
            esNode = new Uri(config.ElasticsearchServerHost);
            connectionSettings = new ConnectionSettings(esNode, defaultIndex: postData.Get("indexName"));
            esClient = new ElasticClient(connectionSettings);

            var product = new Product(Convert.ToInt32(postData.Get("id")),
                postData.Get("title"),
                postData.Get("brand"),
                Convert.ToDouble(postData.Get("price")));

            IIndexResponse indexResponse = esClient.Index(product);

            return Request.CreateResponse(HttpStatusCode.Created, indexResponse.Created);
        }
        public void Execute()
        {
            if (TranslationMemories == null)
                throw new ArgumentNullException("No data to import, please set TranslationMemories property first.");

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

            foreach (TranslationMemory tm in TranslationMemories)
            {
                var indexResult = client.Index(tm);
                Console.Write(indexResult);
            }
        }
예제 #16
0
		/// <summary>
		/// Mainly used to profile the serialization performance and memory usage
		/// </summary>
		/// <param name="args"></param>
		static void Main(string[] args)
		{
			var settings = new ConnectionSettings(new Uri("http://localhost:9200"),"test-index");
			var client = new ElasticClient(settings);
			int calls = 10000;
			Console.WriteLine("done");
			Console.ReadLine();
			//using (var pbar = new ProgressBar(ticks, "Doing loads of in memory calls"))
			{
				for (int i = calls; i > 0; i--)
				{
					client.Index(new Doc() {Id = "asdasd" + i, Name = "Repository"});
				}
			}
			Console.WriteLine("done");
			Console.ReadLine();
		}
예제 #17
0
        private static void ElasticSearchTest()
        {
            var node = new Uri("http://localhost:9200");

            var settings = new ConnectionSettings(
                node,
                defaultIndex: "my-application"
            );

            var client = new ElasticClient(settings);

            Product product = new Product("Tv", DateTime.Now, 200, new string[] { "45''", "48''" });

            var index = client.Index(product);

            ISearchResponse<Product> searchResults = client.Search<Product>(s => s.MatchAll());
            Product prd = searchResults.Hits.FirstOrDefault().Source;
        }
예제 #18
0
        // GET: api/Home
        public IEnumerable<PersonModel> Get()
        {
            var node = new Uri("http://search-logging-4b4ahpkoiumas4xso6qbqrcel4.eu-west-1.es.amazonaws.com");
            var settings = new ConnectionSettings(node);
            var client = new ElasticClient(settings);

            var list = new List<PersonModel>
            {
                new PersonModel {Name = "Murat Akyüz", City = "Sinop"},
                new PersonModel {Name = "Orhan Atılgan", City = "Muğla"}
            };

            var person = new PersonModel
            {
                Id = "1",
                Name = "Murat",
                City = "Sinop"
            };

            //var index = client.Index(person, i => i
            //    .Index("deneme-index")
            //    .Type("deneme-type")
            //    .Refresh()
            //    .Ttl("10m")
            //    );

            var index = client.Index(list, z => z.Index("deneme-index").Type("deneme-type"));

            //var index = client.Index(list, z => z
            //    .Index("deneme-index")
            //    .Type("deneme-type")
            //    .Refresh()
            //    .Ttl("10m"));

            //var index = client.Index(list, i => i
            //    .Index("another-index")
            //    .Type("another-type")
            //    .Id("1-should-not-be-the-id")
            //    .Refresh()
            //    .Ttl("1m"));

            return list;
        }
        public void CreatePersonWithImageAttachment()
        {
            var node = new Uri("http://localhost:9200");

            var settings = new ConnectionSettings(
                node,
                defaultIndex: "my-application"
            );

            var client = new ElasticClient(settings);
            //client.DeleteIndex("index-name");
            client.CreateIndex("index-name", c => c
                 .AddMapping<Document>(m => m.MapFromAttributes())
              );

            string path = "c:\\test.png";

            var attachment = new Attachment
            {
                Content = Convert.ToBase64String(File.ReadAllBytes(path)),
                ContentType = "image/jpeg",
                Name = "IMG_9896.JPG"
            };

            var person = new Person
            {
                Id = Convert.ToString(new Random(DateTime.Now.Second).Next(20000)),
                Firstname = "Martijn",
                Lastname = "Laarman",
                File = new[] { attachment }
            };

            var index = client.Index(person);

            var results = client.Search<Person>(s => s
                .From(0)
                .Size(10)
                .Query(q => q
                     .Term(p => p.Firstname, "martijn")
                )
            );
        }
예제 #20
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);
            }

        }
예제 #21
0
		//TODO figure out a way to trigger this again
		//[U]
		public void DispatchIndicatesMissingRouteValues()
		{
			var settings = new ConnectionSettings(new Uri("http://doesntexist:9200"));
			var client = new ElasticClient(settings);

			Action dispatch = () => client.Index(new Project(), p=>p.Index(null));
			var ce = dispatch.ShouldThrow<ArgumentException>();
			ce.Should().NotBeNull();
			ce.Which.Message.Should().Contain("index=<NULL>");
		}
예제 #22
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();
        }
 private static void WriteErrorsIntoElasticSearchIndex(ElasticClient elasticClient, List<error> errors)
 {
     foreach (var error in errors)
     {
         elasticClient.Index(error);
     }
 }
        /// <summary>
        /// (re-)Index Albums
        /// </summary>
        /// <referenceUrl>https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/_nest.html</referenceUrl>
        /// <returns></returns>
        public ActionResult ReIndex()
        {
            var node = new Uri(ConfigurationManager.AppSettings["ElasticSearchUrl"] ?? "http://localhost:9200");
            var esIndex = ConfigurationManager.AppSettings["ESDefaultIndex"] ?? "musicstore";
            //var settings = new ConnectionSettings("localhost", 9200);
            //var settings = new ConnectionSettings(node, defaultIndex: esIndex);
            var settings = new ConnectionSettings(node);
            settings.SetDefaultIndex(esIndex);
            var client = new ElasticClient(settings);

            foreach (var album in db.Albums)
            {
                //client.Index(album, "musicstore", "albums", album.AlbumId);   // outdated
                //client.Index(album, i => i.Id(album.AlbumId))
                client.Index(album);    // ES will infer the
            }

            return RedirectToAction("Index");
        }
        private static void Index(DocumentModel document, String operation)
        {
            var uriString = ConfigurationManager.AppSettings["SEARCHBOX_URL"];
            var searchBoxUri = new Uri(uriString);

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

            var client = new ElasticClient(settings);

            if (!client.IndexExists(indexName).Exists)
            {
                // Create a new "sample" index with default settings
                ICreateIndexRequest iCreateIndexReq = new CreateIndexRequest(indexName);
                iCreateIndexReq.IndexSettings = new IndexSettings();
                iCreateIndexReq.IndexSettings.NumberOfReplicas = 10;

                //iCreateIndexReq.IndexSettings.Mappings = new List<RootObjectMapping>();
                //RootObjectMapping rootObjectMapping = new RootObjectMapping();
                //rootObjectMapping.AllFieldMapping()
                //iCreateIndexReq.IndexSettings.Mappings.
                //client.CreateIndex(iCreateIndexReq);
                //client.CreateIndex(indexName,s=>s.)
                var resCreate = client.CreateIndex(indexName, s => s.AddMapping<DocumentModel>(f => f.MapFromAttributes()).NumberOfReplicas(1).NumberOfShards(10));

                //client.CreateIndex(indexName, new IndexSettings());
                //client.create
            }

            if (operation.Equals("delete"))
            {
                //client.DeleteById(indexName, "documents", document.DocumentId);
                IDeleteByQueryRequest iDeleteByQueryRequest = new DeleteByQueryRequest();
                //IDeleteIndexRequest delReq = new DeleteIndexRequest(indexName);
                //client.DeleteIndex()
                //client.DeleteByQuery(new DeleteByQueryRequest())
                client.Delete<DocumentModel>(f => f.Id(document.DocumentId).Index(indexName).Refresh());
                //var response = this.Client.Delete<ElasticsearchProject>(f=>f.Id(newDocument.Id).Index(newIndex).Refresh());
            }
            else
            {
               //IIndexRequest<DocumentModel> indexRequest = IndexRequest<DocumentModel>();
               //client.Index(i)
               //client.Index(document, indexName, "documents", document.DocumentId);
               //IndexDescriptor indexDesc = IndexDescriptor;
               //IndexRequestParameters indexParameter = new IndexRequestParameters();
               // indexParameter.Replication(1);
                client.Index(document, i => i.Id(document.DocumentId).Index(indexName));
                //client.Index();
                //client.Index()
            }
        }
        private static void Index(Document document, String operation)
        {
            var uriString = ConfigurationManager.AppSettings["SEARCHBOX_URL"];
            var searchBoxUri = new Uri(uriString);

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

            var client = new ElasticClient(settings);

            if (!client.IndexExists("sample").Exists)
            {
                // Create a new "sample" index with default settings
                client.CreateIndex("sample", new IndexSettings());
            }

            if (operation.Equals("delete"))
            {
                client.DeleteById("sample", "documents", document.DocumentId);
            }
            else
            {
                client.Index(document, "sample", "documents", document.DocumentId);
            }
        }
예제 #27
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();
        }
예제 #28
0
        private static void RandomCDs(int n, string indexName, ElasticClient client)
        {
            Log.Logger.Information("Creating {numberOfDocs} CD documents in index {indexName}", n, indexName);

            for (var i = 0; i < n; i++)
            {
                var book = new CD
                {
                    Id = i,
                    Title = LoremNET.Lorem.Words(1, 5),
                    Genere = LoremNET.Lorem.Words(1, 2),
                    ReleaseDate = LoremNET.Lorem.DateTime(1990)
                };

                client.Index(book, ind => ind.Index(indexName));

                if (i%1000 == 0)
                    Log.Logger.Information("Created {numberOfDocs} CD documents in index {indexName}", i, indexName);
            }
        }
예제 #29
0
        private static void RandomBooks(int n, string indexName, ElasticClient client)
        {
            Log.Logger.Information("Creating {numberOfDocs} book documents in index {indexName}", n, indexName);

            for (var i = 0; i < n; i++)
            {
                var book = new Book
                {
                    Id = i,
                    Description = LoremNET.Lorem.Paragraph(20, 10),
                    Title = LoremNET.Lorem.Words(1, 5),
                    Year = (int) LoremNET.Lorem.Number(1965, 2015)
                };

                client.Index(book, ind => ind.Index(indexName));

                if (i%1000 == 0)
                    Log.Logger.Information("Created {numberOfDocs} book documents in index {indexName}", i, indexName);
            }
        }
        public ActionResult Create([Bind(Include = "JSON,Id,AspNetUserId,Name,Date,Url_Img,Url_Img_Origin,Str1,Str2")] Demotivator demotivator, string newtag)
        {


            var uri = new Uri("https://IlwEAOgvDkuHk3yiB74RhwSs1YC0KCUu:@aniknaemm.east-us.azr.facetflow.io");
            var settings = new ConnectionSettings(uri).SetDefaultIndex("indexdem");
            var client = new ElasticClient(settings);
            

            // Execute a search using the connection from above.
       

            if (ModelState.IsValid)
            {

                demotivator.AspNetUserId = User.Identity.GetUserId();
                demotivator.Date = DateTime.Now;
                
                db.Demotivators.Add(demotivator);

                db.SaveChanges();

                var index = client.Index(demotivator);
                client.Refresh();
               
                AddTag(newtag, demotivator.Id);
                return RedirectToAction("Index");
            }

            ViewBag.AspNetUserId = new SelectList(db.AspNetUsers, "Id", "Email", demotivator.AspNetUserId);
            return View(demotivator);
        }