Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RavenDB search for each of multiple terms using StartsWith

Tags:

c#

linq

ravendb

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)?

like image 813
kendaleiv Avatar asked Jun 26 '12 13:06

kendaleiv


1 Answers

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

like image 87
kendaleiv Avatar answered Oct 07 '22 00:10

kendaleiv