Exemple #1
0
        static void Main(string[] args)
        {
            var indexName          = "geodocument";
            var connectionPool     = new Elasticsearch.Net.SniffingConnectionPool(new Uri[] { new Uri("http://localhost:9200") });
            var connectionSettings = new Nest.ConnectionSettings(connectionPool);

            connectionSettings.DefaultIndex(indexName);
            connectionSettings.DisableDirectStreaming();
            var elasticClient = new ElasticClient(connectionSettings);
            Func <TypeMappingDescriptor <GeoDocument>, ITypeMapping> typeMapping = m => m
                                                                                   .Dynamic(false)
                                                                                   .Properties(ps => ps
                                                                                               .Keyword(k => k
                                                                                                        .Name(n => n.DocId))
                                                                                               .GeoShape(g => g
                                                                                                         .PointsOnly(false)
                                                                                                         .Name(o => o.GeoField)));

            elasticClient.CreateIndex(new CreateIndexDescriptor(indexName).Mappings(ms => ms.Map(typeMapping)));
            var polygon  = "{\"type\":\"Polygon\",\"coordinates\":[[[5.856956,51.002753],[5.856928,51.002771],[5.856687,51.002853],[5.856956,51.002753]]]}";
            var document = new GeoDocument()
            {
                DocId    = "1",
                GeoField = JsonConvert.DeserializeObject <object>(polygon),
            };
            var indexResponse = elasticClient.IndexDocument(document);

            Console.WriteLine(indexResponse.DebugInformation);

            elasticClient.DeleteIndex(new DeleteIndexRequest(indexName));
            Console.ReadKey();
        }
