Created
March 26, 2016 13:47
-
-
Save casper-rasmussen/225779f1f69474fa1109 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static IQueriedSearch<T> AddMatchingQueryStringFor<T>(this ITypeSearch<T> search, string queryString, Expression<Func<T, string>> fieldSelector) | |
{ | |
var fieldName = search.Client.Conventions.FieldNameConvention | |
.GetFieldNameForAnalyzed(fieldSelector); | |
//Split words by space | |
string[] words = queryString.Split(' '); | |
return new Search<T, WildcardQuery>(search, context => | |
{ | |
var boolQuery = new BoolQuery(); | |
//Make sure to add existing query to our bool query as a required condition | |
if (context.RequestBody.Query != null) | |
boolQuery.Must.Add(context.RequestBody.Query); | |
foreach (string word in words) | |
{ | |
//Add a wild card query for each word. Stars represents that is matches the single word | |
var wildcardQuery = new WildcardQuery(fieldName, String.Format("*{0}*", word.ToLowerInvariant())); | |
boolQuery.Should.Add(wildcardQuery); | |
} | |
//Require none off our should match points, as these are optional but may mean that a result is included | |
boolQuery.MinimumNumberShouldMatch = 0; | |
context.RequestBody.Query = boolQuery; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment