Search code examples
c#.netsearchepiserver

EpiServer Basic Filtering of Arbitrary Amount of Values


Consider the following search:

return SearchClient.Instance.UnifiedSearchFor(Request.Query)
.Filter(x => ((IContent)x).Ancestors().Match([ANCESTOR ID]))
.GetResult();

This works fine, as long as there is only one ANCESTOR ID to match with. There aren't, there are multiple - but I'm not sure of how many exactly.

How can I perform multiple filters on this result set?

What I've Tried

var query = SearchClient.Instance.UnifiedSearchFor(Request.Query);

[ANCESTOR IDS].ForEach(o => query.Filter(x => ((IContent)x).Ancestors().Match(o.ToString())));

return query.Skip(offset).GetResult();

This doesn't appear to work, the filter isn't applied. I assume that's because of the way the methods are chained!?

Any help massively appreciated. Bounty on the table for anyone who helps me crack it.

What Else I've Tried

    var ancestorFilterBuilder = SearchClient.Instance.BuildFilter<MyPageType>();

    foreach (var ancestorID in ancestorIDs)
    {
        ancestorFilterBuilder.Or(o => o.Ancestors().Match(ancestorID.ToString()));
    }
.....

SearchClient.Instance.UnifiedSearchFor(Request.Query)
                        .Filter(ancestorFilterBuilder)......

This didn't successfully filter either.


Solution

  • I'd convinced myself I'd misunderstood the EpiServer API, when in fact my approach of dynamically building a filter was correct, aside from the reassigning of the additional Or calls to the filter itself (inspired by Ted's reminder to do so in the context of the other loop I was using):

    var ancestorFilterBuilder = SearchClient.Instance.BuildFilter<MyPageType>();
    
    foreach (var ancestorID in ancestorIDs)
    {
        ancestorFilterBuilder = ancestorFilterBuilder.Or(o => o.Ancestors().Match(ancestorID.ToString()));
    }