コード例 #1
0
        public void SimpleTermFacetWithExclude()
        {
            IQueryResponse <ElasticsearchProject> queryResults = this.SearchRaw <ElasticsearchProject>(
                @" { ""query"" : {
							""match_all"" : { }
					},
					""facets"" : {
					  ""followerLastName"" : { ""terms"" : {
						""field"" : ""followers.lastName""
						, exclude : ["""                         +
                this._LookFor + @"""]
					  } }
					}
				}"
                );

            var facet = queryResults.Facets["followerLastName"];

            this.TestDefaultAssertions(queryResults);

            Assert.IsInstanceOf <TermFacet>(facet);

            var tf = (TermFacet)facet;

            Assert.IsFalse(tf.Items.Any(f => f.Term == this._LookFor));
        }
コード例 #2
0
        public async Task ExecuteAsync(IQueryResponse <List <DeveloperDto> > queryResponse)
        {
            await _auditService.LogAccess(nameof(GetAllDevelopersQuery));

            var developers = await _dbContext
                             .GetAllQuery <Developer>()
                             .Include(d => d.PrimaryLanguage)
                             .ToListAsync();

            var response = developers
                           .Select(d =>
                                   new DeveloperDto()
            {
                DeveloperId       = d.DeveloperId,
                FirstName         = d.FirstName,
                LastName          = d.LastName,
                Gender            = Enum.GetName(typeof(Gender), d.Gender),
                Level             = Enum.GetName(typeof(AbilitonLevel), d.Level),
                PrimaryLanguage   = d.PrimaryLanguage.Name,
                YearsOfExperience = d.YearsOfExperience
            })
                           .ToList();

            queryResponse.Respond(response);
        }
コード例 #3
0
        public IBulkResponse IndexSearchResults(IQueryResponse <T> searchResult, IObserver <IReindexResponse <T> > observer, string toIndex, int page)
        {
            if (!searchResult.IsValid)
            {
                throw new ReindexException(searchResult.ConnectionStatus, "reindex failed on scroll #" + page);
            }

            var bb = new BulkDescriptor();

            foreach (var d in searchResult.Hits)
            {
                IHit <T> d1 = d;
                bb.Index <T>(bi => bi.Object(d1.Source).Type(d1.Type).Index(toIndex).Id(d.Id));
            }

            var indexResult = this.CurrentClient.Bulk(b => bb);

            if (!indexResult.IsValid)
            {
                throw new ReindexException(indexResult.ConnectionStatus, "reindex failed when indexing page " + page);
            }

            observer.OnNext(new ReindexResponse <T>()
            {
                BulkResponse  = indexResult,
                QueryResponse = searchResult,
                Scroll        = page
            });
            return(indexResult);
        }
コード例 #4
0
        private static IQueryResponse <Dictionary <string, object> > ApplySecurity(IQueryResponse <Dictionary <string, object> > queryResults, SearchSecurityOptions options, ref int resultsTotal)
        {
            if (!options.HasFlag(SearchSecurityOptions.DisableSecurityCheck))
            {
                var hitsToRemove = new HashSet <IHit <Dictionary <string, object> > >();
                foreach (var hit in from searchResult in queryResults.Hits.Hits
                         where searchResult != null
                         select searchResult)
                {
                    object uniqueId;
                    if (!hit.Source.TryGetValue("_uniqueid", out uniqueId))                     //TODO: shouldn't have to use the Source property here, the Fields property should be populated. probably something wrong with field mapping.
                    {
                        continue;
                    }

                    object datasource;
                    hit.Source.TryGetValue("_datasource", out datasource);                     //TODO: shouldn't have to use the Source property here, the Fields property should be populated. probably something wrong with field mapping.
                    if (!OutboundIndexFilterPipeline.CheckItemSecurity(new OutboundIndexFilterArgs((string)uniqueId, (string)datasource)))
                    {
                        continue;
                    }

                    hitsToRemove.Add(hit);
                }

                foreach (var hit in hitsToRemove)
                {
                    queryResults.Hits.Hits.Remove(hit);
                    resultsTotal--;
                }
            }
            return(queryResults);
        }
