Session: Querying: How to Use Search

Use the Search() extension method to perform a full-text search on a particular field. Search() accepts a string containing the desired search terms separated by spaces. These search terms are matched with the terms in the index being queried.

An index's terms are derived from the values of the documents' textual fields. These values were converted into one or more terms depending on which Lucene analyzer the index used.

Syntax

IRavenQueryable<T> Search<T>(
        Expression<Func<T, object>> fieldSelector,
        string searchTerms,
        decimal boost = 1,
        SearchOptions options = SearchOptions.Guess,
        SearchOperator @operator = SearchOperator.Or)
Parameters Type Description
fieldSelector Expression<Func<TResult>> Points index field that should be used for querying.
searchTerms string A string of the desired search terms separated by spaces (i.e. to search for "john" or "jack", pass the string "john jack").
Wildcards can be used: ? for any single character, * for any substring.
boost decimal Boost value. Default: 1.
options SearchOptions Set the operator between this Search method and the preceding extension method in the query. Can be set to one of the following: Or, And, Not, Guess. Default: SearchOptions.Guess.
@operator SearchOperator The operator between the individual terms. Can be set to Or or And. Default: SearchOperation.Or.

Example I - Dynamic Query

List<User> users = session
    .Query<User>()
    .Search(u => u.Name, "a*")
    .ToList();
List<User> users = await asyncSession
    .Query<User>()
    .Search(u => u.Name, "a*")
    .ToListAsync();
from Users 
where search(Name, 'a*')

Example II - Query Using Static Index

List<User> users = session
    .Query<User, Users_ByNameAndHobbies>()
    .Search(x => x.Name, "Steve")
    .Search(x => x.Hobbies, "sport")
    .ToList();
List<User> users = await asyncSession
    .Query<User, Users_ByNameAndHobbies>()
    .Search(x => x.Name, "Steve")
    .Search(x => x.Hobbies, "sport")
    .ToListAsync();
from index 'Users/ByNameAndHobbies' 
where search(Name, 'Steve') or search(Hobbies, 'sport')

Example III - Boosting Usage

List<User> users = session
    .Query<User>("Users/ByHobbies")
    .Search(x => x.Hobbies, "I love sport", boost: 10)
    .Search(x => x.Hobbies, "but also like reading books", boost: 5)
    .ToList();
List<User> users = await asyncSession
    .Query<User>("Users/ByHobbies")
    .Search(x => x.Hobbies, "I love sport", boost: 10)
    .Search(x => x.Hobbies, "but also like reading books", boost: 5)
    .ToListAsync();
from index 'Users/ByHobbies' 
where boost(search(Hobbies, 'I love sport'), 10) or boost(search(Hobbies, 'but also like reading books'), 5)

Note

To leverage the searching capabilities with the usage of static indexes, please remember to enable full-text search in field settings of the index definition.