public virtual IndexResult CreateIndex <T>(CreateIndexDescriptor createIndexDescriptor) where T : class
        {
            ElasticClient elasticClient = this.DbContextFactory.GetDbContext() as ElasticClient;

            string indexName = typeof(T).Name.ToLower();
            string aliasName = string.Format("{0}_{1}", "alias", indexName);

            if (createIndexDescriptor == null)
            {
                createIndexDescriptor = new CreateIndexDescriptor(indexName)
                                        .Mappings(ms => ms
                                                  .Map <T>(m => m.AutoMap()))
                                        .Aliases(a => a.Alias(aliasName));
            }

            var request = new IndexExistsRequest(indexName);
            var result  = elasticClient.Indices.Exists(request);

            if (result.Exists)
            {
                return(null);
            }

            var response = elasticClient.Indices.Create(createIndexDescriptor);

            return(new IndexResult
            {
                IsValid = response.IsValid,
                ResponseMessage = response.DebugInformation,
                Exception = response.OriginalException
            });
        }
        /// <inheritdoc />
        public async Task CreateIndexAsync()
        {
            IQueryModel instance  = (IQueryModel)Activator.CreateInstance(typeof(TIndexModel), true);
            string      _idx_name = instance.GetIndexName();
            IndexName   indexName = new IndexName()
            {
                Name = _idx_name
            };

            var indexExistsRequest = new IndexExistsRequest(indexName);
            var existsResult       = await GetClient().IndexExistsAsync(indexExistsRequest);

            if (existsResult.Exists)
            {
                await GetClient().DeleteIndexAsync(indexName);
            }


            var createIndexResponse = await GetClient().CreateIndexAsync(indexName, c => c
                                                                         .Mappings(ms => ms
                                                                                   .Map <TIndexModel>(m => m
                                                                                                      .AutoMap()))
                                                                         .Settings(s => s
                                                                                   .Analysis(a => a
                                                                                             .Analyzers(an => an
                                                                                                        .Custom("default", ca => ca
                                                                                                                .Tokenizer("lowercase")
                                                                                                                .Filters("asciifolding"))))));
        }
예제 #3
0
        static void Main(string[] args)
        {
            var nodes = new Uri[]
            {
                new Uri("https://elasticsearch01:9200"),
                new Uri("https://elasticsearch01:9200"),
                new Uri("https://elasticsearch01:9200")
            };

            var pool     = new StaticConnectionPool(nodes);
            var settings = new ConnectionSettings(pool);

            settings.BasicAuthentication("es_user", "test1");
            var idx = "testindex-" + DateTime.Now.ToString("yyyy.MM.dd");

            settings.DefaultIndex(idx);
            var client  = new ElasticClient(settings);
            var request = new IndexExistsRequest(idx);
            var result  = client.IndexExists(request);

            if (!result.Exists)
            {
                var taskCreate = client.CreateIndexAsync(idx).GetAwaiter();
                while (!taskCreate.IsCompleted)
                {
                    Console.WriteLine(taskCreate.IsCompleted);
                }
            }
            Console.ReadLine();
        }
        public SampleElasticsearchClient(string endPoint, Amazon.RegionEndpoint regionEndPoint)
        {
            AWSCredentials    awsCredentials = FallbackCredentialsFactory.GetCredentials();
            AwsHttpConnection conn           = new AwsHttpConnection(regionEndPoint.SystemName,
                                                                     new StaticCredentialsProvider(new AwsCredentials()
            {
                AccessKey = awsCredentials.GetCredentials().AccessKey,
                SecretKey = awsCredentials.GetCredentials().SecretKey,
                Token     = awsCredentials.GetCredentials().Token
            }));

            var pool = new SingleNodeConnectionPool(new Uri(endPoint));
            ConnectionSettings settings = new ConnectionSettings(pool, conn)
                                          .DisableDirectStreaming()
                                          .InferMappingFor <LogEntry>(m => m.IndexName("logs"));

            //.DefaultMappingFor<LogEntry>(m => m.IndexName("logs"));

            _esClient = new ElasticClient(settings);

            IndexName logIndex = IndexName.From <LogEntry>();

            var req = new IndexExistsRequest(logIndex);
            var res = _esClient.IndexExists(req);

            if (!res.Exists)
            {
                _esClient.CreateIndex("logs", c => c
                                      .Mappings(md => md.Map <LogEntry>(m => m.AutoMap())));
            }
        }
예제 #5
0
        /// <summary>
        /// 索引是否存在
        /// </summary>
        /// <param name="indexName"></param>
        /// <returns></returns>
        public bool IndexExist(string indexName)
        {
            IndexExistsRequest request = new IndexExistsRequest(indexName);
            var response = _es.IndexExists(request);

            return(response.Exists);
        }
예제 #6
0
        public IndexExistsRequestTests()
        {
            var request  = new IndexExistsRequest("my-index");
            var response = this._client.IndexExists(request);

            this._status = response.ConnectionStatus;
        }