コード例 #5
0
        private void RefreshWithGameServerStatus(IQueryResponse queryResponse)
        {
            var newPlayers = new List <IGameServerPlayer>();

            foreach (var queryPlayer in queryResponse.Players)
            {
                if (string.IsNullOrWhiteSpace(queryPlayer.NormalizedName))
                {
                    continue;
                }

                var newPlayer = new GameServerPlayer(queryPlayer);

                var existing = (GameServerPlayer)Players.SingleOrDefault(player => player.NormalizedName == queryPlayer.NormalizedName);

                if (existing != null)
                {
                    newPlayer.RconPlayer = existing.RconPlayer;
                }

                newPlayers.Add(newPlayer);
            }

            Players = newPlayers;
        }
コード例 #6
0
        /// <summary>
        /// Executes the specified query.
        /// </summary>
        /// <typeparam name="TQuery">The query type.</typeparam>
        /// <returns>The query result.</returns>
        public TQuery Query <TQuery>() where TQuery : class, IQueryResponse
        {
            IQueryResponse result = null;

            try
            {
                this.log.DebugFormat("Attempting to retrieve query of type '{0}'.", typeof(TQuery).FullName);

                var queryType = typeof(TQuery).ToString();

                try
                {
                    result = this.queryChannel.DirectQuery(queryType, null);
                }
                catch (Exception e)
                {
                    this.log.Error($"An error occurred while trying to query type '{typeof(TQuery).FullName}'.", e);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            return(result as TQuery);
        }
コード例 #7
0
        public void SimpleTermFacetWithGlobal()
        {
            this.ResetIndexes();
            IQueryResponse <ElasticSearchProject> queryResults = this.ConnectedClient.SearchRaw <ElasticSearchProject>(
                @" { ""query"" : {
							""term"" : { ""followers.lastName"" : """                             + this._LookFor.ToLower() +
                @""" }
					},
					""facets"" : {
					  ""followerLastName"" : { 
						""terms"" : {""field"" : ""followers.lastName""} },
						""global"" : true
					}
				}"                );

            var facet = queryResults.Facets["followerLastName"];

            this.TestDefaultAssertions(queryResults);

            Assert.IsInstanceOf <TermFacet>(facet);

            var tf = (TermFacet)facet;

            Assert.IsTrue(tf.Items.Any(f => f.Term == this._LookFor.ToLower()));
        }
コード例 #8
0
        /// <summary>
        /// Determine if the handler can handle the specified message given the specified query.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="query">The query.</param>
        /// <returns><c>true</c>, if the handler can handle the message; otherwise, <c>false</c>.</returns>
        public bool CanHandle(IMessage message, IQueryResponse query)
        {
            if (message == null || query == null)
            {
                return(false);
            }

            return(typeof(TMessage) == message.GetType() && typeof(TQuery) == query.GetType());
        }
コード例 #9
0
 public ElasticSearchResults(ElasticSearchContext context, IQueryResponse <Dictionary <string, object> > searchResults, SelectMethod selectMethod, IEnumerable <IFieldQueryTranslator> virtualFieldProcessors)
 {
     _context = context;
     _elasticSearchIndexConfiguration = (ElasticSearchIndexConfiguration)_context.Index.Configuration;
     _mapper                 = (ElasticSearchDocumentPropertyMapper)_elasticSearchIndexConfiguration.IndexDocumentPropertyMapper;
     _selectMethod           = selectMethod;
     _virtualFieldProcessors = virtualFieldProcessors;
     _resultsTotal           = searchResults.Total;
     _searchResults          = ApplySecurity(searchResults, context.SecurityOptions, ref _resultsTotal);
 }
コード例 #10
0
        public void HandleQuery()
        {
            var securityContext = new TestSecurityContext();
            var query           = new SimpleQuery();

            IQueryResponse queryResponse = null;

            queryResponse = _cqrsLogicHandler.Handle(securityContext, query);

            Assert.IsNotNull(queryResponse);
        }
コード例 #11
0
		public void BogusQuery()
		{
			var client = this.ConnectedClient;
			IQueryResponse<ElasticSearchProject> queryResults = client.Search<ElasticSearchProject>(s=>s
				.QueryRawJson("here be dragons")
			);
			Assert.False(queryResults.IsValid);
			var error = queryResults.ConnectionStatus.Error;
			Assert.NotNull(error);
			Assert.True(error.HttpStatusCode == System.Net.HttpStatusCode.InternalServerError);
		}
コード例 #12
0
ファイル: PlayerModel.cs プロジェクト: komastar/IdleMiner
 public void OnQueryDone(IQueryResponse response)
 {
     if (Wallet.ContainsKey(response.Coin.CoinType))
     {
         Wallet[response.Coin.CoinType] += response.Amount;
     }
     else
     {
         Wallet.Add(response.Coin.CoinType, response.Amount);
     }
 }
コード例 #13
0
 protected void TestDefaultAssertions(IQueryResponse <ElasticsearchProject> queryResponse)
 {
     Assert.True(queryResponse.IsValid);
     Assert.NotNull(queryResponse.ConnectionStatus);
     Assert.Null(queryResponse.ConnectionStatus.Error);
     Assert.True(queryResponse.Total > 0, "No hits");
     Assert.True(queryResponse.Documents.Any());
     Assert.True(queryResponse.Documents.Count() > 0);
     Assert.True(queryResponse.Shards.Total > 0);
     Assert.True(queryResponse.Shards.Successful == queryResponse.Shards.Total);
     Assert.True(queryResponse.Shards.Failed == 0);
 }
コード例 #14
0
 protected void TestDefaultAssertions(IQueryResponse <ElasticSearchProject> queryResponse)
 {
     Assert.True(queryResponse.IsValid, "response is not valid");
     Assert.NotNull(queryResponse.ConnectionStatus, "connection status is null");
     Assert.Null(queryResponse.ConnectionStatus.Error, "connection status error is null");
     Assert.True(queryResponse.Total > 0, "Query yielded no results as indicated by total returned from ES");
     Assert.True(queryResponse.Documents.Any(), "documents.any() is false");
     Assert.True(queryResponse.Documents.Count() > 0, "documents.count is 0");
     Assert.True(queryResponse.Shards.Total > 0, "did not hit any shard");
     Assert.True(queryResponse.Shards.Successful == queryResponse.Shards.Total, "Not all the shards were hit succesfully");
     Assert.True(queryResponse.Shards.Failed == 0, "shards failed is not null");
 }
コード例 #15
0
ファイル: BaseFacetTestFixture.cs プロジェクト: romankor/NEST
 protected void TestDefaultAssertions(IQueryResponse<ElasticSearchProject> queryResponse)
 {
     Assert.True(queryResponse.IsValid, "response is not valid");
     Assert.NotNull(queryResponse.ConnectionStatus, "connection status is null");
     Assert.Null(queryResponse.ConnectionStatus.Error, "connection status error is null");
     Assert.True(queryResponse.Total > 0, "Query yielded no results as indicated by total returned from ES");
     Assert.True(queryResponse.Documents.Any(), "documents.any() is false");
     Assert.True(queryResponse.Documents.Count() > 0, "documents.count is 0");
     Assert.True(queryResponse.Shards.Total > 0, "did not hit any shard");
     Assert.True(queryResponse.Shards.Successful == queryResponse.Shards.Total, "Not all the shards were hit succesfully");
     Assert.True(queryResponse.Shards.Failed == 0, "shards failed is not null");
 }
コード例 #16
0
        /// <summary>
        /// Gets the server message handlers that can handle the specified message and query. This method will
        /// intentionally throw an exception if no handlers could be found.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="query">The query.</param>
        /// <returns>A collection of message handlers.</returns>
        /// <exception cref="System.ArgumentException">Argument Exception.</exception>
        public IEnumerable <IServerMessageHandler> GetHandlers(IMessage message, IQueryResponse query)
        {
            if (!this.handlers.Any(h => h.CanHandleMessageType(message)))
            {
                throw new ArgumentException(
                          $"Could not locate any server message handlers for the message type, '{message.GetType()}', " +
                          $"and the query type, '{query.GetType()}'. Did you forget to write a server message handler?");
            }

            var result = this.handlers.Where(x => x.CanHandle(message, query)).ToList();

            return(result);
        }
コード例 #17
0
        public void BogusQuery()
        {
            var client = this._client;
            IQueryResponse <ElasticsearchProject> queryResults = client.Search <ElasticsearchProject>(s => s
                                                                                                      .QueryRaw("here be dragons")
                                                                                                      );

            Assert.False(queryResults.IsValid);
            var error = queryResults.ConnectionStatus.Error;

            Assert.NotNull(error);
            Assert.True(error.HttpStatusCode == System.Net.HttpStatusCode.BadRequest, error.HttpStatusCode.ToString());
        }
コード例 #18
0
        public async Task ExecuteAsync(IQueryResponse <List <GenderAverageDto> > queryResponse)
        {
            await _auditService.LogAccess(nameof(GetAverageByGenderQuery));

            using (var connection = new SqlConnection(_connectionStringProvider.GetConnectionString()))
            {
                var result = await connection.QueryAsync <GenderAverageDto>(
                    @"SELECT D.Gender, AVG(A.YearSalary) AS Value 
                        FROM SurveyAnswer A
	                        INNER JOIN Developer D ON D.DeveloperId = A.DeveloperId
                        GROUP BY D.Gender
                        ORDER BY Value DESC");

                queryResponse.Respond(result.ToList());
            }
        }
コード例 #19
0
        public async Task ExecuteAsync(IQueryResponse <List <ProgrammingLanguageDto> > queryResponse)
        {
            await _auditService.LogAccess(nameof(GetMostUsedProgrammingLanguages));

            var response = await _dbContext
                           .GetAllNoCachingQuery <ProgrammingLanguage>()
                           .Select(l =>
                                   new ProgrammingLanguageDto()
            {
                ProgrammingLanguageId = l.ProgrammingLanguageId,
                Name            = l.Name,
                IsStronglyTyped = l.IsStronglyTyped
            })
                           .ToListAsync();

            queryResponse.Respond(response);
        }
コード例 #20
0
        /// <summary>
        /// Handles the specified message by updating the specified query to reflect the state changes described in the
        /// specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="query">The query to be updated.</param>
        public void Handle(IMessage message, IQueryResponse query)
        {
            var msg = message as TMessage;
            var q   = query as TQuery;

            if (msg == null || q == null)
            {
                return;
            }

            var component = this.LocateQueryComponent(msg, q);

            if (component == null)
            {
                return;
            }

            this.modelUpdaterResolver.GetUpdater <TQueryComponent, TMessage>().Update(component, msg);
        }
コード例 #21
0
        public void SimpleTermFacet()
        {
            IQueryResponse <ElasticsearchProject> queryResults = this.SearchRaw <ElasticsearchProject>(
                @" { ""query"" : {
							""match_all"" : { }
					},
					""facets"" : {
					  ""followers.lastName"" : { ""terms"" : {""field"" : ""followers.lastName""} }
					}
				}"
                );

            var facet = queryResults.Facets["followers.lastName"];

            this.TestDefaultAssertions(queryResults);
            Assert.IsInstanceOf <TermFacet>(facet);
            var tf = (TermFacet)facet;

            Assert.AreEqual(0, tf.Missing);
            Assert.Greater(tf.Other, 0);
            Assert.Greater(tf.Total, 0);
            Assert.Greater(tf.Items.Count(), 0);

            foreach (TermItem term in tf.Items)
            {
                Assert.Greater(term.Count, 0);
                Assert.IsNotNullOrEmpty(term.Term);
            }

            tf = queryResults.Facet <TermFacet>(p => p.Followers.Select(f => f.LastName));
            Assert.AreEqual(0, tf.Missing);
            Assert.Greater(tf.Other, 0);
            Assert.Greater(tf.Total, 0);
            Assert.Greater(tf.Items.Count(), 0);

            var items = queryResults.FacetItems <TermItem>(p => p.Followers.Select(f => f.LastName));

            foreach (var i in items)
            {
                Assert.Greater(i.Count, 0);
                Assert.IsNotNullOrEmpty(i.Term);
            }
        }
コード例 #22
0
        public IActionResult Get(string tokens = "")
        {
            IQueryResponse <ContentItem> response = null;

            var qs = Request.QueryString;

            if (qs.HasValue)
            {
                IQueryRequest request = new ContentQueryRequest().Parse(qs.Value);
                response = Query.Execute(request);
            }

            if (response == null)
            {
                return(Json(new { Message = "unable to execute query" }));
            }
            else
            {
                return(Json(response));
            }
        }
コード例 #23
0
        public async Task ProcessQueryResponse(IQueryResponse response)
        {
            try
            {
                var championsFromResponse = await this.ConvertResponseContent(response.Content);
                var championsFromCollection = await this.championQueryingRepository.Find(c => c.Available == true);

                bool areCollectionsEqual = CollectionEquality.CheckForEquality<Champion, int>(championsFromResponse, championsFromCollection, c => c.ChampionId);

                if (!areCollectionsEqual)
                {
                    await this.ProcessDifferences(championsFromResponse, championsFromCollection);
                }

                this.logger.Info("Finished processing Champions response");
            }
            catch (Exception ex)
            {
                this.logger.FatalFormat("Failed to process Champions response: {0}", ex);
            }
        }
コード例 #24
0
        public async Task ProcessQueryResponse(IQueryResponse response)
        {
            try
            {
                var itemsFromResponse = await this.ConvertResponseContent(response.Content);

                var itemsFromCollection = await this.Repository.Find(i => i.Available == true);

                bool areCollectionsEqual = CollectionEquality.CheckForEquality <Rune, int>(itemsFromResponse, itemsFromCollection, r => r.RuneId);

                if (!areCollectionsEqual)
                {
                    await this.ProcessDifferences(itemsFromResponse, itemsFromCollection);
                }

                this.logger.Info("Finished processing Runes response");
            }
            catch (Exception ex)
            {
                this.logger.FatalFormat("Failed to process Runes response: {0}", ex);
            }
        }
