Push related Statamic entry data into Algolia index
Warning: This post is over a year old. I don't always update old posts with new information, so some of this information may be out of date.
Let's take a look at how we can add some good related Statamic entry data to an Algolia index and improve the user search experience.
I've been working on a really fun Statamic project lately. It's been the first proper mix of building a custom Laravel app and making use of the cool things Statamic gives us out the box.
On this particular project, it's going to leverage Algolia to improve the search experience for users discovering content.
Consider the following search index in config/statamic/search.php
:
'videos' => [
'driver' => 'algolia',
'searchables' => 'collection:videos',
'fields' => [
'title', 'artwork', 'tags', 'description', 'id', 'author'
],
],
Here we have 6 fields that we wish to be in our Algolia index. In this instance author
is a related entry in another Statamic collection. If we were to update the index currently, all we'd see is the entry id from the related collection which isn't very helpful to our Algolia search results.
Enter transformers
- "robots in disguise", I know you just sang that in your head!
If we update our index to include transformers:
'videos' => [
'driver' => 'algolia',
'searchables' => 'collection:videos',
'fields' => ['title', 'artwork', 'tags', 'description', 'id', 'author'],
'transformers' => [
'author' => function($author) {
$entry = Entry::find($author);
return [
'author_name' => "{$entry->author_first_name} {$entry->title}",
];
}
]
]
We pass the entry id into a function, lookup the entry by its id, we can then push the author name - where our blueprint has author_first_name
as a field of course.
And here's the result now in our Algolia dashboard index.
It means that now, if a user were to search for Shakira Schmeler
- we'll get that hit in the video search 🙌🏼
Happy transforming.
A Note
At the time of writing, there's an open PR to get this information added to the Statamic knowledge base.