コード例 #1
0
        IAsyncResult invokeSuggest(SuggestRequest request, AsyncCallback callback, object state, bool synchronized)
        {
            var marshaller   = new SuggestRequestMarshaller();
            var unmarshaller = SuggestResponseUnmarshaller.Instance;

            return(Invoke(request, callback, state, synchronized, marshaller, unmarshaller, signer));
        }
コード例 #2
0
        /// <summary>
        /// Retrieving suggestions using the AWS CloudSearch Suggester. The AWS CloudSearch Suggester
        /// returns results from the entire index and does not suport query filtering.
        /// </summary>
        /// <param name="parameters">Suggest request parameters</param>
        /// <returns>SuggestResults</returns>
        public SuggestResults RetieveSuggestions(NameValueCollection parameters)
        {
            SuggestResults suggestResults = new SuggestResults();

            try
            {
                AmazonCloudSearchDomainClient client = GetCloudSearchClient();

                SuggestRequest request = new SuggestRequest();
                if (parameters["suggestername"] != null)
                {
                    request.Suggester = parameters["suggestername"];
                }

                if (parameters["q"] != null)
                {
                    request.Query = parameters["q"];
                }

                request.Size = parameters["size"] != null?Convert.ToInt32(parameters["size"]) : this.DefaultPageSize;

                SuggestResponse results = client.Suggest(request);
                suggestResults.Matches = results.Suggest.Suggestions.Select(c => c.Suggestion).ToList();
            }
            catch (Exception ex)
            {
                suggestResults.HasError    = true;
                suggestResults.ErrorDetail = ex.Message + " : " + ex.StackTrace;
            }

            return(suggestResults);
        }
コード例 #3
0
        /// <summary>
        /// Retrieves autocomplete suggestions for a partial query string. You can use suggestions
        /// enable you to display likely matches before users finish typing. In Amazon CloudSearch,
        /// suggestions are based on the contents of a particular text field. When you request
        /// suggestions, Amazon CloudSearch finds all of the documents whose values in the suggester
        /// field start with the specified query string. The beginning of the field must match
        /// the query string to be considered a match.
        ///
        ///
        /// <para>
        /// For more information about configuring suggesters and retrieving suggestions, see
        /// <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-suggestions.html">Getting
        /// Suggestions</a> in the <i>Amazon CloudSearch Developer Guide</i>.
        /// </para>
        ///
        /// <para>
        /// The endpoint for submitting <code>Suggest</code> requests is domain-specific. You
        /// submit suggest requests to a domain's search endpoint. To get the search endpoint
        /// for your domain, use the Amazon CloudSearch configuration service <code>DescribeDomains</code>
        /// action. A domain's endpoints are also displayed on the domain dashboard in the Amazon
        /// CloudSearch console.
        /// </para>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the Suggest service method.</param>
        ///
        /// <returns>The response from the Suggest service method, as returned by CloudSearchDomain.</returns>
        /// <exception cref="Amazon.CloudSearchDomain.Model.SearchException">
        /// Information about any problems encountered while processing a search request.
        /// </exception>
        public SuggestResponse Suggest(SuggestRequest request)
        {
            var marshaller   = new SuggestRequestMarshaller();
            var unmarshaller = SuggestResponseUnmarshaller.Instance;

            return(Invoke <SuggestRequest, SuggestResponse>(request, marshaller, unmarshaller));
        }
コード例 #4
0
        public virtual string[] GetSuggestions(SuggestRequest request, CultureInfo culture, string indexName = null)
        {
            if (indexName == null)
            {
                indexName = _elasticSearchSettings.GetDefaultIndexName(Language.GetLanguageCode(culture));
            }

            var endpoint = GetSearchEndpoint(indexName, $"?filter_path={JsonNames.Suggest}");

            Logger.Information($"GetSuggestions query:\nGET {endpoint}\n{request?.ToString(Formatting.Indented)}\n");

            JsonReader response = GetResponse(request, endpoint, out _);

            var serializer = new JsonSerializer
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                NullValueHandling     = NullValueHandling.Ignore
            };

            SuggestionsRootObject results = serializer.Deserialize <SuggestionsRootObject>(response);

            if (results?.Suggestions == null)
            {
                results = results?.InnerRoot;
            }

            if (results?.Suggestions != null && results.Suggestions.Length > 0)
            {
                return(results.Suggestions.SelectMany(s => s.Options.Select(o => o.Text)).ToArray());
            }

            return(new string[0]);
        }
