コード例 #1
0
        static void WriteToEngine(IDictionary <string, object> values)
        {
            // If contains rating, this is a movie.
            if (values.ContainsKey("rating"))
            {
                Movie movie;
                try
                {
                    movie = new Movie(values);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Unable to create a Movie object. Skipping. Values: {0}", values.ToPrettyString());
                    movie = null;
                }

                if (movie != null)
                {
                    IIndexResponse response = _client.Index(movie, i => i.Index("movies-test"));
                    Console.WriteLine("added one Movie: {0}", response.Id);
                }
            }
            else
            {
                // This is an actor
                // _client.Index(, i => i.Index("movies-test").Type("actor"));
            }
        }
コード例 #2
0
        /// <summary>
        /// Executes the sender reading data from valuesToBeSent.
        /// </summary>
        /// <returns>Task</returns>
        /// <example>To copy data from SQL Server to Elasticsearch following *.json configuration file can be used:
        /// <code title="SQLServerToElasticsearch.json">
        /// <![CDATA[{
        ///   "$type": "StanskinsImplementation.SimpleJob, StanskinsImplementation",
        ///   "Receivers": {
        ///     "$type": "StankinsInterfaces.OrderedList`1[[StankinsInterfaces.IReceive, StankinsInterfaces]], StankinsInterfaces",
        ///     "0": {
        ///       "$type": "ReiceverDBStmtSqlServer.ReceiverStmtSqlServer, ReiceverDBStmtSqlServer",
        ///       "ConnectionString": "Server=(local)\\SQL2016;Database=IronSQLDBA;Trusted_Connection=True;",
        ///       "CommandType": 4,
        ///       "CommandText": "dbo.active_slow_query_select",
        ///       "FileNameSerializeLastRow": "IronSQLDBA_active_slow_query_select_last_row.json",
        ///       "ParametersMappings": "@original_id=original_id"
        ///     }
        ///   },
        ///   "FiltersAndTransformers": {
        ///     "$type": "StankinsInterfaces.OrderedList`1[[StankinsInterfaces.IFilterTransformer, StankinsInterfaces]], StankinsInterfaces"
        ///   },
        ///   "Senders": {
        ///     "$type": "StankinsInterfaces.OrderedList`1[[StankinsInterfaces.ISend, StankinsInterfaces]], StankinsInterfaces",
        ///     "0": {
        ///       "$type": "SenderElasticSearch.SenderToElasticSearch, SenderElasticSearch",
        ///       "Uri": "http://localhost:9200",
        ///       "IndexName": "ironsqldba-index-active-slow-query",
        ///       "TypeName": "active-slow-query",
        ///       "Id": "id"
        ///     }
        ///   }
        /// }]]>
        /// </code>
        /// </example>
        public async Task Send()
        {
            var settings = new ConnectionSettings(new Uri(this.Uri));
            var client   = new ElasticClient(settings);

            foreach (IRow item in valuesToBeSent)
            {
                IndexRequest <object> request;

                if (string.IsNullOrWhiteSpace(this.Id))
                {
                    request = new IndexRequest <object>(this.IndexName, this.TypeName);
                }
                else
                {
                    string idValue = item.Values[this.Id].ToString(); //TODO: better solution ? (API Nest.Id string/long/Document)
                    request = new IndexRequest <object>(this.IndexName, this.TypeName, idValue);
                }

                request.Document = item.Values;
                IIndexResponse resp = await client.IndexAsync(request);

                if (!resp.ApiCall.Success)
                {
                    throw new Exception(resp.ApiCall.DebugInformation);
                }
            }
        }
コード例 #3
0
        public ElasticIndexResponse Index <T>(T entity) where T : class
        {
            int       retryCount    = 0;
            Exception lastException = null;

            while (retryCount < MaxRetry)
            {
                try
                {
                    IIndexResponse indexResponse = _client.Index(entity);
                    if (indexResponse != null && indexResponse.IsValid)
                    {
                        throw new ElasticSearchServerException(indexResponse.ServerError.Error);
                    }

                    ElasticIndexResponse response = new ElasticIndexResponse();

                    return(response);
                }
                catch (WebException wex)
                {
                    lastException = wex;
                }
                catch (Exception ex)
                {
                    lastException = ex;
                }

                retryCount++;

                Thread.Sleep(500);
            }
            throw new ElasticSearchException("There was an error occured while indexing", lastException);
        }