コード例 #25
0
        public async Task ProcessQueryResponse(IQueryResponse response)
        {
            try
            {
                var championsFromResponse = await this.ConvertResponseContent(response.Content);

                var championsFromCollection = await this.championQueryingRepository.Find(c => c.Available == true);

                bool areCollectionsEqual = CollectionEquality.CheckForEquality <Champion, int>(championsFromResponse, championsFromCollection, c => c.ChampionId);

                if (!areCollectionsEqual)
                {
                    await this.ProcessDifferences(championsFromResponse, championsFromCollection);
                }

                this.logger.Info("Finished processing Champions response");
            }
            catch (Exception ex)
            {
                this.logger.FatalFormat("Failed to process Champions response: {0}", ex);
            }
        }
コード例 #26
0
        public IBulkResponse IndexSearchResults(IQueryResponse <T> searchResult, IObserver <IReindexResponse <T> > observer, string toIndex, int page)
        {
            if (!searchResult.IsValid)
            {
                throw new ReindexException(searchResult.ConnectionStatus, "reindex failed on scroll #" + page);
            }

            var indexResult = this.CurrentClient.IndexMany(searchResult.Documents, toIndex);

            if (!indexResult.IsValid)
            {
                throw new ReindexException(indexResult.ConnectionStatus, "reindex failed when indexing page " + page);
            }

            observer.OnNext(new ReindexResponse <T>()
            {
                BulkResponse  = indexResult,
                QueryResponse = searchResult,
                Scroll        = page
            });
            return(indexResult);
        }