コード例 #5
0
        internal virtual SuggestResponse Suggest(SuggestRequest request)
        {
            var marshaller   = SuggestRequestMarshaller.Instance;
            var unmarshaller = SuggestResponseUnmarshaller.Instance;

            return(Invoke <SuggestRequest, SuggestResponse>(request, marshaller, unmarshaller));
        }
コード例 #6
0
        public async Task <SuggestResponse <Email> > SuggestEmail(string query, int count             = 5,
                                                                  CancellationToken cancellationToken = default)
        {
            var request = new SuggestRequest(query, count);

            return(await SuggestEmail(request, cancellationToken));
        }
コード例 #7
0
        public SuggestRequestTests()
        {
            var request = new SuggestRequest()
            {
                AllIndices      = true,
                AllowNoIndices  = true,
                ExpandWildcards = ExpandWildcards.Closed,
                GlobalText      = "global suggest text",
                Suggest         = new Dictionary <string, ISuggester>
                {
                    { "terms_sug", new CompletionSuggester
                      {
                          Analyzer  = "standard",
                          Field     = Property.Path <ElasticsearchProject>(p => p.Content),
                          Size      = 4,
                          ShardSize = 10,
                          Fuzzy     = new FuzzySuggester
                          {
                              Fuzziness    = Fuzziness.Ratio(0.3),
                              PrefixLength = 4
                          }
                      } }
                }
            };
            var response = this._client.Suggest(request);

            this._status = response.ConnectionStatus;
        }
コード例 #8
0
        /// <summary>
        /// Initiates the asynchronous execution of the Suggest operation.
        /// <seealso cref="Amazon.CloudSearchDomain.IAmazonCloudSearchDomain"/>
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the Suggest operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task <SuggestResponse> SuggestAsync(SuggestRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = new SuggestRequestMarshaller();
            var unmarshaller = SuggestResponseUnmarshaller.Instance;

            return(Invoke <IRequest, SuggestRequest, SuggestResponse>(request, marshaller, unmarshaller, signer, cancellationToken));
        }
コード例 #9
0
        public async Task <SuggestResponse <Bank> > FindBank(string query)
        {
            var request = new SuggestRequest(query);

            return(await ExecutePost <SuggestResponse <Bank> >(
                       method : SuggestionsMethod.Find,
                       entity : SuggestionsEntity.Bank, request : request));
        }
コード例 #10
0
        public async Task <SuggestResponse <Address> > FindAddress(string query)
        {
            var request = new SuggestRequest(query);

            return(await Execute <SuggestResponse <Address> >(
                       method : SuggestionsMethod.Find,
                       entity : SuggestionsEntity.Address, request : request));
        }
コード例 #11
0
        /// <summary>
        /// Initiates the asynchronous execution of the Suggest operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the Suggest operation on AmazonCloudSearchDomainClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        ///
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndSuggest
        ///         operation.</returns>
        public virtual IAsyncResult BeginSuggest(SuggestRequest request, AsyncCallback callback, object state)
        {
            var marshaller   = new SuggestRequestMarshaller();
            var unmarshaller = SuggestResponseUnmarshaller.Instance;

            return(BeginInvoke <SuggestRequest>(request, marshaller, unmarshaller,
                                                callback, state));
        }
コード例 #12
0
        /// <summary>
        /// Initiates the asynchronous execution of the Suggest operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the Suggest operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public virtual Task <SuggestResponse> SuggestAsync(SuggestRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = SuggestRequestMarshaller.Instance;
            var unmarshaller = SuggestResponseUnmarshaller.Instance;

            return(InvokeAsync <SuggestRequest, SuggestResponse>(request, marshaller,
                                                                 unmarshaller, cancellationToken));
        }
コード例 #13
0
        public override string[] GetSuggestions(SuggestRequest request, CultureInfo culture, string indexName = null)
        {
            if (_suggestions == null)
            {
                return(base.GetSuggestions(request, culture, indexName));
            }

            return(_suggestions);
        }