コード例 #4
0
        protected override void ExpectResponse(IIndexResponse response)
        {
            response.ShouldBeValid();

            var searchResponse = Client.Search <Document>(s => s
                                                          .Index(CallIsolatedValue)
                                                          .Query(q => q
                                                                 .Match(m => m
                                                                        .Field(a => a.Attachment.Content)
                                                                        .Query("NEST mapper")
                                                                        )
                                                                 )
                                                          );

            searchResponse.ShouldBeValid();
            searchResponse.Documents.Count().Should().Be(1);

            searchResponse = Client.Search <Document>(s => s
                                                      .Index(CallIsolatedValue)
                                                      .StoredFields(f => f.Field(d => d.Attachment.ContentType))
                                                      .Query(q => q
                                                             .MatchAll()
                                                             )
                                                      );

            searchResponse.ShouldBeValid();
            searchResponse.Documents.Count().Should().Be(1);

            // mapper attachment extracts content type
            searchResponse.Hits.First()
            .Fields
            .ValueOf <Document, string>(d => d.Attachment.ContentType)
            .Should().Be("application/pdf");
        }
コード例 #5
0
        protected override void ExpectResponse(IIndexResponse response)
        {
            response.ShouldBeValid();

            // search on language (document is detected as French)
            var searchResponse = Client.Search <Document>(s => s
                                                          .StoredFields(f => f
                                                                        .Field(d => d.Attachment.Name)
                                                                        .Field(d => d.Attachment.Author)
                                                                        .Field(d => d.Attachment.Content)
                                                                        .Field(d => d.Attachment.ContentLength)
                                                                        .Field(d => d.Attachment.ContentType)
                                                                        .Field(d => d.Attachment.Date)
                                                                        .Field(d => d.Attachment.Keywords)
                                                                        .Field(d => d.Attachment.Language)
                                                                        .Field(d => d.Attachment.Title)
                                                                        )
                                                          .Index(CallIsolatedValue)
                                                          .Query(q => q
                                                                 .MatchAll()
                                                                 )
                                                          );

            var documents = new List <Document>();

            // try to set all the metadata
            foreach (var hit in searchResponse.Hits)
            {
                var document = new Document {
                    Attachment = new Nest.Attachment()
                };
                document.Attachment.Name          = hit.Fields.ValueOf <Document, string>(d => d.Attachment.Name);
                document.Attachment.Author        = hit.Fields.ValueOf <Document, string>(d => d.Attachment.Author);
                document.Attachment.Content       = hit.Fields.ValueOf <Document, string>(d => d.Attachment.Content);
                document.Attachment.ContentLength = hit.Fields.ValueOf <Document, long?>(d => d.Attachment.ContentLength);
                document.Attachment.ContentType   = hit.Fields.ValueOf <Document, string>(d => d.Attachment.ContentType);
                document.Attachment.Date          = hit.Fields.ValueOf <Document, DateTime?>(d => d.Attachment.Date);
                document.Attachment.Keywords      = hit.Fields.ValueOf <Document, string>(d => d.Attachment.Keywords);
                document.Attachment.Language      = hit.Fields.ValueOf <Document, string>(d => d.Attachment.Language);
                document.Attachment.Title         = hit.Fields.ValueOf <Document, string>(d => d.Attachment.Title);
                documents.Add(document);
            }

            documents.Should().NotBeEmpty();
            documents.Count.Should().Be(1);

            var firstDocument = documents[0];

            // This is the only metadata that can be extracted from the sample doc
            firstDocument.Attachment.Title.Should().Be("Attachment Test Document");
            firstDocument.Attachment.ContentType.Should().Be("application/pdf");
            firstDocument.Attachment.Author.Should().Be("Russ Cam");
            firstDocument.Attachment.Keywords.Should().Be("nest,test,document");
            firstDocument.Attachment.Date.Should().Be(new DateTime(2016, 12, 08, 3, 5, 13, DateTimeKind.Utc));
            firstDocument.Attachment.ContentLength.Should().Be(315745);
            firstDocument.Attachment.Content.Should().Contain("mapper-attachment support");
            firstDocument.Attachment.Language.Should().Be("fr");
        }
コード例 #6
0
        public T Save(T data, Refresh refresh = Refresh.WaitFor)
        {
            IIndexResponse response = Client.Index(data, idx => idx.Index(DefaultIndex).Refresh(refresh));

            if (!response.IsValid)
            {
                throw new InvalidOperationException(response.ServerError.ToString());
            }
            return(data);
        }
コード例 #7
0
        private static IIndexResponse Index_InlineFunc(ElasticClient client, Album album)
        {
            album.Rank = 5;     // establish our ID

            IIndexResponse response = client.Index(album, i => i
                                                   .Index("rolling-stone-500")
                                                   //.Id(5)
                                                   );

            return(response);
        }
コード例 #8
0
        private static void Index_IIndexRequest(ElasticClient client, Album album)
        {
            album.Rank = 3;     // establish our ID

            IIndexRequest <Album> req = new IndexRequest <Album>(album);

            req.Index = "rolling-stone-500";
            //req.Id = "59";

            IIndexResponse response1 = client.Index(req);
        }
コード例 #9
0
        /// <summary>
        /// 添加一个文档到索引中
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="entity"></param>
        /// <param name="indexName"></param>
        /// <returns></returns>
        public virtual async Task <bool> AddAsync <TEntity>(TEntity entity, string indexName) where TEntity : class
        {
            IIndexResponse response = await Context.IndexAsync(entity, f => f.Index(indexName));

            if (!response.IsValid)
            {
                Logger.LogError($"[Success:{response.ApiCall.Success}]\t{response.ApiCall.Uri}");
                Logger.LogError(response.ApiCall.DebugInformation);
                Logger.LogError(response.ApiCall.OriginalException?.Message);
            }
            return(response.ApiCall.Success);
        }
コード例 #10
0
        public async Task <IndexResponseDTO> IndexAsync(string indexName, T model)
        {
            IIndexResponse response = await elasticClient.IndexAsync(model, i => i
                                                                     .Index(indexName)
                                                                     .Type <T>());

            return(new IndexResponseDTO()
            {
                IsValid = response.IsValid,
                StatusMessage = response.DebugInformation,
                Exception = response.OriginalException
            });
        }
コード例 #11
0
        private static void Index_IndexDescriptorFunc(ElasticClient client, Album album)
        {
            album.Rank = 4;     // establish our ID

            Func <IndexDescriptor <Album>, IndexDescriptor <Album> > fun = (i) =>
            {
                return(i
                       .Index("rolling-stone-500")
                       //.Id(4)
                       );
            };

            IIndexResponse response2 = client.Index(album, fun);
        }
コード例 #12
0
        private static object GetJsonModel(IIndexResponse response, Projectmaster model)
        {
            var result = new
            {
                props = new {
                    model.projectname,
                    model.NatureofIndustry,
                    model.projectcode
                },
                msg = response.Result
            };

            return(result);
        }
コード例 #13
0
 public static MvcHtmlString ErrorMessageFor(this HtmlHelper helper, IIndexResponse esResponse)
 {
     if (esResponse != null && !esResponse.Created)
     {
         return esResponse.ServerError != null ? 
             new MvcHtmlString("There was a problem adding your watch request: " + esResponse.ServerError.Error) : 
             new MvcHtmlString("There was a problem adding your watch request");
     }
     if (esResponse != null && esResponse.Created)
     {
         return new MvcHtmlString("Thanks, we'll notify you when you can apply for seats on this flight :)");
     }
     return new MvcHtmlString("");
 }
コード例 #14
0
        private bool Index(IEvent evnt, string indexName)
        {
            string ttl           = configuration.TTL[evnt.Type];
            var    logStashEvent = new LogStashEvent(evnt)
            {
                TTL = ttl
            };

            IIndexResponse result = client.Index(logStashEvent, indexName, evnt.Type);

            if (!result.OK)
            {
                logger.Error(string.Format("Failed to index: '{0}'. Result: '{1}'. Retrying...", evnt, result.ConnectionStatus.Result));
            }

            return(result.OK);
        }
        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));
        }
コード例 #16
0
        protected override void ExpectResponse(IIndexResponse response)
        {
            response.ShouldBeValid();

            // search on attachment name
            var searchResponse = Client.Search <Document>(s => s
                                                          .Index(CallIsolatedValue)
                                                          .Query(q => q
                                                                 .Match(m => m
                                                                        .Field(a => a.Attachment.Name)
                                                                        .Query("name")
                                                                        )
                                                                 )
                                                          );

            searchResponse.ShouldBeValid();
            searchResponse.Documents.Count().Should().Be(1);

            // search on content type
            searchResponse = Client.Search <Document>(s => s
                                                      .Index(CallIsolatedValue)
                                                      .Query(q => q
                                                             .Match(m => m
                                                                    .Field(a => a.Attachment.ContentType)
                                                                    .Query("pdf")
                                                                    )
                                                             )
                                                      );

            searchResponse.ShouldBeValid();
            searchResponse.Documents.Count().Should().Be(1);

            // search on language
            searchResponse = Client.Search <Document>(s => s
                                                      .Index(CallIsolatedValue)
                                                      .Query(q => q
                                                             .Match(m => m
                                                                    .Field(a => a.Attachment.Language)
                                                                    .Query("en")
                                                                    )
                                                             )
                                                      );

            searchResponse.ShouldBeValid();
            searchResponse.Documents.Count().Should().Be(1);
        }
コード例 #17
0
        protected override void ExpectResponse(IIndexResponse response)
        {
            response.ShouldBeValid();

            var searchResponse = Client.Search <Document>(s => s
                                                          .Index(CallIsolatedValue)
                                                          .Query(q => q
                                                                 .Match(m => m
                                                                        .Field(a => a.Attachment.Content)
                                                                        .Query("NEST mapper")
                                                                        )
                                                                 )
                                                          );

            searchResponse.ShouldBeValid();
            searchResponse.Documents.Count().Should().Be(1);
        }
コード例 #18
0
        protected override void ExpectResponse(IIndexResponse response)
        {
            response.ShouldBeValid();

            // search on language (document is detected as French)
            var searchResponse = Client.Search <Document>(s => s
                                                          .Index(CallIsolatedValue)
                                                          .Query(q => q
                                                                 .Match(m => m
                                                                        .Field(a => a.Attachment.Language)
                                                                        .Query("fr")
                                                                        )
                                                                 )
                                                          );

            searchResponse.ShouldBeValid();
            searchResponse.Documents.Count().Should().Be(1);
        }
コード例 #19
0
        protected override void ExpectResponse(IIndexResponse response)
        {
            response.IsValid.Should().BeTrue();

            var getResponse = this.Client.Get <IngestedAttachment>(response.Id, g => g.Index(CallIsolatedValue));

            getResponse.IsValid.Should().BeTrue();
            getResponse.Source.Should().NotBeNull();

            getResponse.Source.Attachment.Should().NotBeNull();

            var attachment = getResponse.Source.Attachment;

            attachment.Date.Should().Be(new DateTime(2016, 02, 21, 5, 47, 36, DateTimeKind.Utc));
            attachment.ContentType.Should().Be("application/pdf");
            attachment.Author.Should().Be("Russ Cam");
            attachment.Language.Should().Be("fr");
            attachment.ContentLength.Should().Be(93);
            attachment.Content.Should().Contain("mapper-attachment support");
        }
コード例 #20
0
        public void AddToIndex(String productName)
        {
            if (String.IsNullOrEmpty(productName))
            {
                throw new ArgumentNullException(nameof(productName));
            }

            var            jsonForAdd    = new { str = productName };
            IIndexResponse indexResponse = _client.Index(jsonForAdd, i => i
                                                         .Index(IndexName)
                                                         .Type(TypeName)
                                                         .Id(Guid.NewGuid())
                                                         .Refresh(null)
                                                         );

            if (!indexResponse.IsValid)
            {
                throw indexResponse.OriginalException;
            }
        }
コード例 #21
0
        protected override void ExpectResponse(IIndexResponse response)
        {
            response.ShouldBeValid();

            var getResponse = Client.Get <Project>(response.Id, g => g.Routing(CallIsolatedValue));

            getResponse.ShouldBeValid();
            getResponse.Source.Should().NotBeNull();
            getResponse.Source.LeadDeveloper.Should().NotBeNull();

            var geoIp = getResponse.Source.LeadDeveloper.GeoIp;

            geoIp.Should().NotBeNull();
            geoIp.ContinentName.Should().Be("Europe");
            geoIp.CityName.Should().Be("Reykjavik");
            geoIp.CountryIsoCode.Should().Be("IS");
            geoIp.RegionName.Should().Be("Capital Region");
            geoIp.Location.Should().NotBeNull();
            geoIp.Location.Latitude.Should().Be(64.1383);
            geoIp.Location.Longitude.Should().Be(-21.8959);
        }
コード例 #22
0
        protected override void ExpectResponse(IIndexResponse response)
        {
            response.ShouldBeValid();

            var getResponse = this.Client.Get <IngestedAttachment>(response.Id, g => g.Index(CallIsolatedValue));

            getResponse.ShouldBeValid();
            getResponse.Source.Should().NotBeNull();

            getResponse.Source.Attachment.Should().NotBeNull();

            var attachment = getResponse.Source.Attachment;

            attachment.Title.Should().Be("Attachment Test Document");
            attachment.Keywords.Should().Be("nest,test,document");
            attachment.Date.Should().Be(new DateTime(2016, 12, 08, 3, 5, 13, DateTimeKind.Utc));
            attachment.ContentType.Should().Be("application/pdf");
            attachment.Author.Should().Be("Russ Cam");
            attachment.Language.Should().Be("fr");
            attachment.ContentLength.Should().Be(96);
            attachment.Content.Should().Contain("mapper-attachment support");
        }
