Exemplo n.º 1
0
		public SuggestionQueryResult ExecuteSuggestionQuery(string indexName, SuggestionQuery suggestionQuery)
		{
			if (suggestionQuery == null) throw new ArgumentNullException("suggestionQuery");
			if (string.IsNullOrWhiteSpace(suggestionQuery.Term)) throw new ArgumentNullException("suggestionQuery.Term");
			if (string.IsNullOrWhiteSpace(indexName)) throw new ArgumentNullException("indexName");
			if (string.IsNullOrWhiteSpace(suggestionQuery.Field)) throw new ArgumentNullException("suggestionQuery.Field");

			suggestionQuery.MaxSuggestions = Math.Min(suggestionQuery.MaxSuggestions, database.Configuration.MaxPageSize);

			if (suggestionQuery.MaxSuggestions <= 0) suggestionQuery.MaxSuggestions = SuggestionQuery.DefaultMaxSuggestions;
			if (suggestionQuery.Accuracy.HasValue && (suggestionQuery.Accuracy.Value <= 0f || suggestionQuery.Accuracy.Value > 1f))
				suggestionQuery.Accuracy = SuggestionQuery.DefaultAccuracy;

			if (suggestionQuery.Accuracy.HasValue == false)
				suggestionQuery.Accuracy = SuggestionQuery.DefaultAccuracy;
			if (suggestionQuery.Distance.HasValue == false)
				suggestionQuery.Distance = StringDistanceTypes.Default;

		    var definition = database.IndexDefinitionStorage.GetIndexDefinition(indexName);
			var indexExtensionKey =
				MonoHttpUtility.UrlEncode(suggestionQuery.Field + "-" + suggestionQuery.Distance + "-" + suggestionQuery.Accuracy);
			var indexExtension = database.IndexStorage.GetIndexExtensionByPrefix(indexName, indexExtensionKey) as SuggestionQueryIndexExtension;

			IndexSearcher currentSearcher;
			using (database.IndexStorage.GetCurrentIndexSearcher(definition.IndexId, out currentSearcher))
			{
				if (currentSearcher == null)
				{
					throw new InvalidOperationException("Could not find current searcher");
				}
				var indexReader = currentSearcher.IndexReader;

				if (indexExtension != null)
					return indexExtension.Query(suggestionQuery, indexReader);

				var suggestionQueryIndexExtension = new SuggestionQueryIndexExtension(
					database.WorkContext,
					Path.Combine(database.Configuration.IndexStoragePath, "Raven-Suggestions", indexName, indexExtensionKey),
					GetStringDistance(suggestionQuery.Distance ?? StringDistanceTypes.Default),
					indexReader.Directory() is RAMDirectory,
					suggestionQuery.Field,
					suggestionQuery.Accuracy ?? 0.5f);

				database.IndexStorage.SetIndexExtension(indexName, indexExtensionKey, suggestionQueryIndexExtension);

				long _;
				var task = Task.Factory.StartNew(() => suggestionQueryIndexExtension.Init(indexReader));
				database.Tasks.AddTask(task, new TaskBasedOperationState(task), new TaskActions.PendingTaskDescription
				                                           {
                                                               Payload = indexName,
                                                               TaskType = TaskActions.PendingTaskType.SuggestionQuery,
                                                               StartTime = SystemTime.UtcNow
				                                           }, out _);

				// wait for a bit for the suggestions to complete, but not too much (avoid IIS resets)
				task.Wait(15000, database.WorkContext.CancellationToken);

				return suggestionQueryIndexExtension.Query(suggestionQuery, indexReader);
			}
		}
		public SuggestionQueryResult Query(SuggestionQuery suggestionQuery)
		{
			if(suggestionQuery.Term.StartsWith("<<") && suggestionQuery.Term.EndsWith(">>"))
			{
				var individualTerms = suggestionQuery.Term.Substring(2, suggestionQuery.Term.Length - 4).Split(new[] {' ', '\t', '\r','\n'}, StringSplitOptions.RemoveEmptyEntries);
				var result = new List<string>();

				foreach (var term in individualTerms)
				{
					result.AddRange(spellChecker.SuggestSimilar(term,
					                                            suggestionQuery.MaxSuggestions,
					                                            null,
					                                            suggestionQuery.Field,
					                                            true));
				}

				return new SuggestionQueryResult
				{
					Suggestions = result.ToArray()
				};
			}
			string[] suggestions = spellChecker.SuggestSimilar(suggestionQuery.Term,
			                                                   suggestionQuery.MaxSuggestions,
			                                                   null,
			                                                   suggestionQuery.Field,
			                                                   true);

			return new SuggestionQueryResult
			{
				Suggestions = suggestions
			};
		}
