Before you begin
This tutorial assumes that you installed Node.js in your environment, and you understand how to create and run Node.js scripts. You also need an Algolia account. If you don’t have one already, you can create an account for free.Dataset
For this tutorial, you’ll use an ecommerce dataset where each result is a product. All records have acategories
attribute with one or more categories.
Download the dataset and import it into your Algolia application.
For more information, see Import with the dashboard.
Install dependencies
Install thealgolia-sitemap
as a dependency.
This helper library lets you dynamically generate sitemaps from your Algolia indices.
Create a sitemap of all the records in your index
First, create a sitemap with all your products to let search engines know where to find them. You need your Algolia application ID and your API key. The API key must havebrowse
permission.
JavaScript
sitemap
function, you need to add a hitsToParams
callback function.
This function turns a record from your index into a sitemap entry.
The return value of the hitsToParams
function must be an object with attributes
that match an <url>
entry of a sitemap file:
loc
(required): the URL of the page for the recordlastmod
: the last modified date (ISO 8601)priority
: the priority of this page compared to other pages on your site (between 0 and 1)changefreq
: describes how often the page is likely to changealternates
: alternate versions of this linkalternates.languages
: an array of enabled languages for this linkalternates.hitToURL
: a function that transforms a language into a URL
loc
attribute.
JavaScript
sitemaps/
directory.
Now, you can run the sitemap.js
script:
/sitemaps
directory now has two types of files:
- The
sitemap-index.xml
file with links to each sitemap file - The
sitemap.0.xml
file with links to your products
xmllint
.
Create a sitemap for categories
You should add your category pages to the sitemap. If you’re using the sample dataset, use thecategories
attribute for the URL:
JSON
https://example.com/{CATEGORY_NAME}
.
You need to modify the hitToParams
callback function to return an array of all categories that belong to a given record.
Since categories apply to many records, you need to make sure to add them to your sitemaps only once.
With ES6, you can use a Set
.
JavaScript
Create a sitemap for categories and all records
You can modify the code for adding category pages to your sitemap to create a combined sitemap for both records and categories.JavaScript
Notify search engines of sitemap changes
Finally, you can let search engines know that your sitemap has changed. Most search engines have aping
mechanism to inform them of a new sitemap,
so you can perform this directly from your script.
JavaScript