コード例 #23
0
        private static void ExamineResponse(IIndexResponse response)
        {
            Console.WriteLine("_index: {0}", response.Index);
            Console.WriteLine("_type: {0}", response.Type);
            Console.WriteLine("_id: {0}", response.Id);
            Console.WriteLine("_version: {0}", response.Version);
            Console.WriteLine("created: {0}", response.Created);

            Console.WriteLine();
            Console.WriteLine("REQ Body: ");
            Console.WriteLine(Encoding.UTF8.GetString(response.ConnectionStatus.Request));
            Console.WriteLine();

            Console.WriteLine("RESP Body: ");
            Console.WriteLine(Encoding.UTF8.GetString(response.ConnectionStatus.ResponseRaw));
            Console.WriteLine();

            //Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings() {
            //    ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
            //};
            //Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(response, settings));
        }
コード例 #24
0
        public static IIndexResponse IndexAlbum(string url)
        {
            var uri    = new Uri(url);
            var config = new ConnectionSettings(uri);

            config.ExposeRawResponse(true);

            var   client = new ElasticClient(config);
            Album album  = Album.ChronicleV1;

            // approach 1
            Index_IIndexRequest(client, album);

            // approach 2
            Index_IndexDescriptorFunc(client, album);

            // approach 3
            IIndexResponse response = Index_InlineFunc(client, album);

            ExamineResponse(response);

            return(response);
        }
コード例 #25
0
        public async Task <DataAccessResponse <string> > Add(Friend friend)
        {
            DataAccessResponse <string> response = new DataAccessResponse <string>();

            if (friend == null)
            {
                return(response.NotFound());
            }

            if (friend.PurchasedItems != null)
            {
                friend.PurchasedItems.ForEach(p => p.Id = Guid.NewGuid());
            }

            IIndexResponse indexResponse = await _esClient.IndexAsync <Friend>(friend, d => d.Index(Index).Type(Type));

            if (!indexResponse.IsValid)
            {
                return(response.InternalServerError());
            }

            return(response.Created(indexResponse.Id));
        }
コード例 #26
0
        public void Handle(string jsonString)
        {
            LogEntity logEntity = null;

            try
            {
                logEntity = DataConverter.FromJson <LogEntity>(jsonString);
            }
            catch (Exception ex)
            {
                logEntity = new LogEntity()
                {
                    Exception = ex, Message = jsonString, DateTime = DateTime.Now
                };
            }

            if (logEntity == null)
            {
                logEntity = new LogEntity()
                {
                    Message = jsonString, DateTime = DateTime.Now
                };
            }

            IIndexResponse indexResponse = _elasticClient.Index(logEntity, idx => idx.Index(_options.LogEventName.ToLower(GlobalSettings.Culture)));

            if (indexResponse != null)
            {
                _logger.LogDebug(indexResponse.DebugInformation);

                if (!indexResponse.IsValid)
                {
                    _logger.LogError(indexResponse.DebugInformation);
                }
            }
        }
コード例 #27
0
 /// <summary>
 /// 新增一条文档
 /// </summary>
 /// <typeparam name="T">文档类型</typeparam>
 /// <param name="model">文档实体</param>
 /// <param name="index">文档所在库</param>
 /// <returns>返回true false</returns>
 public bool Index <T>(T model, string index = null) where T : class => HandleResponseResult(() =>
 {
     IIndexResponse response = _builder?.Client?.Index(model, x => x.Type(typeof(T).SearchName()).Index(index ?? _defaultIndex));
     return(response);
 });