Exemplo n.º 3
0
        /// <summary>
        /// Responds the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public override void Respond(IHttpContext context)
        {
            var match = urlMatcher.Match(context.GetRequestUrl());
            var index = match.Groups[1].Value;
            
            var term = context.Request.QueryString["term"];
            var field = context.Request.QueryString["field"];

            StringDistanceTypes distanceTypes;
            int numOfSuggestions;
            float accuracy;

            if (Enum.TryParse(context.Request.QueryString["distance"], true, out distanceTypes) == false)
                distanceTypes =StringDistanceTypes.Default;

            if (int.TryParse(context.Request.QueryString["max"], out numOfSuggestions) == false)
                numOfSuggestions = 10;

            if(float.TryParse(context.Request.QueryString["accuracy"], out accuracy) == false)
                accuracy = 0.5f;

            var query = new SuggestionQuery
                            {
                                Distance = distanceTypes,
                                Field = field,
                                MaxSuggestions = numOfSuggestions,
                                Term = term,
                                Accuracy = accuracy
                            };

            var suggestionQueryResult = Database.ExecuteSuggestionQuery(index, query);
            context.WriteJson(suggestionQueryResult);
        }
		public SuggestionQueryResult Query(SuggestionQuery suggestionQuery, IndexReader indexReader)
		{
			if (suggestionQuery.Accuracy.HasValue == false)
				throw new InvalidOperationException("SuggestionQuery.Accuracy must be specified.");

			if (suggestionQuery.Distance.HasValue == false)
				throw new InvalidOperationException("SuggestionQuery.Distance must be specified.");

			spellChecker.setStringDistance(SuggestionQueryRunner.GetStringDistance(suggestionQuery.Distance.Value));
			spellChecker.SetAccuracy(suggestionQuery.Accuracy.Value);

			if (suggestionQuery.Term.StartsWith("<<") && suggestionQuery.Term.EndsWith(">>"))
			{
				return QueryOverMultipleWords(suggestionQuery, indexReader,
					suggestionQuery.Term.Substring(2, suggestionQuery.Term.Length - 4));
			}
			if (suggestionQuery.Term.StartsWith("(") && suggestionQuery.Term.EndsWith(")"))
			{
				return QueryOverMultipleWords(suggestionQuery, indexReader,
					suggestionQuery.Term.Substring(1, suggestionQuery.Term.Length - 2));
			}
			string[] suggestions = spellChecker.SuggestSimilar(suggestionQuery.Term,
															   suggestionQuery.MaxSuggestions,
															   indexReader,
															   suggestionQuery.Field,
															   true);

			return new SuggestionQueryResult
			{
				Suggestions = suggestions
			};
		}
