Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static class SearchExtensions
- {
- public static ITypeSearch<T> FuzzyMatch<T>(this ITypeSearch<T> search, string term, Expression<Func<T, string>> fieldSelector, double? boost = null)
- where T : IContent
- {
- // fetch fieldName for query to be applied on by given fieldSelector.
- var fieldName = search.Client.Conventions.FieldNameConvention.GetFieldNameForAnalyzed(fieldSelector);
- // if term is empty or there is no such field as given, return existing search query.
- if (string.IsNullOrWhiteSpace(term) || fieldName == null)
- {
- return search;
- }
- var fuzzyQuery = new FuzzyQuery(fieldName, term)
- {
- Boost = boost,
- MinSimilarity = Constants.Search.Settings.FuzzyQueryMinSimilarity
- };
- return new Search<T, IQuery>(search, context =>
- {
- // if current search context contains a query, we need to combine existing query with fuzzy query we created.
- if (context.RequestBody.Query != null)
- {
- var boolQuery = new BoolQuery
- {
- MinimumNumberShouldMatch = 1
- };
- // combine existing query and fuzzy query
- boolQuery.Should.Add(context.RequestBody.Query);
- boolQuery.Should.Add(fuzzyQuery);
- context.RequestBody.Query = boolQuery;
- }
- else
- {
- context.RequestBody.Query = fuzzyQuery;
- }
- });
- }
- }
Add Comment
Please, Sign In to add comment