コード例 #14
0
        /// <summary>
        /// Retrieves autocomplete suggestions for a partial query string. You can use suggestions
        /// enable you to display likely matches before users finish typing. In Amazon CloudSearch,
        /// suggestions are based on the contents of a particular text field. When you request
        /// suggestions, Amazon CloudSearch finds all of the documents whose values in the suggester
        /// field start with the specified query string. The beginning of the field must match
        /// the query string to be considered a match.
        ///
        ///
        /// <para>
        /// For more information about configuring suggesters and retrieving suggestions, see
        /// <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-suggestions.html">Getting
        /// Suggestions</a> in the <i>Amazon CloudSearch Developer Guide</i>.
        /// </para>
        ///
        /// <para>
        /// The endpoint for submitting <code>Suggest</code> requests is domain-specific. You
        /// submit suggest requests to a domain's search endpoint. To get the search endpoint
        /// for your domain, use the Amazon CloudSearch configuration service <code>DescribeDomains</code>
        /// action. A domain's endpoints are also displayed on the domain dashboard in the Amazon
        /// CloudSearch console.
        /// </para>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the Suggest service method.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        ///
        /// <returns>The response from the Suggest service method, as returned by CloudSearchDomain.</returns>
        /// <exception cref="Amazon.CloudSearchDomain.Model.SearchException">
        /// Information about any problems encountered while processing a search request.
        /// </exception>
        public virtual Task <SuggestResponse> SuggestAsync(SuggestRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = SuggestRequestMarshaller.Instance;
            options.ResponseUnmarshaller = SuggestResponseUnmarshaller.Instance;

            return(InvokeAsync <SuggestResponse>(request, options, cancellationToken));
        }
コード例 #15
0
        /// <summary>
        /// Retrieves autocomplete suggestions for a partial query string. You can use suggestions
        /// enable you to display likely matches before users finish typing. In Amazon CloudSearch,
        /// suggestions are based on the contents of a particular text field. When you request
        /// suggestions, Amazon CloudSearch finds all of the documents whose values in the suggester
        /// field start with the specified query string. The beginning of the field must match
        /// the query string to be considered a match.
        ///
        ///
        /// <para>
        /// For more information about configuring suggesters and retrieving suggestions, see
        /// <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/getting-suggestions.html">Getting
        /// Suggestions</a> in the <i>Amazon CloudSearch Developer Guide</i>.
        /// </para>
        ///
        /// <para>
        /// The endpoint for submitting <code>Suggest</code> requests is domain-specific. You
        /// submit suggest requests to a domain's search endpoint. To get the search endpoint
        /// for your domain, use the Amazon CloudSearch configuration service <code>DescribeDomains</code>
        /// action. A domain's endpoints are also displayed on the domain dashboard in the Amazon
        /// CloudSearch console.
        /// </para>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the Suggest service method.</param>
        ///
        /// <returns>The response from the Suggest service method, as returned by CloudSearchDomain.</returns>
        /// <exception cref="Amazon.CloudSearchDomain.Model.SearchException">
        /// Information about any problems encountered while processing a search request.
        /// </exception>
        public virtual SuggestResponse Suggest(SuggestRequest request)
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = SuggestRequestMarshaller.Instance;
            options.ResponseUnmarshaller = SuggestResponseUnmarshaller.Instance;

            return(Invoke <SuggestResponse>(request, options));
        }
コード例 #16
0
        /// <summary>
        /// Initiates the asynchronous execution of the Suggest operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the Suggest operation on AmazonCloudSearchDomainClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        ///
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndSuggest
        ///         operation.</returns>
        public virtual IAsyncResult BeginSuggest(SuggestRequest request, AsyncCallback callback, object state)
        {
            var options = new InvokeOptions();

            options.RequestMarshaller    = SuggestRequestMarshaller.Instance;
            options.ResponseUnmarshaller = SuggestResponseUnmarshaller.Instance;

            return(BeginInvoke(request, options, callback, state));
        }
コード例 #17
0
 private bool CountryEq(SuggestRequest request, StringValues value)
 {
     if (string.IsNullOrEmpty(value))
     {
         return(false);
     }
     request.Country.IsActive = true;
     request.Country.Country  = value;
     return(true);
 }
コード例 #18
0
        internal static string[] GetSuggestions <T>(this IElasticSearchService <T> service, string searchText, SearchEngine engine)
        {
            var request = new SuggestRequest(searchText, service.SizeValue);

            var elasticSuggestions = engine.GetSuggestions(request, service.SearchLanguage);

            var repository           = ServiceLocator.Current.GetInstance <IAutoSuggestRepository>();
            var editorialSuggestions = repository.GetWords(Language.GetLanguageCode(service.CurrentLanguage))
                                       .Where(w => w?.StartsWith(searchText) == true);

            return(editorialSuggestions.Concat(elasticSuggestions).Distinct().ToArray());
        }