Exemplo n.º 5
0
		public static SuggestionQueryResult ExecuteSuggestionQuery(this DocumentDatabase self, string index, SuggestionQuery suggestionQuery)
		{
			if (index == "dynamic" || index.StartsWith("dynamic/", StringComparison.OrdinalIgnoreCase))
			{
				var entitName = index == "dynamic" ? null : index.Remove(0, "dynamic/".Length);
				index = self.FindDynamicIndexName(entitName, new IndexQuery
				{
					Query = suggestionQuery.Field + ":" + QuoteIfNeeded(suggestionQuery.Term)
				});
				if(string.IsNullOrEmpty(index))
					throw new InvalidOperationException("Could find no index for the specified query, suggestions will not create a dynamic index, and cannot suggest without an index. Did you forget to query before calling Suggest?");
			}

			var indexDefinition = self.GetIndexDefinition(index);
			if (indexDefinition == null)
				throw new InvalidOperationException(string.Format("Could not find specified index '{0}'.", index));

			if (indexDefinition.Suggestions.ContainsKey(suggestionQuery.Field) == false && self.Configuration.PreventAutomaticSuggestionCreation)
			{
				// if index does not have suggestions defined for this field and server configuration does not allow to create it on the fly
				// then just return empty result
				return new SuggestionQueryResult();
			}


			return new SuggestionQueryRunner(self).ExecuteSuggestionQuery(index, suggestionQuery);
		}
		public static SuggestionQueryResult ExecuteSuggestionQuery(this DocumentDatabase self, string index, SuggestionQuery suggestionQuery)
		{
			if (index == "dynamic" || index.StartsWith("dynamic/", StringComparison.OrdinalIgnoreCase))
			{
				throw new InvalidOperationException("Cannot get suggestions for dynamic indexes, only static indexes with explicitly defined Suggestions are supported");
			}
		    
            var indexDefinition = self.Indexes.GetIndexDefinition(index);
		    if (indexDefinition == null)
		        throw new InvalidOperationException(string.Format("Could not find specified index '{0}'.", index));

		    SuggestionOptions suggestion;
		    if (indexDefinition.Suggestions.TryGetValue(suggestionQuery.Field, out suggestion) == false)
		    {
		        throw new InvalidOperationException(string.Format("Index '{0}' does not have suggestions configured for field '{1}'.", index, suggestionQuery.Field));
		    }


		    if (suggestionQuery.Accuracy.HasValue == false)
		        suggestionQuery.Accuracy = suggestion.Accuracy;

		    if (suggestionQuery.Distance.HasValue == false)
		        suggestionQuery.Distance = suggestion.Distance;


		    return new SuggestionQueryRunner(self).ExecuteSuggestionQuery(index, suggestionQuery);
		}
Exemplo n.º 7
0
		public SuggestionQueryResult ExecuteSuggestionQuery(string indexName, SuggestionQuery suggestionQuery)
		{
			if (suggestionQuery == null) throw new ArgumentNullException("suggestionQuery");
			if (string.IsNullOrWhiteSpace(suggestionQuery.Term)) throw new ArgumentNullException("suggestionQuery.Term");
			if (string.IsNullOrWhiteSpace(indexName)) throw new ArgumentNullException("indexName");
			if (string.IsNullOrWhiteSpace(suggestionQuery.Field)) throw new ArgumentNullException("suggestionQuery.Field");
			if (suggestionQuery.MaxSuggestions <= 0) suggestionQuery.MaxSuggestions = 10;
			if (suggestionQuery.Accuracy <= 0 || suggestionQuery.Accuracy > 1) suggestionQuery.Accuracy = 0.5f;

			suggestionQuery.MaxSuggestions = Math.Min(suggestionQuery.MaxSuggestions,
													  _database.Configuration.MaxPageSize);

			var indexExtensionKey = suggestionQuery.Field + "/" + suggestionQuery.Distance + "/" + suggestionQuery.Accuracy;

			var indexExtension = _database.IndexStorage.GetIndexExtension(indexName, indexExtensionKey) as SuggestionQueryIndexExtension;

			if (indexExtension != null)
				return indexExtension.Query(suggestionQuery);


			IndexSearcher currentSearcher;
			using(_database.IndexStorage.GetCurrentIndexSearcher(indexName,out currentSearcher))
			{
				var indexReader = currentSearcher.GetIndexReader();

				var suggestionQueryIndexExtension = new SuggestionQueryIndexExtension(GetStringDistance(suggestionQuery), suggestionQuery.Field, suggestionQuery.Accuracy);
				suggestionQueryIndexExtension.Init(indexReader);

				_database.IndexStorage.SetIndexExtension(indexName, indexExtensionKey, suggestionQueryIndexExtension);

				return suggestionQueryIndexExtension.Query(suggestionQuery);
			}
		}
