I’m not sure if this will be useful to anyone or not, but here it is anyways…
I just added Algolia to a Hugo site I’ve been working on, and I thought my solution for automatically keeping Algolia informed about new content could be useful for others to see.
Basically, I generate some special JSON, then use Algolia’s REST batch API to update Algolia after each build.
Since I already have JSON output for something else, I ended up creating an /algolia.json
by adding this to my config.toml
:
[outputFormats.Algolia]
mediaType = "application/json"
baseName = "algolia"
isPlainText = true
Then I just had to create a template (themes/$theme/layouts/algolia.json
) which outputs data which looks like:
{
"requests": [
{ "action": "updateObject",
"body": {
...,
"objectID": "/foo/bar" } },
{ "action": "updateObject",
"body": {
...,
"objectID": "/foo/baz" } }
]
}
Where ...
your data. I found it convenient to just use the URL as my objectID, but anything which uniquely identifies a record works. My template is at https://github.com/factopolis/factopolis/blob/master/themes/factopolis/layouts/algolia.json, but it’s pretty specific to my site so I’m not sure how helpful it would be as a guide.
A simple example to get you started:
{
"requests": [
{{ range $idx, $page := $.Site.Pages }}
{{ if $idx }},{{ end }}
{ "action": "updateObject",
"body": {
"title": {{ $page.Title | jsonify }},
"objectID": {{ $page.URL | jsonify }}
}
}
{{ end }}
]
}
Note that if you remove content it won’t be deleted from Algolia. I think you could prepend a { "action": "clear" }
, but it shouldn’t be very common for me so I’ve left it off for now, and I’ll just clear the index manually when necessary.
Then add a few environment variables to your CI, and upload the file with something like
curl -X POST \
-H "X-Algolia-API-Key: ${ALGOLIA_API_KEY}" \
-H "X-Algolia-Application-Id: ${ALGOLIA_APPLICATION_ID}" \
--data-binary @web/algolia.json \
"https://${ALGOLIA_APPLICATION_ID}.algolia.net/1/indexes/${ALGOLIA_INDEX_NAME}/batch"
This does hit Algolia a bit harder than necessary, but I don’t think I’ll run into their free limits for quite some time (you basically get 100.000 updateObject
actions per month, so you’d need a pretty large and active site to hit the limit even for the free tier). If it does become a problem I’ll probably create a second git repository, have CI for the first repo update a file in the second one, then look at the diff to see what really needs to change and only send Algolia the necessary operations.
From there it’s just the standard front-end integration stuff for Algolia, which isn’t too difficult.
The commit for all this on my site is 3a980173a8fa220f1aa534393f57b6e32ded1067, could be useful if anyone runs into trouble.