Skip to content

Instantly share code, notes, and snippets.

@tarnacious
Created November 28, 2011 06:47
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tarnacious/1399392 to your computer and use it in GitHub Desktop.
Save tarnacious/1399392 to your computer and use it in GitHub Desktop.
Searching for multiple terms using the Umbraco Examine API.
// This seems way too difficult for what you would expect to be a pretty common task;
// taking a search string from the user and finding documents which contain some or all of the terms
// in the search string.
// This function naively splits a search string into terms and finds documents
// which contain some or all of the terms. Does not handle quoted terms as or ignore case as it should.
public IEnumerable<SearchResult> Search(string searchString, string[] fields)
{
// Spit the search string and return an empty list if no search string was provided.
if (string.IsNullOrEmpty(searchString)) return new List<SearchResult>();
string[] terms = searchString.Split(' ');
// For the GroupOr function we need two lists:
// 1) The first containing fields to search
// 2) The second with search terms to find in the field at the same index in the first list
// So.. if we have more than one search term we need to add every combination of search term and
// field to the lists.
// Eg. If we have two fields and two search terms our list should look like this
// searchFields = [Field1, Field2, Field1, Field2]
// searchTerms = [Term1, Term1, Term2, Term2]
var searchFields = new List<string>();
var searchTerms = new List<string>();
foreach(var t in terms) {
searchTerms.AddRange(fields.Select(_ => t));
searchFields.AddRange(fields);
}
// Pass our lists to GroupOr, compile and execute the search.
var query = ExamineManager.Instance.CreateSearchCriteria().GroupedOr(searchFields, searchTerms.ToArray());
var search = ExamineManager.Instance.Search(query.Compile());
// Map the results into a basic search result stucture
var results = search.Select(m => new SearchResult()
{
Title = m.Fields["nodeName"],
NodeId = m.Id,
Url = umbraco.library.NiceUrl(m.Id),
Score = m.Score,
DateUpdated = DateTime.Parse(m.Fields["updateDate"]).ToString("dd MMM, yyy")
});
// Filtering and maybe paging if required.
return results.Where(m => !string.IsNullOrEmpty(m.Url));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment