Is there a recommended way to search for each of multiple terms using StartsWith when the terms are not known at compile time?
I envision something like this:
var searchTerms = "John Doe".Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var query = session.Query<Person, PersonIndex>()
.Where(x => x.FirstName.StartsWithAnyOf(searchTerms) ||
x.LastName.StartsWithAnyOf(searchTerms));
The query would be the equivalent of:
var query = session.Query<Person, PersonIndex>()
.Where(x => x.FirstName.Starts(searchTerms[0]) ||
x.LastName.StartsWith(searchTerms[0]) ||
x.FirstName.Starts(searchTerms[1]) ||
x.LastName.StartsWith(searchTerms[1]));
Is the answer to build a LINQ query at runtime (PredicateBuilder or similar)?
Using LuceneQuery (may want to use a subclause depending on what else you are doing):
var searchTerms = "John Doe".Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var query = session.Advanced.LuceneQuery<Person, PersonIndex>();
query = query.OpenSubclause(); // optional
foreach (var term in terms)
{
query = query.WhereStartsWith("FirstName"), term).OrElse();
query = query.WhereStartsWith("LastName"), term).OrElse();
}
query = query.WhereEquals("Id", null);
query = query.CloseSubclause(); // if OpenSubclause() was used
If you want strongly typed variable names check out this answer: https://stackoverflow.com/a/301957/941536
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With