public async Task<IEnumerable<Message>> Get(string q, int from, int size)
        {
            var url = ConfigurationManager.AppSettings["ES_URL"];
            var setting = new ConnectionSettings(new Uri(url));
            var client = new ElasticClient(setting);

            // Parse the search query
            string[] terms = q.Split(' ');
            var personTerm = terms.SingleOrDefault(x => x.StartsWith("person:"));
            if (!string.IsNullOrEmpty(personTerm))
            {
                terms = terms.Except(new string[] { personTerm }).ToArray();
                personTerm = personTerm.Replace("person:", string.Empty);
            }
            var textTerms = string.Join(" ", terms);

            var searchResults = await client.SearchAsync<Message>(s => s
                .AllIndices()
                .AllTypes()
                .Size(size)
                .From(from)
                .SortAscending(f => f.Date)
                .Query(qry =>
                    (qry.Term("from", personTerm) ||
                    qry.Term("to", personTerm)) &&
                    qry.Match(m => m
                        .OnField(f => f.Text)
                        .Query(textTerms)
                        .Operator(Operator.And))));

            return searchResults.Documents;
        }
Exemple #2
0
        public void SearchUsingSingleClient(string indexName, int port, int numberOfSearches)
        {
            var settings = this.CreateSettings(indexName, port);
            var client = new ElasticClient(settings);

            var tasks = new List<Task>();
            for (var p = 0; p < numberOfSearches; p++)
            {
                var t = client.SearchAsync<Message>(s => s.MatchAll())
                    .ContinueWith(ta =>
                    {
                        if (!ta.Result.IsValid)
                            throw new ApplicationException(ta.Result.ConnectionStatus.ToString());
                    });
                tasks.Add(t);
            }
            Task.WaitAll(tasks.ToArray());
        }
        public async Task <IReadOnlyCollection <T> > FetchQuotes <T>(string Symbol, DateTime Start, DateTime End) where T : class, IDataRow, new()
        {
            List <T> documents = new List <T>();

            var search = await _client.SearchAsync <T>(s => s
                                                       .AllTypes()
                                                       .From(0)
                                                       .Size(10000)
                                                       .Query(q => q
                                                              .Match(m => m
                                                                     .Field(new Field("baseSymbol"))
                                                                     .Query(Symbol)
                                                                     ) && q
                                                              .DateRange(r => r
                                                                         .Field(f => f.date)
                                                                         .GreaterThanOrEquals(Start)
                                                                         .LessThanOrEquals(End)
                                                                         )
                                                              )
                                                       .Scroll(100)
                                                       );

            //first page
            string scrollId = search.ScrollId;

            documents.AddRange(search.Documents);

            ISearchResponse <T> results;

            do
            {
                //page until we get all the results
                results = await _client.ScrollAsync <T>(100, scrollId);

                scrollId = results.ScrollId;
                documents.AddRange(results.Documents);
            } while (results.Documents.Count == 10000);

            this.Log("Retrieved {0} document objects.", documents.Count);

            return(documents);
        }
        /** 
	     * An example of using `OnRequestCompleted()` for complex logging. Remember, if you would also like 
         * to capture the request and/or response bytes, you also need to set `.DisableDirectStreaming()`
         * to `true`
		*/
        [U]public async Task UsingOnRequestCompletedForLogging()
		{
		    var list = new List<string>();
			var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
			var settings = new ConnectionSettings(connectionPool, new InMemoryConnection())
                .DisableDirectStreaming()
				.OnRequestCompleted(response =>
				{
                    // log out the request
                    if (response.RequestBodyInBytes != null)
                    {
                        list.Add(
                            $"{response.HttpMethod} {response.Uri} \n" +
                            $"{Encoding.UTF8.GetString(response.RequestBodyInBytes)}");
                    }
                    else
                    {
                        list.Add($"{response.HttpMethod} {response.Uri}");
                    }

                    // log out the response
                    if (response.ResponseBodyInBytes != null)
                    {
                        list.Add($"Status: {response.HttpStatusCode}\n" +
                                 $"{Encoding.UTF8.GetString(response.ResponseBodyInBytes)}\n" +
                                 $"{new string('-', 30)}\n");
                    }
                    else
                    {
                        list.Add($"Status: {response.HttpStatusCode}\n" +
                                 $"{new string('-', 30)}\n");
                    }
                });

			var client = new ElasticClient(settings);

            var syncResponse = client.Search<object>(s => s
                .Scroll("2m")
                .Sort(ss => ss
                    .Ascending(SortSpecialField.DocumentIndexOrder)
                )
            );

            list.Count.Should().Be(2);

            var asyncResponse = await client.SearchAsync<object>(s => s
                .Scroll("2m")
                .Sort(ss => ss
                    .Ascending(SortSpecialField.DocumentIndexOrder)
                )
            );

            list.Count.Should().Be(4);
            list.ShouldAllBeEquivalentTo(new []
            {
                "POST http://localhost:9200/_search?scroll=2m \n{\"sort\":[{\"_doc\":{\"order\":\"asc\"}}]}",
                "Status: 200\n------------------------------\n",
                "POST http://localhost:9200/_search?scroll=2m \n{\"sort\":[{\"_doc\":{\"order\":\"asc\"}}]}",
                "Status: 200\n------------------------------\n"
            });
        }