Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
NestedTermsFacetExtensions for EPiServer Find
public static class NestedTermsFacetExtensions
{
public static ITypeSearch<TSource> NestedTermsFacetFor<TSource, TEnumerable>(
this ITypeSearch<TSource> search,
Expression<Func<TSource, IEnumerable<TEnumerable>>> enumerableFieldSelector, Expression<Func<TEnumerable, string>> itemFieldSelector)
{
return search.AddNestedTermsFacetFor(enumerableFieldSelector, itemFieldSelector, null);
}
public static ITypeSearch<TSource> NestedTermsFacetFor<TSource, TEnumerable>(
this ITypeSearch<TSource> search,
Expression<Func<TSource, IEnumerable<TEnumerable>>> enumerableFieldSelector, Expression<Func<TEnumerable, string>> itemFieldSelector, Action<TermsFacetRequest> facetRequestAction)
{
return search.AddNestedTermsFacetFor(enumerableFieldSelector, itemFieldSelector, facetRequestAction);
}
public static ITypeSearch<TSource> AddNestedTermsFacetFor<TSource>(
this ITypeSearch<TSource> search,
Expression enumerableFieldSelector, Expression itemFieldSelector, Action<TermsFacetRequest> facetRequestAction)
{
enumerableFieldSelector.ValidateNotNullArgument("enumerableFieldSelector");
itemFieldSelector.ValidateNotNullArgument("itemFieldSelector");
var facetName = enumerableFieldSelector.GetFieldPath() + "." + itemFieldSelector.GetFieldPath();
var fieldName = enumerableFieldSelector.GetFieldPath() + "." + search.Client.Conventions.FieldNameConvention.GetFieldName(itemFieldSelector);
var action = facetRequestAction;
return search.TermsFacetFor(facetName, x =>
{
x.Field = fieldName;
if (action.IsNotNull())
{
action(x);
}
});
}
}
public static class NestedTermsFacetResultExtraction
{
private static TFacet GetFacetFor<TFacet>(IHasFacetResults facetsResultsContainer, string facetName)
where TFacet : Facet
{
var facet = facetsResultsContainer.Facets[facetName];
if (facet.IsNull())
{
return null;
}
return facet as TFacet;
}
public static TermsFacet NestedTermsFacetFor<TResult, TEnumerable>(
this IHasFacetResults<TResult> facetsResultsContainer, Expression<Func<TResult, IEnumerable<TEnumerable>>> enumerableFieldSelector, Expression<Func<TEnumerable, string>> itemFieldSelector)
{
return GetFacetFor<TermsFacet>(facetsResultsContainer, enumerableFieldSelector.GetFieldPath() + "." + itemFieldSelector.GetFieldPath());
}
}
// Usage
// Given:
public class BlogPost
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public IEnumerable<Author> Authors { get; set; }
...
}
public class Author : User, IHasTitle
{
public string Name { get; set; }
...
}
// Request facet:
var searchResult = client.Search<BlogPost>().NestedTermsFacetFor(x => x.Authors, x => x.Name).GetResult();
// Get facet:
var termsFacet = searchResult.NestedTermsFacetFor(x => x.Authors(), x => x.Name);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment