Table of contents :

How to Rank Products by Sales in Algolia

100-days-of-algolia-031

Table of contents :

WooCommerce stores can use sales performance as a relevance signal so that popular products appear before less frequently purchased products when search results have similar textual relevance. In Algolia, the usual implementation is to index a numeric sales attribute and add it to the index’s custom ranking configuration.

Choose the sales metric

Before changing the ranking, define exactly what “sales” means. Common options include lifetime units sold, units sold during a recent period, gross revenue, or net revenue after refunds. Lifetime units are simple, but they can cause older products to dominate indefinitely. A rolling 30-day or 90-day metric is often more useful for merchandising because it reflects current demand.

For a WooCommerce catalog, a practical attribute might be named sales_count_30d. Keep the value numeric and use a consistent update process. Do not index formatted currency strings, values containing commas, or text such as “250 sold”; Algolia must receive a number to sort by it.

Add the metric to the Algolia record

An indexed product record can contain the sales metric alongside the fields used for search and display:

{
  "objectID": "4821",
  "name": "Canvas Travel Backpack",
  "categories": ["Bags", "Travel"],
  "price": 89.00,
  "sales_count_30d": 127,
  "in_stock": true
}

The exact record shape depends on the WooCommerce integration or custom indexing code. The important details are that the field is present on every applicable product and that its value is an integer or floating-point number rather than a string.

Configure Algolia custom ranking

Set the index’s custom ranking to sort by the sales attribute in descending order:

customRanking: [
  "desc(sales_count_30d)"
]

Custom ranking is used after Algolia’s textual relevance rules have narrowed and ordered records with comparable relevance. It should not replace searchable attributes, typo tolerance, filters, or other relevance settings. A product that does not match the query well should not rank highly merely because it has many historical sales.

When configuring the index through the Algolia JavaScript client, the settings may look like this:

await index.setSettings({
  searchableAttributes: [
    "name",
    "categories",
    "description"
  ],
  customRanking: [
    "desc(sales_count_30d)"
  ]
});

Apply the setting to every replica that should use sales-based ordering. If the store has a dedicated sort such as “Most popular,” keep that sort in a replica index rather than changing the default relevance index for every search.

Create a dedicated popularity replica

A common WooCommerce pattern is to preserve a relevance-oriented primary index and create a replica for popularity sorting. The front end can then offer a sort option without forcing every shopper into the same ranking strategy.

  • Relevance index: prioritizes textual relevance and uses minimal business ranking.
  • Popularity replica: uses desc(sales_count_30d) as its custom ranking.
  • Price replicas: optionally sort by ascending or descending price.

When a shopper selects “Most popular,” send the query to the popularity replica. In InstantSearch, this is commonly implemented with a sort-by widget configured with the relevant index names.

const search = instantsearch({
  indexName: "products_relevance",
  searchClient
});

search.addWidgets([
  instantsearch.widgets.sortBy({
    items: [
      { label: "Relevance", value: "products_relevance" },
      { label: "Most popular", value: "products_popularity" }
    ]
  })
]);

Keep the sales value synchronized

Ranking quality depends on the freshness of the indexed metric. A WooCommerce agency should decide whether updates happen immediately after an order, on a schedule, or through a combination of both.

  1. Listen for completed or paid orders.
  2. Calculate the contribution of the order’s line items to the chosen sales period.
  3. Update the affected product records in the source system.
  4. Send only the changed records to Algolia when possible.
  5. Handle refunds, cancellations, and order status changes according to the metric definition.

For lifetime units sold, WooCommerce’s product-level sales count may be sufficient if the store’s business rules treat it as authoritative. For a rolling period, maintain a separate aggregate table or reporting process. Avoid calculating a full catalog total during every product save; that approach becomes expensive on stores with large catalogs.

Sales events can be queued for asynchronous processing with Action Scheduler or another worker system. This avoids delaying checkout or order-status requests while records are being reindexed.

Example update flow

A simplified server-side process might collect the changed product IDs and send refreshed records through the Algolia client:

const products = changedProductIds.map((productId) => ({
  objectID: String(productId),
  name: getProductName(productId),
  price: getProductPrice(productId),
  sales_count_30d: getThirtyDaySales(productId),
  in_stock: isProductInStock(productId)
}));

await index.saveObjects(products);

The production implementation should use the store’s existing indexing serializer so that updating the sales field does not accidentally remove taxonomies, variants, images, or other searchable fields from the record. If records are generated by a WooCommerce Algolia extension, extend its indexing hooks instead of maintaining a second incompatible record format.

Combine sales with availability and merchandising rules

Sales ranking should not promote products that cannot be purchased. Use a filter such as in_stock:true when the storefront requires available products, or configure inventory handling in the integration. Also consider explicit merchandising rules for seasonal products, campaigns, or products that must be promoted for commercial reasons.

Do not treat custom ranking as a substitute for hard constraints. A discontinued product should be removed or filtered, not merely given a low sales score. Likewise, category, brand, price, visibility, and customer-specific eligibility should remain filters or separate business rules.

Prevent ranking bias

Raw lifetime sales favor products with a long history and high exposure. Several safeguards can make the ranking more useful:

  • Use a rolling sales window to reflect current demand.
  • Apply a minimum inventory or availability filter.
  • Use a logarithmic or bucketed score when a few products overwhelm the catalog.
  • Segment the metric by category when comparing products with very different purchase patterns.
  • Use a secondary ranking signal, such as margin or conversion rate, only when the business requirement justifies it.

If a transformed score is required, calculate it before indexing. For example, a store might index popularity_score rather than raw units sold:

popularity_score = Math.log1p(unitsSold30d) * conversionWeight;

Keep the transformation documented and stable. Changing the formula without reindexing all products can leave records with incompatible scores.

Test the ranking with realistic queries

Test generic queries, brand queries, category queries, zero-result searches, and queries for products with low sales but strong textual matches. Compare the relevance index with the popularity replica and verify that filters continue to work. Check products with equal sales values, missing values, newly launched products, and returned or cancelled orders.

Use Algolia analytics and WooCommerce conversion data to measure whether the sort increases useful engagement and purchases rather than only clicks. Monitor search conversion, add-to-cart rate, revenue per search, and the performance of new products. If the popular sort harms discoverability, make it an optional sort or reduce the influence of the sales metric.

Operational checklist

  • Define whether the metric is based on units, orders, gross revenue, or net revenue.
  • Use a numeric Algolia attribute with a documented update interval.
  • Configure descending custom ranking for the popularity index or replica.
  • Keep unavailable and hidden WooCommerce products out of results.
  • Process order and refund changes asynchronously when appropriate.
  • Reindex complete records when the record serializer changes.
  • Validate ranking behavior with production-like queries and analytics.
Trending posts
You might also like