Exemplo n.º 8
0
		/// <summary>
		/// Responds the specified context.
		/// </summary>
		/// <param name="context">The context.</param>
		public override void Respond(IHttpContext context)
		{
			var match = urlMatcher.Match(context.GetRequestUrl());
			var index = match.Groups[1].Value;

			var indexEtag = Database.GetIndexEtag(index, null);
			if (context.MatchEtag(indexEtag))
			{
				context.SetStatusToNotModified();
				return;
			}

			var term = context.Request.QueryString["term"];
			var field = context.Request.QueryString["field"];

			StringDistanceTypes distanceTypes;
			int numOfSuggestions;
			float accuracy;

			if (Enum.TryParse(context.Request.QueryString["distance"], true, out distanceTypes) == false)
				distanceTypes = StringDistanceTypes.Default;

			if (distanceTypes == StringDistanceTypes.None)
			{
				context.SetStatusToBadRequest();
				context.WriteJson(new
				{
					Error = "Suggestion is disabled since you specified the Distance value as 'StringDistanceTypes.None'."
				});
				return;
			}

			if (int.TryParse(context.Request.QueryString["max"], out numOfSuggestions) == false)
				numOfSuggestions = 10;

			if (float.TryParse(context.Request.QueryString["accuracy"], out accuracy) == false)
				accuracy = 0.5f;

			bool popularity;
			if (bool.TryParse(context.Request.QueryString["popularity"], out popularity) == false)
				popularity = false;

			var query = new SuggestionQuery
			{
				Distance = distanceTypes,
				Field = field,
				MaxSuggestions = numOfSuggestions,
				Term = term,
				Accuracy = accuracy,
				Popularity = popularity
			};

			var suggestionQueryResult = Database.ExecuteSuggestionQuery(index, query);
			context.WriteETag(Database.GetIndexEtag(index, null));
			context.WriteJson(suggestionQueryResult);
		}
Exemplo n.º 9
0
		public SuggestionQueryResult ExecuteSuggestionQuery(string indexName, SuggestionQuery suggestionQuery)
		{
			if (suggestionQuery == null) throw new ArgumentNullException("suggestionQuery");
			if (string.IsNullOrWhiteSpace(suggestionQuery.Term)) throw new ArgumentNullException("suggestionQuery.Term");
			if (string.IsNullOrWhiteSpace(indexName)) throw new ArgumentNullException("indexName");
			if (string.IsNullOrWhiteSpace(suggestionQuery.Field)) throw new ArgumentNullException("suggestionQuery.Field");
			if (suggestionQuery.MaxSuggestions <= 0) suggestionQuery.MaxSuggestions = 10;
			if (suggestionQuery.Accuracy <= 0 || suggestionQuery.Accuracy > 1) suggestionQuery.Accuracy = 0.5f;

			suggestionQuery.MaxSuggestions = Math.Min(suggestionQuery.MaxSuggestions,
													  database.Configuration.MaxPageSize);

			var indexExtensionKey = MonoHttpUtility.UrlEncode(suggestionQuery.Field + "-" + suggestionQuery.Distance + "-" + suggestionQuery.Accuracy);

			var indexExtension = (
				                     database.IndexStorage.GetIndexExtension(indexName, indexExtensionKey) ??
									 database.IndexStorage.GetIndexExtensionByPrefix(indexName, MonoHttpUtility.UrlEncode(suggestionQuery.Field +"-"+suggestionQuery.Distance)) ??
									 database.IndexStorage.GetIndexExtensionByPrefix(indexName, MonoHttpUtility.UrlEncode(suggestionQuery.Field)) 
			                     ) as SuggestionQueryIndexExtension;


			IndexSearcher currentSearcher;
			using (database.IndexStorage.GetCurrentIndexSearcher(indexName, out currentSearcher))
			{
				if (currentSearcher == null)
				{
					throw new InvalidOperationException("Could not find current searcher");
				}
				var indexReader = currentSearcher.IndexReader;

				if (indexExtension != null)
					return indexExtension.Query(suggestionQuery, indexReader);


				var suggestionQueryIndexExtension = new SuggestionQueryIndexExtension(
					database.WorkContext,
					Path.Combine(database.Configuration.IndexStoragePath, "Raven-Suggestions", indexName, indexExtensionKey),
					indexReader.Directory() is RAMDirectory,
					GetStringDistance(suggestionQuery.Distance),
					suggestionQuery.Field,
					suggestionQuery.Accuracy);

				database.IndexStorage.SetIndexExtension(indexName, indexExtensionKey, suggestionQueryIndexExtension);

				long _;
				var task = Task.Factory.StartNew(() => suggestionQueryIndexExtension.Init(indexReader));
				database.AddTask(task, new object(), out _);

				// wait for a bit for the suggestions to complete, but not too much (avoid IIS resets)
				task.Wait(15000, database.WorkContext.CancellationToken);

				return suggestionQueryIndexExtension.Query(suggestionQuery, indexReader);
			}
		}
