Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform search for multiple terms in Sitecore 7 ContentSearch API?

I am exploring the new Sitecore.ContentSearch "LINQ to Sitecore" API in Sitecore 7. It is my understanding that Sitecore recommends using the new LINQ API over the existing Sitecore.Search API, however, I am struggling to perform even the simplest of queries.

Take for instance the following search query: "hello world".

Using the Sitecore.Search API, the terms "hello world" would typically be passed through a QueryParser which would result in documents matching the word "hello" OR "world". Documents containing both terms would be scored higher that those with just one.

How does one perform this same query using LINQ?

Here's what I have tried:

var results = SearchContext.GetQueryable<MyResultItem>();

var terms = searchTerm.Split(' ');

// Not supported exception
results = results.Where(r => terms.Any(t => r.Content.Contains(r)));

// Close, but performs an "AND" between terms, and does not appear
// to score documents properly
foreach (var term in terms)
{
    results = results.Where(r => r.Content.Contains(t));
}

UPDATE

I am convinced that I am missing something really simple. Surely with all the work that went into the new search API, this simple use case wasn't overlooked... right?

As a workaround, I tried opening the default sitecore_web_index using the existing SearchManager, however, this does not work.

Unfortunately, I have had to resort to the existing API until I can figure this out. I will be sure to update this question with my findings.

UPDATE 2

I found the Sitecore.ContentSearch.Utilities.LinqHelper class which partially solves the problem. You can use it to dynamically build a query similar to a BooleanQuery in Lucene.Net, however, it's options are limited and it adds a bit of performance overhead.

like image 224
Derek Hunziker Avatar asked Jun 23 '13 03:06

Derek Hunziker


1 Answers

All of the predicate builders I tried didn't work, however, Sitecore 7 ships with a PredicateBuilder of it's own that did the trick.

using Sitecore.ContentSearch;
using Sitecore.ContentSearch.Linq;
using Sitecore.ContentSearch.SearchTypes;
using Sitecore.ContentSearch.Utilities;
// Sitecore 7 (Update 1+): using Sitecore.ContentSearch.Linq.Utilities;

...

var index = ContentSearchManager.GetIndex("sitecore_web_index");
using (var context = index.CreateSearchContext())
{
    var predicate = PredicateBuilder.True<SearchResultItem>();
    foreach (var t in term.Split(' '))
    {
        var tempTerm = t;
        predicate = predicate.Or(p => p.Content.Contains(tempTerm));
    }

    var results = context.GetQueryable<SearchResultItem>().Where(predicate).GetResults();

    ...
}
like image 143
Derek Hunziker Avatar answered Oct 18 '22 19:10

Derek Hunziker