コード例 #28
0
ファイル: IndexerBase.cs プロジェクト: zacharyk-suzy/stencil
 public virtual IndexResult UpdateDocument(TModel model)
 {
     return(base.ExecuteFunctionWrite("UpdateDocument", delegate()
     {
         try
         {
             Exception exception = null;
             string error = "invalid";
             // try twice
             for (int i = 0; i < 2; i++)
             {
                 try
                 {
                     exception = null;
                     ElasticClient client = this.ClientFactory.CreateClient();
                     IndexRequest <TModel> request = new IndexRequest <TModel>(this.ClientFactory.IndexName, this.DocumentType, this.GetModelId(model));
                     request.Document = model;
                     IIndexResponse result = client.Index(request);
                     if (!result.IsValid)
                     {
                         HealthReporter.Current.UpdateMetric(HealthTrackType.Each, string.Format(HealthReporter.INDEXER_INSTANT_FAIL_SOFT_FORMAT, typeof(TModel).FriendlyName()), 0, 1);
                         if (result.ServerError != null && result.ServerError.Error != null && !string.IsNullOrEmpty(result.ServerError.Error.Reason))
                         {
                             error = result.ServerError.Error.Reason;
                         }
                         // allow it to try again
                     }
                     else
                     {
                         return new IndexResult()
                         {
                             success = true,
                             version = result.Version.ToString(),
                             created = result.Created,
                             attempts = i + 1
                         };
                     }
                 }
                 catch (Exception ex)
                 {
                     exception = ex;
                 }
             }
             if (exception != null)
             {
                 throw exception;
             }
             return new IndexResult()
             {
                 success = false,
                 error = error
             };
         }
         catch (Exception ex)
         {
             this.IFoundation.LogError(ex, "UpdateDocument");
             HealthReporter.Current.UpdateMetric(HealthTrackType.Each, string.Format(HealthReporter.INDEXER_INSTANT_FAIL_TIMEOUT_FORMAT, typeof(TModel).FriendlyName()), 0, 1);
             return new IndexResult()
             {
                 success = false,
                 error = ex.Message
             };
         }
     }));
 }
コード例 #29
0
 public static ElasticIndexResponse SuccessResponse(IIndexResponse response)
 {
     return(new ElasticIndexResponse {
         Success = true, Response = response
     });
 }
コード例 #30
0
 public IndexResponse( IIndexResponse<UUIDResult> response )
 {
     FacetQueriesResult = response.FacetResult.FacetQueriesResult.Select( result => new FacetsResult( result ) );
     FacetFieldsResult  = response.FacetResult.FacetFieldsResult.Select( result => new FacetsResult( result ) );
 }
コード例 #31
0
 /// <summary>
 /// Creates a new document in the provided ElasticSearch index.
 /// </summary>
 /// <param name="document">The document.</param>
 /// <param name="indexName">The name of the index.</param>
 public void Create(DocumentEntity document, string indexName)
 {
     IIndexResponse indexResponse = elasticClient
                                    .Index(document, i => i.Index(indexName));
 }