예제 #7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            services.AddControllersWithViews();
            services.AddHttpContextAccessor();

            var esClientSettings = new ConnectionSettings(new Uri(Configuration["Elasticsearch:Url"]))
                                   .DefaultIndex(Configuration["Elasticsearch:Index"])
                                   .ThrowExceptions();

            var esClient = new ElasticClient(esClientSettings);

            var requestExistIndex = new IndexExistsRequest("subscriptions");

            if (!esClient.Indices.Exists(requestExistIndex).Exists)
            {
                var settings = new IndexSettings {
                    NumberOfReplicas = 0, NumberOfShards = 1
                };
                var indexConfig = new IndexState {
                    Settings = settings
                };
                esClient.Indices.Create("subscriptions", c => c
                                        .InitializeUsing(indexConfig)
                                        .Map <Subscriber>(mp => mp.AutoMap()));
            }

            var emailConfig = Configuration
                              .GetSection("EmailConfiguration")
                              .Get <EmailConfig>();

            var semanticGraph = new SemanticGraph(DefaultGraphPath, DefaultNodeIdPropName,
                                                  DefaultEdgePropName, lablesDocFreqPath: LablesDocFreqPath);

            services.AddSingleton <IElasticClient>(esClient);
            services.AddSingleton(emailConfig);
            services.AddSingleton(semanticGraph);

            services.AddScoped <INewsRepository, NewsRepository>();
            services.AddScoped <INewsService, NewsService>();

            services.AddScoped <ISubscribeRepository, SubscribeRepository>();
            services.AddScoped <ISubscribeService, SubscribeService>();
            services.AddScoped <IEmailSender, EmailSender>();
            services.AddScoped <IEmailService, EmailService>();
            services.AddScoped <ISemanticService, SemanticService>();

            // In production, the Angular files will be served from this directory

            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }
예제 #8
0
        public static ElasticClient GetElasticClient(string elasticSearchUri, string elasticSearchIndex)
        {
            var node     = new Uri(elasticSearchUri);
            var settings = new ConnectionSettings(node).DefaultIndex(elasticSearchIndex);
            var client   = new ElasticClient(settings);

            var request = new IndexExistsRequest(elasticSearchIndex);
            var result  = client.IndexExists(request);

            if (!result.Exists)
            {
                client = CreateIndex(client, elasticSearchIndex);
            }

            return(client);
        }
예제 #9
0
        public void CheckIndexFor <T>() where T : class
        {
            var indexName = typeof(T).Name.ToLower();

            if (ExistantIndexes.Contains(indexName))
            {
                return;
            }

            this.Map <T>(x => x.AutoMap().Index(indexName));

            var request = new IndexExistsRequest(indexName);
            var result  = this.IndexExists(request);

            if (!result.Exists)
            {
                this.CreateIndex(indexName);
            }

            ExistantIndexes.Add(indexName);
        }
        public async Task <bool> CreateIndexAsync()
        {
            var createIndexDescriptor = new CreateIndexDescriptor("users")
                                        .Map <User>(m => m
                                                    .AutoMap()
                                                    .Properties(ps => ps
                                                                .Completion(c => c
                                                                            .Name(p => p.Suggest))));

            var request     = new IndexExistsRequest("users");
            var indexExists = _elasticClient.Indices.Exists(request);

            if (indexExists.IsValid)
            {
                _elasticClient.Indices.Delete("users");
            }

            var response = await _elasticClient.Indices.CreateAsync("users");

            return(response.IsValid);
        }
예제 #11
0
        /// <summary>
        /// elastic search indexi yoksa oluşturur
        /// </summary>
        /// <returns>elastic search apisinden hata alırsa false ile birlikte hatayı döner</returns>
        public Tuple <bool, string> CreateNewIndex()
        {
            var createIndexDescriptor = new CreateIndexDescriptor(IndexName)
                                        .Mappings(ms => ms
                                                  .Map <T>(m => m.AutoMap())
                                                  ).Aliases(a => a.Alias(AliasName));

            var request = new IndexExistsRequest(IndexName);
            var result  = client.IndexExists(request);

            if (!result.Exists)
            {
                var response = client.CreateIndex(createIndexDescriptor);
                if (!response.IsValid)
                {
                    return(new Tuple <bool, string>(false, response.ServerError.Error.ToString()));
                }
            }

            return(new Tuple <bool, string>(true, ""));
        }
        public ElasticSearchServiceLibrary(string indexName, string node, int numberOfReplicas = 5, int numberOfShards = 5)
        {
            var uri      = new Uri(node);
            var settings = new ConnectionSettings(uri);

            settings.DefaultIndex(indexName);

            var indexSettings = new IndexSettings();

            indexSettings.NumberOfReplicas = numberOfReplicas;
            indexSettings.NumberOfShards   = numberOfShards;

            _client = new ElasticClient(settings);
            var indexDescriptor = new CreateIndexDescriptor(indexName).Mappings(ms => ms.Map <TModel>(m => m.AutoMap()));

            var request = new IndexExistsRequest(indexName);

            if (!_client.IndexExists(request).Exists)
            {
                _client.CreateIndex(indexName, i => indexDescriptor);
            }
        }
        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);
        }
        private void EnsureIndexExists(ElasticClient esClient, string indexName)
        {
            var indexExistsRequest = new IndexExistsRequest(indexName);
            var indexExistsResult = esClient.IndexExists(indexExistsRequest);

            if (indexExistsResult.Exists == false)
            {
                var createIndexRequest = new CreateIndexRequest(indexName);

                var createIndexResponse = esClient.CreateIndex(createIndexRequest);

                if (createIndexResponse.Acknowledged == false)
                {
                    throw new ApplicationException(string.Format("Kunne ikke lave {0} index", indexName));
                }
            }
        }
		public IndexExistsRequestTests()
		{
			var request = new IndexExistsRequest("my-index");
			var response = this._client.IndexExists(request);
			this._status = response.ConnectionStatus;
		}