コード例 #27
0
        /// <summary>
        /// Executes a query and returns the header for the result in the response.
        /// </summary>
        /// <param name="dispatchId">The number we need to respond with.</param>
        /// <param name="command"></param>
        /// <remarks>
        /// This keeps track of all result sets because sections of the result are
        /// later queries via the <see cref="ProtocolConstants.ResultSection"/>
        /// Query.
        /// </remarks>
        /// <returns></returns>
        private byte[] QueryCommand(int dispatchId, byte[] command)
        {
            // Read the query from the Query.
            MemoryStream input  = new MemoryStream(command, 8, command.Length - 8);
            BinaryReader reader = new BinaryReader(input, Encoding.Unicode);
            SqlQuery     query  = SqlQuery.ReadFrom(reader);

            try {
                // Do the query
                IQueryResponse response = dbInterface.ExecuteQuery(query)[0];

                // Prepare the stream to output the response to,
                MemoryStream output = new MemoryStream();
                BinaryWriter writer = new BinaryWriter(output, Encoding.Unicode);

                writer.Write(dispatchId);
                writer.Write(ProtocolConstants.Success);

                // The response sends the result id, the time the query took, the
                // total row count, and description of each column in the result.
                writer.Write(response.ResultId);
                writer.Write(response.QueryTimeMillis);
                writer.Write(response.RowCount);
                int colCount = response.ColumnCount;
                writer.Write(colCount);
                for (int i = 0; i < colCount; ++i)
                {
                    response.GetColumnDescription(i).WriteTo(writer);
                }
                writer.Flush();
                return(output.ToArray());
            } catch (DataException e) {
                //      debug.writeException(e);
                return(Exception(dispatchId, e));
            }
        }
