Skip to content

Instantly share code, notes, and snippets.

@casper-rasmussen
Created March 26, 2016 13:47
Show Gist options
  • Save casper-rasmussen/225779f1f69474fa1109 to your computer and use it in GitHub Desktop.
Save casper-rasmussen/225779f1f69474fa1109 to your computer and use it in GitHub Desktop.
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