Exemple #2
0
        public async Task Example()
        {
            Environment.SetEnvironmentVariable("EVENTSTOREURL", "tcp://*****:*****@"http://localhost:9200"; //Environment.GetEnvironmentVariable("ELASTICSEARCHURL");
            Uri    node             = new Uri(elasticSearchUrl);

            Nest.ConnectionSettings settings = new Nest.ConnectionSettings(node);
            settings.DisableDirectStreaming();
            ElasticClient elasticClient = new ElasticClient(settings);

            // We wire up EventFlow with all of our classes. Instead of adding events,
            // commands, etc. explicitly, we could have used the the simpler
            // AddDefaults(Assembly) instead.
            using (var resolver = EventFlowOptions.New
                                  .AddEvents(typeof(ExampleEvent))
                                  .AddCommands(typeof(ExampleCommand), typeof(ExampleUpdateCommand))
                                  .AddCommandHandlers(typeof(ExampleCommandHandler), typeof(ExampleUpdateCommandHandler))
                                  .ConfigureEventStorePersistence("tcp://localhost:1113")
                                  .ConfigureElasticsearch(() => elasticClient)
                                  .UseElasticsearchReadModel <ExampleReadModel>()
                                  //.UseInMemoryReadStoreFor<ExampleReadModel>()
                                  .CreateResolver())
            {
                for (int i = 0; i < 10; i++)
                {
                    var rndMagicNum = new Random().Next();

                    // Create a new identity for our aggregate root
                    var exampleId = ExampleId.New;

                    // Resolve the command bus and use it to publish a command
                    var commandBus = resolver.Resolve <ICommandBus>();
                    await commandBus.PublishAsync(
                        new ExampleCommand(exampleId, rndMagicNum), CancellationToken.None)
                    .ConfigureAwait(false);


                    await commandBus.PublishAsync(
                        new ExampleUpdateCommand(exampleId, 1), CancellationToken.None)
                    .ConfigureAwait(false);


                    // Resolve the query handler and use the built-in query for fetching
                    // read models by identity to get our read model representing the
                    // state of our aggregate root
                    var queryProcessor   = resolver.Resolve <IQueryProcessor>();
                    var exampleReadModel = await queryProcessor.ProcessAsync(
                        new ReadModelByIdQuery <ExampleReadModel>(exampleId), CancellationToken.None)
                                           .ConfigureAwait(false);

                    // Verify that the read model has the expected magic number
                    exampleReadModel.MagicNumber.Should().Be(1);

                    Output.WriteLine(exampleId.Value);
                }
            }
        }
        public static IElasticClient ConfigureElastic()
        {
            Logger.Info("Setting up Elastic");
            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 (string.IsNullOrEmpty(index))
            {
                throw new ArgumentException("No DefaultIndex parameter in elastic connection string");
            }

            index = index.Substring(13);

            var node = new Uri(url.Substring(4));
            var pool = new Elasticsearch.Net.SingleNodeConnectionPool(node);

            var regex    = new Regex("([+\\-!\\(\\){}\\[\\]^\"~*?:\\\\\\/>< ]|[&\\|]{2}|AND|OR|NOT)", RegexOptions.Compiled);
            var settings = new Nest.ConnectionSettings(pool, (_) => new JsonNetSerializer(_))
                           .DefaultIndex(index)
                           .DefaultTypeNameInferrer(type =>
                                                    type.FullName
                                                    .Replace("Pulse.Presentation.ServiceStack.", "")
                                                    .Replace("Pulse.Application.Elastic.", "")
                                                    .Replace('.', '_')
                                                    )
                           .DefaultFieldNameInferrer(field => regex.Replace(field, ""));

#if DEBUG
            settings = settings.DisableDirectStreaming();
#endif

            var client = new ElasticClient(settings);


            if (!client.IndexExists(index).Exists)
            {
                client.CreateIndex(index, i => i
                                   .Settings(s => s
                                             .NumberOfShards(8)
                                             .NumberOfReplicas(0)
                                             .Analysis(analysis => analysis
                                                       .TokenFilters(f => f.NGram("ngram", d => d.MinGram(1).MaxGram(15)))
                                                       .Analyzers(a => a
                                                                  .Custom("default_index", t => t.Tokenizer("keyword").Filters(new[] { "standard", "lowercase", "asciifolding", "kstem", "ngram" }))
                                                                  .Custom("suffix", t => t.Tokenizer("keyword").Filters(new[] { "standard", "lowercase", "asciifolding", "reverse" }))
                                                                  )
                                                       )));
            }

            return(client);
        }
        public static IElasticClient ConfigureElastic()
        {
            Logger.Info("Setting up Elastic");
            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 (string.IsNullOrEmpty(index))
                throw new ArgumentException("No DefaultIndex parameter in elastic connection string");

            index = index.Substring(13);

            var node = new Uri(url.Substring(4));
            var pool = new Elasticsearch.Net.SingleNodeConnectionPool(node);

            var regex = new Regex("([+\\-!\\(\\){}\\[\\]^\"~*?:\\\\\\/>< ]|[&\\|]{2}|AND|OR|NOT)", RegexOptions.Compiled);
            var settings = new Nest.ConnectionSettings(pool, (_) => new JsonNetSerializer(_))
                .DefaultIndex(index)
                .DefaultTypeNameInferrer(type =>
                        type.FullName
                        .Replace("Pulse.Presentation.ServiceStack.", "")
                        .Replace("Pulse.Application.Elastic.", "")
                        .Replace('.', '_')
                        )
                .DefaultFieldNameInferrer(field => regex.Replace(field, ""));
#if DEBUG
            settings = settings.DisableDirectStreaming();
#endif

            var client = new ElasticClient(settings);


            if (!client.IndexExists(index).Exists)
                client.CreateIndex(index, i => i
                    .Settings(s => s
                        .NumberOfShards(8)
                        .NumberOfReplicas(0)
                        .Analysis(analysis => analysis
                        .TokenFilters(f => f.NGram("ngram", d => d.MinGram(1).MaxGram(15)))
                        .Analyzers(a => a
                            .Custom("default_index", t => t.Tokenizer("keyword").Filters(new[] { "standard", "lowercase", "asciifolding", "kstem", "ngram" }))
                            .Custom("suffix", t => t.Tokenizer("keyword").Filters(new[] { "standard", "lowercase", "asciifolding", "reverse" }))
                        )
                    )));

            return client;
        }