コード例 #19
0
        public SuggestResponse Suggest(SuggestRequest request)
        {
            Dictionary <int, float> similarity = _pool.DictionaryOfFloatByInt.Get();
            var selfIds = _pool.HashSetOfInts.Get();
            Dictionary <int, List <LikeBucket> > suggested = _pool.DictionaryOfLikeBucketsByInt.Get();

            _context.Likes.Suggest(
                request.Id,
                similarity,
                suggested,
                selfIds,
                _context,
                request.City.IsActive ? _storage.Cities.Get(request.City.City) : (short)0,
                request.Country.IsActive ? _storage.Countries.Get(request.Country.Country) : (short)0);

            var response = _pool.SuggestResponse.Get();
            var list     = _pool.ListOfIntegers.Get();
            var comparer = _pool.SuggestComparer.Get();

            comparer.Init(similarity);
            list.AddRange(suggested.Keys);
            list.Sort(comparer);

            int count = 0;

            for (int i = 0; i < list.Count; i++)
            {
                var buckets = suggested[list[i]];
                for (int bucketIndex = 0; bucketIndex < buckets.Count; bucketIndex++)
                {
                    if (!selfIds.Contains(buckets[bucketIndex].LikeeId))
                    {
                        response.Ids.Add(buckets[bucketIndex].LikeeId);
                        count++;
                        if (count == request.Limit)
                        {
                            goto Finish;
                        }
                    }
                }
            }
Finish:
            response.Limit = request.Limit;

            _pool.DictionaryOfFloatByInt.Return(similarity);
            _pool.DictionaryOfLikeBucketsByInt.Return(suggested);
            _pool.ListOfIntegers.Return(list);
            _pool.SuggestComparer.Return(comparer);
            _pool.HashSetOfInts.Return(selfIds);

            return(response);
        }
コード例 #20
0
 public virtual Response <SuggestDocumentsResult> SuggestPost(SuggestRequest suggestRequest, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)
 {
     using var scope = _clientDiagnostics.CreateScope("DocumentsClient.SuggestPost");
     scope.Start();
     try
     {
         return(RestClient.SuggestPost(suggestRequest, requestOptions, cancellationToken));
     }
     catch (Exception e)
     {
         scope.Failed(e);
         throw;
     }
 }
コード例 #21
0
        internal SuggestResponse Suggest(SuggestRequest request)
        {
            var task = SuggestAsync(request);

            try
            {
                return(task.Result);
            }
            catch (AggregateException e)
            {
                ExceptionDispatchInfo.Capture(e.InnerException).Throw();
                return(null);
            }
        }
コード例 #22
0
        public void CanConvertToPostRequestPayload()
        {
            SuggestParameters parameters = CreateTestParameters();

            SuggestRequest request = parameters.ToRequest("find me", "mySuggester");

            Assert.Equal(parameters.Filter, request.Filter);
            Assert.Equal(parameters.HighlightPostTag, request.HighlightPostTag);
            Assert.Equal(parameters.HighlightPreTag, request.HighlightPreTag);
            Assert.Equal(parameters.MinimumCoverage, request.MinimumCoverage);
            Assert.Equal(parameters.OrderBy.ToCommaSeparatedString(), request.OrderBy);
            Assert.Equal("find me", request.SearchText);
            Assert.Equal(parameters.SearchFields.ToCommaSeparatedString(), request.SearchFields);
            Assert.Equal(parameters.Select.ToCommaSeparatedString(), request.Select);
            Assert.Equal("mySuggester", request.SuggesterName);
            Assert.Equal(parameters.Top, request.Top);
            Assert.Equal(parameters.UseFuzzyMatching, request.UseFuzzyMatching);
        }
コード例 #23
0
        public object Execute(ExecutorContext context)
        {
            var cmdletContext = context as CmdletContext;
            // create request
            var request = new SuggestRequest();

            if (cmdletContext.Query != null)
            {
                request.Query = cmdletContext.Query;
            }
            if (cmdletContext.Size != null)
            {
                request.Size = cmdletContext.Size.Value;
            }
            if (cmdletContext.Suggester != null)
            {
                request.Suggester = cmdletContext.Suggester;
            }

            CmdletOutput output;

            // issue call
            using (var client = CreateClient(cmdletContext.ServiceUrl))
            {
                try
                {
                    var    response       = CallAWSServiceOperation(client, request);
                    object pipelineOutput = cmdletContext.Select(response, this);
                    output = new CmdletOutput
                    {
                        PipelineOutput  = pipelineOutput,
                        ServiceResponse = response
                    };
                }
                catch (Exception e)
                {
                    output = new CmdletOutput {
                        ErrorResponse = e
                    };
                }

                return(output);
            }
        }