コード例 #28
0
        /// <inheritdoc/>
        public virtual IQueryResponse[] ExecuteQuery(SqlQuery query)
        {
            CheckNotDisposed();

            // Record the Query start time
            DateTime startTime = DateTime.Now;

            // Where Query result eventually resides.
            ResultSetInfo resultSetInfo;
            int resultId = -1;

            // For each StreamableObject in the SQLQuery object, translate it to a
            // IRef object that presumably has been pre-pushed onto the server from
            // the client.
            bool blobsWereFlushed = false;
            object[] vars = query.Variables;
            if (vars != null) {
                for (int i = 0; i < vars.Length; ++i) {
                    object ob = vars[i];
                    // This is a streamable object, so convert it to a *IRef
                    if (ob != null && ob is StreamableObject) {
                        StreamableObject sObject = (StreamableObject) ob;

                        // Flush the streamable object from the cache
                        // Note that this also marks the blob as complete in the blob store.
                        IRef reference = FlushLargeObjectRefFromCache(sObject.Identifier);

                        // Set the IRef object in the Query.
                        vars[i] = reference;

                        // There are blobs in this Query that were written to the blob store.
                        blobsWereFlushed = true;
                    }
                }
            }

            // Evaluate the sql Query.
            Table[] results = SqlQueryExecutor.Execute(dbConnection, query);
            IQueryResponse[] responses = new IQueryResponse[results.Length];
            int j = 0;

            foreach (Table result in results) {
                try {
                    // Put the result in the result cache...  This will Lock this object
                    // until it is removed from the result set cache.  Returns an id that
                    // uniquely identifies this result set in future communication.
                    // NOTE: This locks the roots of the table so that its contents
                    //   may not be altered.
                    resultSetInfo = new ResultSetInfo(query, result);
                    resultId = AddResultSet(resultSetInfo);
                } catch (Exception e) {
                    // If resultId set, then dispose the result set.
                    if (resultId != -1)
                        DisposeResultSet(resultId);

                    // Handle the throwable during Query execution
                    throw HandleExecuteThrowable(e, query);
                }

                // The time it took the Query to execute.
                TimeSpan taken = DateTime.Now - startTime;

                // Return the Query response
                responses[j]  = new QueryResponse(resultId, resultSetInfo, (int) taken.TotalMilliseconds, "");
                j++;
            }

            return responses;
        }
コード例 #29
0
        protected IQueryResponse[] CoreExecuteQuery(string text, IEnumerable<SqlQueryParameter> parameters)
        {
            // Record the Query start time
            DateTime startTime = DateTime.Now;

            // Where Query result eventually resides.
            int resultId = -1;

            // For each StreamableObject in the query object, translate it to a
            // IRef object that presumably has been pre-pushed onto the server from
            // the client.

            // Evaluate the sql Query.
            var query = new SqlQuery(text);
            if (parameters != null) {
                foreach (var parameter in parameters) {
                    var preparedParam = parameter.Value;
                    if (preparedParam is StreamableObject) {
                        var obj = (StreamableObject) preparedParam;
                        IRef objRef = CompleteStream(obj.Identifier);
                        preparedParam = objRef;
                    }
                    query.Parameters.Add(new SqlQueryParameter(parameter.Name, preparedParam));
                }
            }

            Table[] results = SqlQueryExecutor.Execute(Session.Connection, query);
            var responses = new IQueryResponse[results.Length];
            int j = 0;

            foreach (Table result in results) {
                QueryResult queryResult;
                try {
                    // Put the result in the result cache...  This will Lock this object
                    // until it is removed from the result set cache.  Returns an id that
                    // uniquely identifies this result set in future communication.
                    // NOTE: This locks the roots of the table so that its contents
                    //   may not be altered.
                    queryResult = new QueryResult(query, result);
                    resultId = AddResult(queryResult);
                } catch (Exception e) {
                    // If resultId set, then dispose the result set.
                    if (resultId != -1)
                        DisposeResult(resultId);

                    throw;
                }

                // The time it took the Query to execute.
                TimeSpan taken = DateTime.Now - startTime;

                // Return the Query response
                responses[j]  = new QueryResponse(resultId, queryResult, (int) taken.TotalMilliseconds, "");
                j++;
            }

            return responses;
        }
コード例 #30
0
 protected void TestDefaultAssertions(IQueryResponse<ElasticSearchProject> queryResponse)
 {
     Assert.True(queryResponse.IsValid);
     Assert.NotNull(queryResponse.ConnectionStatus);
     Assert.Null(queryResponse.ConnectionStatus.Error);
     Assert.True(queryResponse.Total > 0, "No hits");
     Assert.True(queryResponse.Documents.Any());
     Assert.True(queryResponse.Documents.Count() > 0);
     Assert.True(queryResponse.Shards.Total > 0);
     Assert.True(queryResponse.Shards.Successful == queryResponse.Shards.Total);
     Assert.True(queryResponse.Shards.Failed == 0);
 }
