Hi.
If you're trying to retrieve the categories for each result and display them as part of the result listing, you can retrieve the original content item and get the categories from there. The content item can be retrieved using the OriginalObjectGetter() method which returns an object which you can cast into whatever's needed like this:
var categorisedContent = hit.OriginalObjectGetter() as ICategorizable;
var categories = categorisedContent?.Category;
Obviously bear in mind that the original object may not be an ICategorizable (or whatever you choose to cast it to) depending what you're indexing and searching so you'll need to handle the scenario where categorisedContent is null.
Paul,
Thank you for this. I just tried it out. That's a real help.
Do you know off-hand if this method pulls data from the search results, or if it goes back to the DB to get the content result for each call?
I don't know for definite, but I'm fairly sure that, in that instance, it pulls content from the IContentRepository or IContentLoader so it'll be coming from either the database or the cache depending on whether that content item has been loaded before.
Paul,
Thank you for this. I did some testing with SQL Profiler and this generates a LOT of hits to the DB (when not cached). I feel like in the long run, this may be a bit expensive. Do you, or anyone know the proper way to do this with the UnifiedSearchRegistry? Either the indexing registry or the projections? This data exists in the Find index, I (ideally) just need a way to map it from Find index.
Cheers
I suspect it can be done with projections as there is a field in ISearchContent called SearchCategories which should contain the info you need. I'll take a look if I get a moment later.
You should be able to get access to the category value without hitting the content repository by adding it to the MetaData dictionary on the search hit. You can add that in your search initialisation like this:
SearchClient.Instance.Conventions.UnifiedSearchRegistry.ForInstanceOf<PageData>()
.ProjectMetaDataFrom(page => new Dictionary<string, EPiServer.Find.IndexValue> { { "Categories", page.Category.ToString() } });
You'll need to run the indexing scheduled job before that change will take effect.
Paul, thank you so much for this. I tried in a few different ways to accomplish it and your solution seems to work really well for me.
Hello,
We're trying to include the list of categories in our UnifiedSearchResults with no luck. The documentation seems to be VERY sparse with UnifiedSearch.
We've tried an extension method to see if we could just get it into the UnifiedSearchHit.FileName property using this:
That didn't seem to work.
We've played with projections as well. Just trying to get it to replace the name to see if there's any traction with that.
No luck there either.
Does anyone have some suggestions on what we could try please?