Exemplo n.º 10
0
		private static StringDistance GetStringDistance(SuggestionQuery query)
		{
			switch (query.Distance)
			{
				case StringDistanceTypes.NGram:
					return new NGramDistance();
				case StringDistanceTypes.JaroWinkler:
					return new JaroWinklerDistance();
				default:
					return new LevenshteinDistance();
			}
		}
Exemplo n.º 11
0
		public HttpResponseMessage SuggestGet(string id)
		{
			var index = id;

			var indexEtag = Database.Indexes.GetIndexEtag(index, null);
			if (MatchEtag(indexEtag))
				return GetEmptyMessage(HttpStatusCode.NotModified);

			var term = GetQueryStringValue("term");
			var field = GetQueryStringValue("field");

			StringDistanceTypes distanceTypes;
			int numOfSuggestions;
			float accuracy;

			if (Enum.TryParse(GetQueryStringValue("distance"), true, out distanceTypes) == false)
				distanceTypes = StringDistanceTypes.Default;

			if (distanceTypes == StringDistanceTypes.None)
			{
				return GetMessageWithObject(new
				{
					Error = "Suggestion is disabled since you specified the Distance value as 'StringDistanceTypes.None'."
				}, HttpStatusCode.BadRequest);
			}

			if (int.TryParse(GetQueryStringValue("max"), out numOfSuggestions) == false)
				numOfSuggestions = 10;

			if (float.TryParse(GetQueryStringValue("accuracy"),NumberStyles.AllowDecimalPoint,CultureInfo.InvariantCulture, out accuracy) == false)
				accuracy = 0.5f;

			bool popularity;
			if (bool.TryParse(GetQueryStringValue("popularity"), out popularity) == false)
				popularity = false;

			var query = new SuggestionQuery
			{
				Distance = distanceTypes,
				Field = field,
				MaxSuggestions = numOfSuggestions,
				Term = term,
				Accuracy = accuracy,
				Popularity = popularity
			};

			var suggestionQueryResult = Database.ExecuteSuggestionQuery(index, query);

			var msg = GetMessageWithObject(suggestionQueryResult);
			WriteETag(Database.Indexes.GetIndexEtag(index, null), msg);
			return msg;
		}
		public SuggestionQueryResult Query(SuggestionQuery suggestionQuery)
		{
			var suggestions = spellChecker.SuggestSimilar(suggestionQuery.Term,
			                                              suggestionQuery.MaxSuggestions,
			                                              null,
			                                              suggestionQuery.Field,
			                                              true);

			return new SuggestionQueryResult
			{
				Suggestions = suggestions
			};
		}
Exemplo n.º 13
0
		public static SuggestionQueryResult ExecuteSuggestionQuery(this DocumentDatabase self, string index, SuggestionQuery suggestionQuery)
		{
			if (index == "dynamic" || index.StartsWith("dynamic/", StringComparison.InvariantCultureIgnoreCase))
			{
				var entitName = index == "dynamic" ? null : index.Remove(0, "dynamic/".Length);
				index = self.FindDynamicIndexName(entitName, new IndexQuery
				{
					Query = suggestionQuery.Field + ":" + QouteIfNeeded(suggestionQuery.Term)
				});
				if(string.IsNullOrEmpty(index))
					throw new InvalidOperationException("Could find no index for the specified query, suggestions will not create a dynamic index, and cannot suggest without an index. Did you forget to query before calling Suggest?");
			}

			return new SuggestionQueryRunner(self).ExecuteSuggestionQuery(index, suggestionQuery);
		}