コード例 #31
0
        protected IQueryResponse[] CoreExecuteQuery(IQuery context, string text, IEnumerable <QueryParameter> parameters, QueryParameterStyle parameterStyle)
        {
            // Where Query result eventually resides.
            int resultId = -1;

            // For each StreamableObject in the query object, translate it to a
            // IRef object that presumably has been pre-pushed onto the server from
            // the client.

            // Evaluate the sql Query.
            var query = new SqlQuery(text, parameterStyle);

            if (parameters != null)
            {
                foreach (var p in parameters)
                {
                    var c = p.SqlType.TypeCode;
                    switch (c)
                    {
                    case SqlTypeCode.Blob:
                    case SqlTypeCode.Clob:
                    case SqlTypeCode.LongVarBinary:
                    case SqlTypeCode.LongVarChar:
                    case SqlTypeCode.VarBinary:
                        throw new NotImplementedException("TODO: Download the Large-Objects and replace with a reference");

                    default:
                        query.Parameters.Add(p);
                        break;
                    }
                }
            }

            var stopwatch = new Stopwatch();

            stopwatch.Start();

            var results   = context.ExecuteQuery(query);
            var responses = new IQueryResponse[results.Length];
            int j         = 0;

            foreach (var result in results)
            {
                QueryResult queryResult;
                try {
                    if (result.Type == StatementResultType.Exception)
                    {
                        throw result.Error;
                    }

                    queryResult = new QueryResult(query, result, context.AutoCommit());
                    resultId    = AddResult(queryResult);
                } catch (Exception) {
                    if (resultId != -1)
                    {
                        DisposeResult(resultId);
                    }

                    throw;
                }

                var taken = stopwatch.ElapsedMilliseconds;

                // Return the Query response
                responses[j] = new QueryResponse(resultId, queryResult, (int)taken, "");

                j++;
            }

            stopwatch.Stop();
            return(responses);
        }
コード例 #32
0
ファイル: ServerConnector.cs プロジェクト: prepare/deveeldb
        protected IQueryResponse[] CoreExecuteQuery(IQueryContext context, string text, IEnumerable<QueryParameter> parameters)
        {
            // Where Query result eventually resides.
            int resultId = -1;

            // For each StreamableObject in the query object, translate it to a
            // IRef object that presumably has been pre-pushed onto the server from
            // the client.

            // Evaluate the sql Query.
            var query = new SqlQuery(text);
            if (parameters != null) {
                // TODO: Download the Large-Objects and replace with a reference
            }

            var stopwatch = new Stopwatch();
            stopwatch.Start();

            var results = context.ExecuteQuery(query);
            var responses = new IQueryResponse[results.Length];
            int j = 0;

            foreach (var result in results) {
                QueryResult queryResult;
                try {
                    queryResult = new QueryResult(query, result);
                    resultId = AddResult(queryResult);
                } catch (Exception e) {
                    if (resultId != -1)
                        DisposeResult(resultId);

                    throw;
                }

                var taken = stopwatch.Elapsed;

                // Return the Query response
                responses[j] = new QueryResponse(resultId, queryResult, (int)taken.TotalMilliseconds, "");

                j++;
            }

            stopwatch.Stop();
            return responses;
        }
コード例 #33
0
        public async Task ExecuteAsync(IQueryResponse <int> queryResponse)
        {
            await _auditService.LogAccess(nameof(GetTotalResponsesCountQuery));

            throw new NotImplementedException();
        }
コード例 #34
0
 public QueryExecuteResponse(IQueryResponse[] queryResponse)
 {
     QueryResponse = queryResponse;
 }
コード例 #35
0
 private void AssertBoolQueryResults(IQueryResponse<BoolTerm> results, int expectedCount)
 {
     Assert.True(results.IsValid, results.ConnectionStatus.Result);
     Assert.True(results.ConnectionStatus.Success, results.ConnectionStatus.Result);
     Assert.GreaterOrEqual(results.Total, expectedCount);
 }
コード例 #36
0
 private void AssertTermResults(IQueryResponse<ElasticsearchProject> results)
 {
     Assert.True(results.IsValid, results.ConnectionStatus.ResponseRaw.Utf8String());
     Assert.True(results.ConnectionStatus.Success, results.ConnectionStatus.ResponseRaw.Utf8String());
     Assert.GreaterOrEqual(results.Total, 1);
 }