コード例 #24
0
        private static void TestSuggest(IOpenSearchAPI client)
        {
            var request = new SuggestRequest();

            request.AppName     = "helloworld";
            request.Hits        = 5;
            request.SuggestName = "hello_dropdown";
            request.Query       = "sousuo";

            var response = client.SuggestUsingPOST(request);

            if (response.Success.HasValue && response.Success.Value)
            {
                Console.WriteLine(response.Json);
            }
            else
            {
                Console.WriteLine(response.Error);
            }
        }
コード例 #25
0
        public void MissingParametersAreMissingInTheRequest()
        {
            var parameters = new SuggestParameters();

            // Search text and suggester name can never be null.
            SuggestRequest request = parameters.ToRequest("find me", "mySuggester");

            Assert.Null(request.Filter);
            Assert.Null(request.HighlightPostTag);
            Assert.Null(request.HighlightPreTag);
            Assert.Null(request.MinimumCoverage);
            Assert.Null(request.OrderBy);
            Assert.Equal("find me", request.SearchText);
            Assert.Null(request.SearchFields);
            Assert.Equal("*", request.Select);  // Nothing selected for Suggest means select everything.
            Assert.Equal("mySuggester", request.SuggesterName);
            Assert.Null(request.Top);
            Assert.True(request.UseFuzzyMatching.HasValue);
            Assert.False(request.UseFuzzyMatching.Value);  // Fuzzy is non-nullable in the client-side contract.
        }
コード例 #26
0
        public string[] Suggest(string collection, string bucket, string word, int?limit = null)
        {
            using (var session = this.CreateSession())
            {
                var request = new SuggestRequest(word, limit);

                session.Write("SUGGEST"
                              , collection
                              , bucket
                              , request.Word
                              , request.Limit
                              );

                var response = session.Read();
                Assert.IsTrue(response.StartsWith("PENDING"), "Expected pending marker", response);

                var marker = response.Substring("PENDING ".Length);

                return(this.ParseSuggestResponse(marker, session.Read()));
            }
        }
コード例 #27
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            SuggestRequest request;

            try
            {
                request = new SuggestRequest
                {
                    NamespaceName  = NamespaceName,
                    SuggestDetails = SuggestDetails,
                    OpcRequestId   = OpcRequestId
                };

                response = client.Suggest(request).GetAwaiter().GetResult();
                WriteOutput(response, response.SuggestOutput);
                FinishProcessing(response);
            }
            catch (Exception ex)
            {
                TerminatingErrorDuringExecution(ex);
            }
        }
コード例 #28
0
 public async Task <SuggestResponse <Address> > FindFias(SuggestRequest request)
 {
     return(await Execute <SuggestResponse <Address> >(method : SuggestionsMethod.Find, entity : SuggestionsEntity.Fias, request : request));
 }
コード例 #29
0
        public async Task <SuggestResponse <Email> > SuggestEmail(string query, int count = 5)
        {
            var request = new SuggestRequest(query, count);

            return(await SuggestEmail(request));
        }
コード例 #30
0
        public async Task <SuggestResponse <Address> > FindFias(string query)
        {
            var request = new SuggestRequest(query);

            return(await FindFias(request));
        }
コード例 #31
-1
		public SuggestRequestTests()
		{
			var request = new SuggestRequest()
			{
				AllIndices = true,
				AllowNoIndices = true,
				ExpandWildcards = ExpandWildcards.Closed,
				GlobalText = "global suggest text",
				Suggest = new Dictionary<string, ISuggester>
				{
					{ "terms_sug", new CompletionSuggester
					{
						Analyzer = "standard",
						Field = Property.Path<ElasticsearchProject>(p=>p.Content),
						Size = 4,
						ShardSize = 10,
						Fuzzy = new FuzzySuggester
						{
							Fuzziness = Fuzziness.Ratio(0.3),
							PrefixLength = 4
						}
					} 
					}
				}
			};
			var response = this._client.Suggest(request);
			this._status = response.ConnectionStatus;
		}