Exemplo n.º 14
0
        public SuggestionQueryResult ExecuteSuggestionQuery(string indexName, SuggestionQuery suggestionQuery)
        {
            if (suggestionQuery == null) throw new ArgumentNullException("suggestionQuery");
            if (string.IsNullOrWhiteSpace(suggestionQuery.Term)) throw new ArgumentNullException("suggestionQuery.Term");
            if (string.IsNullOrWhiteSpace(indexName)) throw new ArgumentNullException("indexName");
            if (string.IsNullOrWhiteSpace(suggestionQuery.Field)) throw new ArgumentNullException("suggestionQuery.Field");
            if (suggestionQuery.MaxSuggestions <= 0) suggestionQuery.MaxSuggestions = 10;
            if (suggestionQuery.Accuracy <= 0 || suggestionQuery.Accuracy > 1) suggestionQuery.Accuracy = 0.5f;

            suggestionQuery.MaxSuggestions = Math.Min(suggestionQuery.MaxSuggestions,
                                                      _database.Configuration.MaxPageSize);

            var currentSearcher = _database.IndexStorage.GetCurrentIndexSearcher(indexName);
            IndexSearcher searcher;
            using(currentSearcher.Use(out searcher))
            {
                var indexReader = searcher.GetIndexReader();

                var spellChecker = new SpellChecker.Net.Search.Spell.SpellChecker(new RAMDirectory(), GetStringDistance(suggestionQuery));
                try
                {
                    spellChecker.IndexDictionary(new LuceneDictionary(indexReader, suggestionQuery.Field));
                    spellChecker.SetAccuracy(suggestionQuery.Accuracy);

                    var suggestions = spellChecker.SuggestSimilar(suggestionQuery.Term, 
                        suggestionQuery.MaxSuggestions,
                        indexReader,
                        suggestionQuery.Field, 
                        true);

                    return new SuggestionQueryResult
                    {
                        Suggestions = suggestions
                    };
                }
                finally
                {
                    spellChecker.Close();
                    // this is really stupid, but it doesn't handle this in its close method!
                    GC.SuppressFinalize(spellChecker);
                }
            }
            
        }
