7

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

walther
  • 13,466
  • 5
  • 41
  • 67
kendaleiv
  • 5,793
  • 3
  • 28
  • 38

2 Answers2

4

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

Community
  • 1
  • 1
kendaleiv
  • 5,793
  • 3
  • 28
  • 38
0

What is it that you are trying to do? You are probably better off using an analyzed field and then issuing a .Search rather than a .Where.

Ayende Rahien
  • 22,925
  • 1
  • 36
  • 41
  • I don't think `.Search` will do what I want, I want to return _John Doe_ when the search string is _Jo_, _Do_, _Jo Doe_, _Jo Do_. I don't think `.Search` will return _John Doe_ unless I match one of the analyzed terms? – kendaleiv Jun 27 '12 at 14:21
  • Just to clarify, I mean when the search string is **any of**. – kendaleiv Jun 27 '12 at 19:34