AndreasElffors
AndreasElffors

Reputation: 107

RavenDB Query with unknown amount of arguments?

I'm trying to implement search functionality for an application and i'd like to make a query which can take an unkown amount of arguments/search terms.

for example, if i've got two arguments i'd like something like this.

            using (IDocumentSession session = RavenDbConfig.RavenDBDocumentStore.OpenSession())
        {

                var searchresults = session.Query<Contact>()
                    .Where(x => x.Firstname.StartsWith("searchArgument1") || x.Firstname.StartsWith("searchArgument2"))
                    .ToList();
        }

... and so on.

So is this possible? If not, how would you approach a problem where you don't know how many search terms the user wants to use to search for something?

Upvotes: 0

Views: 54

Answers (1)

Jens Pettersson
Jens Pettersson

Reputation: 1177

You can append more where clauses to your query before enumerating it. I think you have to use the DocumentQuery<> to be able to do what you want (or maybe the Search() feature, not quite sure):

using (var session = _documentStore.OpenSession())
{
    var query = session.Advanced.DocumentQuery<Contact>()
        .WhereStartsWith(x => x.FirstName, "searchArgument1");

    if(hasSearchArgument2)
        query = query.WhereStartsWith(x => x.FirstName, "searchArgument2");

    var contacts = query.ToList();
}

This will return all documents with FirstName that starts with either searchArgument1 or searchArgument2.

The Lucene query that gets executed in the above example looks like:

{FirstName:searchArgument1* FirstName:searchArgument2*}

Read more about DocumentQuery<> here: http://ravendb.net/docs/article-page/3.0/csharp/indexes/querying/query-vs-document-query

Also, read about Search as it might be more suited for your situation: http://ravendb.net/docs/article-page/3.0/csharp/indexes/querying/searching

Hope this helps!

Upvotes: 1

Related Questions