Exemplo n.º 15
0
		public SuggestionQueryResult ExecuteSuggestionQuery(string indexName, SuggestionQuery suggestionQuery)
		{
			if (suggestionQuery == null) throw new ArgumentNullException("suggestionQuery");
			if (string.IsNullOrWhiteSpace(suggestionQuery.Term)) throw new ArgumentNullException("suggestionQuery.Term");
			if (string.IsNullOrWhiteSpace(indexName)) throw new ArgumentNullException("indexName");
			if (string.IsNullOrWhiteSpace(suggestionQuery.Field)) throw new ArgumentNullException("suggestionQuery.Field");
			if (suggestionQuery.MaxSuggestions <= 0) suggestionQuery.MaxSuggestions = 10;
			if (suggestionQuery.Accuracy <= 0 || suggestionQuery.Accuracy > 1) suggestionQuery.Accuracy = 0.5f;

			suggestionQuery.MaxSuggestions = Math.Min(suggestionQuery.MaxSuggestions,
													  _database.Configuration.MaxPageSize);

			var indexExtensionKey = MonoHttpUtility.UrlEncode(suggestionQuery.Field + "-" + suggestionQuery.Distance + "-" + suggestionQuery.Accuracy);

			var indexExtension = _database.IndexStorage.GetIndexExtension(indexName, indexExtensionKey) as SuggestionQueryIndexExtension;


			IndexSearcher currentSearcher;
			using (_database.IndexStorage.GetCurrentIndexSearcher(indexName, out currentSearcher))
			{
				if (currentSearcher == null)
				{
					throw new InvalidOperationException("Could not find current searcher");
				}
				var indexReader = currentSearcher.IndexReader;

				if (indexExtension != null)
					return indexExtension.Query(suggestionQuery, indexReader);


				var suggestionQueryIndexExtension = new SuggestionQueryIndexExtension(
					Path.Combine(_database.Configuration.IndexStoragePath, "Raven-Suggestions", indexName, indexExtensionKey),
					indexReader,
					GetStringDistance(suggestionQuery.Distance),
					suggestionQuery.Field,
					suggestionQuery.Accuracy);
				suggestionQueryIndexExtension.Init(indexReader);

				_database.IndexStorage.SetIndexExtension(indexName, indexExtensionKey, suggestionQueryIndexExtension);

				return suggestionQueryIndexExtension.Query(suggestionQuery, indexReader);
			}
		}
		private SuggestionQueryResult QueryOverMultipleWords(SuggestionQuery suggestionQuery, IndexReader indexReader,
		                                                     string queryText)
		{
			var individualTerms = queryText.Split(new[] {' ', '\t', '\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);
			var result = new List<string>();

			foreach (var term in individualTerms)
			{
				result.AddRange(spellChecker.SuggestSimilar(term,
				                                            suggestionQuery.MaxSuggestions,
				                                            indexReader,
				                                            suggestionQuery.Field,
				                                            suggestionQuery.Popularity));
			}

			return new SuggestionQueryResult
			{
				Suggestions = result.ToArray()
			};
		}
		public SuggestionQueryResult Query(SuggestionQuery suggestionQuery, IndexReader indexReader)
		{
			if(suggestionQuery.Term.StartsWith("<<") && suggestionQuery.Term.EndsWith(">>"))
			{
				return QueryOverMultipleWords(suggestionQuery, indexReader, 
					suggestionQuery.Term.Substring(2, suggestionQuery.Term.Length - 4));
			}
			if (suggestionQuery.Term.StartsWith("(") && suggestionQuery.Term.EndsWith(")"))
			{
				return QueryOverMultipleWords(suggestionQuery, indexReader,
					suggestionQuery.Term.Substring(1, suggestionQuery.Term.Length - 2));
			}
			string[] suggestions = spellChecker.SuggestSimilar(suggestionQuery.Term,
			                                                   suggestionQuery.MaxSuggestions,
			                                                   indexReader, 
			                                                   suggestionQuery.Field,
			                                                   true);

			return new SuggestionQueryResult
			{
				Suggestions = suggestions
			};
		}
Exemplo n.º 18
0
		public Task<SuggestionQueryResult> SuggestAsync(string index, SuggestionQuery suggestionQuery)
		{
			return new CompletedTask<SuggestionQueryResult>(databaseCommands.Suggest(index, suggestionQuery));
		}
Exemplo n.º 19
0
		/// <summary>
		/// Returns a list of suggestions based on the specified suggestion query.
		/// </summary>
		/// <param name="index">The index to query for suggestions</param>
		/// <param name="suggestionQuery">The suggestion query.</param>
		public Task<SuggestionQueryResult> SuggestAsync(string index, SuggestionQuery suggestionQuery)
		{
			if (suggestionQuery == null) throw new ArgumentNullException("suggestionQuery");

			var requestUri = url + string.Format("/suggest/{0}?term={1}&field={2}&max={3}&distance={4}&accuracy={5}",
				Uri.EscapeUriString(index),
				Uri.EscapeDataString(suggestionQuery.Term),
				Uri.EscapeDataString(suggestionQuery.Field),
				Uri.EscapeDataString(suggestionQuery.MaxSuggestions.ToInvariantString()),
				Uri.EscapeDataString(suggestionQuery.Distance.ToString()),
				Uri.EscapeDataString(suggestionQuery.Accuracy.ToInvariantString()));

			var request = jsonRequestFactory.CreateHttpJsonRequest(
				new CreateHttpJsonRequestParams(this, requestUri, "GET", credentials, convention)
					.AddOperationHeaders(OperationsHeaders));
			
			return request.ReadResponseJsonAsync()
				.ContinueWith(task =>
				{
					var json = (RavenJObject) task.Result;
					return new SuggestionQueryResult
					{
						Suggestions = ((RavenJArray) json["Suggestions"]).Select(x => x.Value<string>()).ToArray(),
					};
				});
		}
Exemplo n.º 20
0
		public LazySuggestOperation(string index, SuggestionQuery suggestionQuery)
		{
			this.index = index;
			this.suggestionQuery = suggestionQuery;
		}
		private SuggestionQueryResult QueryOverMultipleWords(SuggestionQuery suggestionQuery, IndexReader indexReader,
															 string queryText)
		{
			var individualTerms = queryText.Split(new[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

			var result = new HashSet<string>();
			var maxSuggestions = suggestionQuery.MaxSuggestions;
			foreach (var term in individualTerms)
			{
				if (maxSuggestions <= 0) 
					break;

				foreach (var suggestion in spellChecker.SuggestSimilar(term,
															suggestionQuery.MaxSuggestions, // we can filter out duplicates, so taking more
															indexReader,
															suggestionQuery.Field,
															suggestionQuery.Popularity))
				{
					if (result.Add(suggestion) == false)
						continue;

					maxSuggestions--;
					if (maxSuggestions <= 0)
						break;
				}
			}

			return new SuggestionQueryResult
			{
				Suggestions = result.ToArray()
			};
		}
Exemplo n.º 22
0
 public SuggestionQueryResult ExecuteSuggestionQuery(string index, SuggestionQuery suggestionQuery)
 {
     return suggestionQueryRunner.ExecuteSuggestionQuery(index, suggestionQuery);
 }
Exemplo n.º 23
0
		public static SuggestionQueryResult ExecuteSuggestionQuery(this DocumentDatabase self, string index, SuggestionQuery suggestionQuery)
		{
			return new SuggestionQueryRunner(self).ExecuteSuggestionQuery(index, suggestionQuery);
		}
Exemplo n.º 24
0
		/// <summary>
		/// Returns a list of suggestions based on the specified suggestion query.
		/// </summary>
		/// <param name="index">The index to query for suggestions</param>
		/// <param name="suggestionQuery">The suggestion query.</param>
		public Task<SuggestionQueryResult> SuggestAsync(string index, SuggestionQuery suggestionQuery)
		{
			if (suggestionQuery == null) throw new ArgumentNullException("suggestionQuery");

			var requestUri = url + string.Format("/suggest/{0}?term={1}&field={2}&max={3}&distance={4}&accuracy={5}",
				Uri.EscapeUriString(index),
				Uri.EscapeDataString(suggestionQuery.Term),
				Uri.EscapeDataString(suggestionQuery.Field),
				Uri.EscapeDataString(suggestionQuery.MaxSuggestions.ToString()),
				Uri.EscapeDataString(suggestionQuery.Distance.ToString()),
				Uri.EscapeDataString(suggestionQuery.Accuracy.ToString()));

			var request = HttpJsonRequest.CreateHttpJsonRequest(this, requestUri, "GET", credentials, convention);
			request.AddOperationHeaders(OperationsHeaders);
			var serializer = convention.CreateSerializer();

			return Task.Factory.FromAsync<string>(request.BeginReadResponseString, request.EndReadResponseString, null)
				.ContinueWith(task =>
				{
					using (var reader = new JsonTextReader(new StringReader(task.Result)))
					{
						var json = (JToken)serializer.Deserialize(reader);
						return new SuggestionQueryResult
						{
							Suggestions = json["Suggestions"].Children().Select(x => x.Value<string>()).ToArray(),
						};
					}
				});
		}
Exemplo n.º 25
0
        public ActionResult SuggestSearch( string query )
        {
            if (!string.IsNullOrWhiteSpace(query))
            {
                var suggestionQuery = new SuggestionQuery()
                {
                    Accuracy = 0.5f,
                    Distance = StringDistanceTypes.Default,
                    Field = "FullText",
                    MaxSuggestions = 8,
                    Term = query
                };

                var result = DocumentSession.Advanced.DatabaseCommands.Suggest(new FullTextIndex().IndexName,
                                                                               suggestionQuery);

                if (result != null && result.Suggestions != null)
                {
                    return Json(result.Suggestions, JsonRequestBehavior.AllowGet);
                }
            }

            return Json(new string[0], JsonRequestBehavior.AllowGet);
        }