Guest User

Untitled

a guest
Nov 16th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. public static class SearchExtensions
  2. {
  3. public static ITypeSearch<T> FuzzyMatch<T>(this ITypeSearch<T> search, string term, Expression<Func<T, string>> fieldSelector, double? boost = null)
  4. where T : IContent
  5. {
  6. // fetch fieldName for query to be applied on by given fieldSelector.
  7. var fieldName = search.Client.Conventions.FieldNameConvention.GetFieldNameForAnalyzed(fieldSelector);
  8.  
  9. // if term is empty or there is no such field as given, return existing search query.
  10. if (string.IsNullOrWhiteSpace(term) || fieldName == null)
  11. {
  12. return search;
  13. }
  14.  
  15. var fuzzyQuery = new FuzzyQuery(fieldName, term)
  16. {
  17. Boost = boost,
  18. MinSimilarity = Constants.Search.Settings.FuzzyQueryMinSimilarity
  19. };
  20.  
  21. return new Search<T, IQuery>(search, context =>
  22. {
  23. // if current search context contains a query, we need to combine existing query with fuzzy query we created.
  24. if (context.RequestBody.Query != null)
  25. {
  26. var boolQuery = new BoolQuery
  27. {
  28. MinimumNumberShouldMatch = 1
  29. };
  30.  
  31. // combine existing query and fuzzy query
  32. boolQuery.Should.Add(context.RequestBody.Query);
  33. boolQuery.Should.Add(fuzzyQuery);
  34. context.RequestBody.Query = boolQuery;
  35. }
  36. else
  37. {
  38. context.RequestBody.Query = fuzzyQuery;
  39. }
  40. });
  41. }
  42. }
Add Comment
Please, Sign In to add comment