コード例 #32
0
        static void Main(string[] args)
        {
            var    local     = new Uri("http://localhost:9200");
            string indexName = "blog_post_author_index";
            var    settings  = new ConnectionSettings(local).DefaultIndex(indexName);
            var    elastic   = new ElasticClient(settings);

            var res = elastic.ClusterHealth();

            Console.WriteLine(res.Status);

            var blogPost = new BlogPost
            {
                Id    = Guid.NewGuid(),
                Title = "First blog post",
                Body  = "This is very long blog post!"
            };

            if (!elastic.IndexExists(indexName).Exists)
            {
                var createIndexResponse = elastic.CreateIndex(indexName);
                var mappingBlogPost     = elastic.Map <BlogPost>(s => s.AutoMap());
                var mappingBlogAuthor   = elastic.Map <Author>(s => s.AutoMap());
                Console.WriteLine("createIndexResponse=" + createIndexResponse.IsValid);
                Console.WriteLine("mappingBlogPost=" + mappingBlogPost.IsValid);
                Console.WriteLine("mappingBlogAuthor=" + mappingBlogAuthor.IsValid);
            }

            IIndexResponse indexResponse = elastic.Index(blogPost, i => i
                                                         .Index(indexName)
                                                         .Type(typeof(BlogPost))
                                                         .Id(1)
                                                         .Refresh());

            Console.WriteLine("IIndexResponse=" + indexResponse.IsValid);


            //insert 10 documents
            for (var i = 2; i < 12; i++)
            {
                var blogPostNew = new BlogPost
                {
                    Id    = Guid.NewGuid(),
                    Title = string.Format("title {0:000}", i),
                    Body  = string.Format("This is {0:000} very long blog post!", i)
                };
                IIndexResponse bulkIndexReponse = elastic.Index(blogPostNew, p => p
                                                                .Type(typeof(BlogPost))
                                                                .Id(i)
                                                                .Refresh());
                Console.WriteLine("bulk IIndexResponse=" + bulkIndexReponse.IsValid);
            }

            //Get document by id
            var result = elastic.Get <BlogPost>(new GetRequest(indexName, typeof(BlogPost), 16));

            Console.WriteLine("Document id:" + result.Id);
            Console.WriteLine("Document fields:" + result.Fields);
            Console.WriteLine("Document Type:" + result.Type);
            Console.WriteLine("Document Found Status:" + result.Found);

            //delete document by id
            //var deleteResult = elastic.Delete(new DeleteRequest(indexName, typeof(BlogPost), 1));
            //Console.WriteLine(deleteResult.Found);

            //Query search queries for match all
            var searchResult = elastic.Search <BlogPost>(sr => sr
                                                         .From(0)
                                                         .Size(5)
                                                         .Query(q => q.MatchAll())
                                                         .Sort(ss => ss
                                                               .Ascending(p => p.Title)
                                                               .Field(f => f.Field(ff => ff.Title)))
                                                         );

            Console.WriteLine("Search results for Match All!! ==>");
            Console.WriteLine(searchResult.Hits.Count());
            foreach (var hit in searchResult.Hits)
            {
                Console.WriteLine(hit.Source);
            }

            //Query search results using Match
            var blogPostsForSearch = new[]
            {
                new BlogPost {
                    Id    = Guid.NewGuid(),
                    Title = "test post 123",
                    Body  = "1"
                },
                new BlogPost
                {
                    Id    = Guid.NewGuid(),
                    Title = "test something 123",
                    Body  = "2"
                },
                new BlogPost
                {
                    Id    = Guid.NewGuid(),
                    Title = "read this post",
                    Body  = "3"
                }
            };
            var id = 15;

            foreach (var blogPostSearch in blogPostsForSearch)
            {
                var insertRes = elastic.Index(blogPostSearch, p => p
                                              .Id(++id)
                                              .Refresh());
                Console.WriteLine("Match SearchResults IIndexResponse=" + insertRes.IsValid);
            }

            var searchMatch = elastic.Search <BlogPost>(es => es
                                                        .Query(q => q
                                                               .Match(m => m
                                                                      .Field(f => f.Title)
                                                                      .Query("test post 123"))));

            Console.WriteLine("Search results for Match!! ==>");
            Console.WriteLine(searchMatch.Hits.Count());
            foreach (var hit in searchMatch.Hits)
            {
                Console.WriteLine(hit.Source);
            }

            //Match with AND Operator
            var searchMatchAnd = elastic.Search <BlogPost>(es => es
                                                           .Query(q => q
                                                                  .Match(m => m
                                                                         .Field(f => f.Title)
                                                                         .Query("test post 123")
                                                                         .Operator(Operator.And))));

            Console.WriteLine("Search results for Match!! ==>");
            Console.WriteLine(searchMatchAnd.Hits.Count());
            foreach (var hit in searchMatchAnd.Hits)
            {
                Console.WriteLine(hit.Source);
            }

            //MinimumShouldMatch
            var searchMinMatch = elastic.Search <BlogPost>(es => es
                                                           .Query(q => q
                                                                  .Match(m => m
                                                                         .Field(f => f.Title)
                                                                         .Query("test post 123")
                                                                         .Operator(Operator.Or)
                                                                         .MinimumShouldMatch(2))));

            Console.WriteLine("Search results for Min Match!! ==>");
            Console.WriteLine(searchMinMatch.Hits.Count());
            foreach (var hit in searchMinMatch.Hits)
            {
                Console.WriteLine(hit.Source);
            }

            //Bool Query
            var boolQuerySearchResult = elastic.Search <BlogPost>(es => es
                                                                  .Query(qu => qu
                                                                         .Bool(b => b
                                                                               .Must(m =>
                                                                                     m.Match(mt => mt.Field(f => f.Title).Query("title")) &&
                                                                                     m.Match(mt2 => mt2.Field(f => f.Body).Query("002")))))
                                                                  .Sort(so => so.Field(fe => fe.Field(fe1 => fe1.Title))
                                                                        .Ascending(p => p.Title)));

            Console.WriteLine("Search results for Bool with Must!! ==>");
            Console.WriteLine(boolQuerySearchResult.Hits.Count());
            foreach (var hit in boolQuerySearchResult.Hits)
            {
                Console.WriteLine(hit.Source);
            }

            //Using replacing Must with should (or)
            var boolQuerySearchResultShould = elastic.Search <BlogPost>(es => es
                                                                        .Query(qu => qu
                                                                               .Bool(b => b
                                                                                     .Should(m =>
                                                                                             m.Match(mt => mt.Field(f => f.Title).Query("title")) ||
                                                                                             m.Match(mt2 => mt2.Field(f => f.Body).Query("002")))))
                                                                        .Sort(so => so.Field(fe => fe.Field(fe1 => fe1.Title))
                                                                              .Ascending(p => p.Title)));

            Console.WriteLine("Search results for Bool with Should!! ==>");
            Console.WriteLine(boolQuerySearchResultShould.Hits.Count());
            foreach (var hit in boolQuerySearchResultShould.Hits)
            {
                Console.WriteLine(hit.Source);
            }

            //Using bool with MUST NOT
            var boolQuerySearchResultMustNot = elastic.Search <BlogPost>(es => es
                                                                         .Query(qu => qu
                                                                                .Bool(b => b
                                                                                      .Should(m =>
                                                                                              m.Match(mt => mt.Field(f => f.Title).Query("title")) ||
                                                                                              m.Match(mt2 => mt2.Field(f => f.Body).Query("002")))
                                                                                      .Must(ms => ms
                                                                                            .Match(mt3 => mt3.Field(fi => fi.Body).Query("this")))
                                                                                      .MustNot(mn => mn
                                                                                               .Match(mt4 => mt4.Field(fi => fi.Body).Query("003")))))
                                                                         .Sort(so => so.Field(fe => fe.Field(fe1 => fe1.Title))
                                                                               .Ascending(p => p.Title)));

            Console.WriteLine("Search results for Bool with MUST NOT!! ==>");
            Console.WriteLine(boolQuerySearchResultMustNot.Hits.Count());
            foreach (var hit in boolQuerySearchResultMustNot.Hits)
            {
                Console.WriteLine(hit.Source);
            }

            //Using the above query with bitwise operator
            var boolQuerySearchResultBitwise = elastic.Search <BlogPost>(es => es
                                                                         .Query(q =>
                                                                                (q.Match(mt1 => mt1.Field(f1 => f1.Title).Query("title")) ||
                                                                                 q.Match(mt2 => mt2.Field(f2 => f2.Body).Query("002"))) &&
                                                                                (q.Match(mt3 => mt3.Field(fe3 => fe3.Body).Query("this"))) &&
                                                                                (!q.Match(mt4 => mt4.Field(fe4 => fe4.Body).Query("003")))));

            Console.WriteLine("Search results for Bool with Bitwise operator!! ==>");
            Console.WriteLine(boolQuerySearchResultBitwise.Hits.Count());
            foreach (var hit in boolQuerySearchResultBitwise.Hits)
            {
                Console.WriteLine(hit.Source);
            }
            //Nested Types and Nested Query
            Console.WriteLine("*******Nested Types and Nested Query*************");

            var authors = new[]
            {
                new Author {
                    Id = Guid.NewGuid(), FirstName = "John", LastName = "Doe"
                },
                new Author {
                    Id = Guid.NewGuid(), FirstName = "Notjohn", LastName = "Doe"
                },
                new Author {
                    Id = Guid.NewGuid(), FirstName = "John", LastName = "Notdoe"
                }
            };

            foreach (var author in authors)
            {
                IIndexResponse indexResponse2 = elastic.Index(author, i => i
                                                              .Index(indexName)
                                                              .Type(typeof(Author))
                                                              .Id(Guid.NewGuid())
                                                              .Refresh());
                Console.WriteLine("IIndexResponse=" + indexResponse2.IsValid);
            }


            Console.WriteLine("IIndexResponse=" + indexResponse.IsValid);

            var blogPostWithAuthor = new[]
            {
                new BlogPost {
                    Id = Guid.NewGuid(), Title = "test post 1", Body = "1", Author = authors[0]
                },
                new BlogPost {
                    Id = Guid.NewGuid(), Title = "test post 2", Body = "2", Author = authors[1]
                },
                new BlogPost {
                    Id = Guid.NewGuid(), Title = "test post 3", Body = "3", Author = authors[2]
                }
            };



            foreach (var blogPostAuthor in blogPostWithAuthor)
            {
                var resindex = elastic.Index(blogPostAuthor, p => p
                                             .Id(blogPostAuthor.Id.ToString())
                                             .Refresh());
                Console.WriteLine("Match SearchResults IIndexResponse=" + resindex.IsValid);
            }

            Console.WriteLine("*******Nested Query*************");
            var nestedQuery = elastic.Search <BlogPost>(es => es
                                                        .Query(q => q
                                                               .Nested(n => n
                                                                       .Path(b => b.Author)
                                                                       .Query(nq =>
                                                                              nq.Match(m1 => m1.Field(f1 => f1.Author.FirstName).Query("John")) &&
                                                                              nq.Match(m2 => m2.Field(f2 => f2.Author.LastName).Query("Notdoe"))))
                                                               ));

            Console.WriteLine(nestedQuery.IsValid);
            Console.WriteLine(nestedQuery.Hits.Count());
            foreach (var hit in nestedQuery.Hits)
            {
                Console.WriteLine(hit.Source);
            }
            Console.ReadLine();
        }