コード例 #37
0
ファイル: BoolQueryResults.cs プロジェクト: cicorias/NEST
 private void AssertBoolQueryResults(IQueryResponse <BoolTerm> results, int expectedCount)
 {
     Assert.True(results.IsValid, results.ConnectionStatus.Result);
     Assert.True(results.ConnectionStatus.Success, results.ConnectionStatus.Result);
     Assert.GreaterOrEqual(results.Total, expectedCount);
 }
コード例 #38
0
ファイル: ServerConnector.cs プロジェクト: deveel/deveeldb
        protected IQueryResponse[] CoreExecuteQuery(IQuery context, string text, IEnumerable<QueryParameter> parameters, QueryParameterStyle parameterStyle)
        {
            // Where Query result eventually resides.
            int resultId = -1;

            // For each StreamableObject in the query object, translate it to a
            // IRef object that presumably has been pre-pushed onto the server from
            // the client.

            // Evaluate the sql Query.
            var query = new SqlQuery(text, parameterStyle);
            if (parameters != null) {
                foreach (var p in parameters) {
                    var c = p.SqlType.TypeCode;
                    switch (c) {
                        case SqlTypeCode.Blob:
                        case SqlTypeCode.Clob:
                        case SqlTypeCode.LongVarBinary:
                        case SqlTypeCode.LongVarChar:
                        case SqlTypeCode.VarBinary:
                            throw new NotImplementedException("TODO: Download the Large-Objects and replace with a reference");
                        default:
                            query.Parameters.Add(p);
                            break;
                    }
                }
            }

            var stopwatch = new Stopwatch();
            stopwatch.Start();

            var results = context.ExecuteQuery(query);
            var responses = new IQueryResponse[results.Length];
            int j = 0;

            foreach (var result in results) {
                QueryResult queryResult;
                try {
                    if (result.Type == StatementResultType.Exception)
                        throw result.Error;

                    queryResult = new QueryResult(query, result, context.AutoCommit());
                    resultId = AddResult(queryResult);
                } catch (Exception) {
                    if (resultId != -1)
                        DisposeResult(resultId);

                    throw;
                }

                var taken = stopwatch.ElapsedMilliseconds;

                // Return the Query response
                responses[j] = new QueryResponse(resultId, queryResult, (int)taken, "");

                j++;
            }

            stopwatch.Stop();
            return responses;
        }
コード例 #39
0
ファイル: DeveelDbCommand.cs プロジェクト: deveel/deveeldb
        private void CreateResults(IQueryResponse[] response)
        {
            results = new LocalQueryResult[response.Length];

            for (int i = 0; i < response.Length; i++) {
                var r = response[i];
                var columns = new QueryResultColumn[r.ColumnCount];
                for (int j = 0; j < columns.Length; j++) {
                    columns[j] = r.GetColumn(j);
                }

                var result = new LocalQueryResult(connection);
                result.QueryTime = r.QueryTimeMillis;

                result.Setup(r.ResultId, columns, r.RowCount);
                result.SetFetchSize(connection.Settings.FetchSize);
                result.SetMaxRowCount(connection.Settings.MaxFetchSize);

                // Does the result set contain large objects?  We can't cache a
                // result that contains binary data.

                bool hasLargeObject = result.HasLargeObject;

                // If the result row count < 40 then download and store locally in the
                // result set and dispose the resources on the server.
                if (!hasLargeObject && result.RowCount < 40) {
                    result.DownloadAndClose();
                } else {
                    result.Download(0, System.Math.Min(10, result.RowCount));
                }

                results[i] = result;
            }
        }
コード例 #40
0
ファイル: TermToString.cs プロジェクト: cicorias/NEST
 private void AssertTermResults(IQueryResponse <ElasticsearchProject> results)
 {
     Assert.True(results.IsValid, results.ConnectionStatus.Result);
     Assert.True(results.ConnectionStatus.Success, results.ConnectionStatus.Result);
     Assert.GreaterOrEqual(results.Total, 1);
 }
コード例 #41
0
 private IEnumerable<Tweet> Results(IQueryResponse<Tweet> response)
 {
     return response.Documents;
 }
コード例 #42
0
 /// <summary>
 /// Handles the specified query.
 /// </summary>
 /// <param name="query">The query.</param>
 public void HandleQueryResponse(IQueryResponse query)
 {
 }