Search by Algolia
Haystack EU 2023: Learnings and reflections from our team
ai

Haystack EU 2023: Learnings and reflections from our team

If you have built search experiences, you know creating a great search experience is a never ending process: the data ...

Paul-Louis Nech

Senior ML Engineer

What is k-means clustering? An introduction
product

What is k-means clustering? An introduction

Just as with a school kid who’s left unsupervised when their teacher steps outside to deal with a distraction ...

Catherine Dee

Search and Discovery writer

Feature Spotlight: Synonyms
product

Feature Spotlight: Synonyms

Back in May 2014, we added support for synonyms inside Algolia. We took our time to really nail the details ...

Jaden Baptista

Technical Writer

Feature Spotlight: Query Rules
product

Feature Spotlight: Query Rules

You’re running an ecommerce site for an electronics retailer, and you’re seeing in your analytics that users keep ...

Jaden Baptista

Technical Writer

An introduction to transformer models in neural networks and machine learning
ai

An introduction to transformer models in neural networks and machine learning

What do OpenAI and DeepMind have in common? Give up? These innovative organizations both utilize technology known as transformer models ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

What’s the secret of online merchandise management? Giving store merchandisers the right tools
e-commerce

What’s the secret of online merchandise management? Giving store merchandisers the right tools

As a successful in-store boutique manager in 1994, you might have had your merchandisers adorn your street-facing storefront ...

Catherine Dee

Search and Discovery writer

New features and capabilities in Algolia InstantSearch
engineering

New features and capabilities in Algolia InstantSearch

At Algolia, our business is more than search and discovery, it’s the continuous improvement of site search. If you ...

Haroen Viaene

JavaScript Library Developer

Feature Spotlight: Analytics
product

Feature Spotlight: Analytics

Analytics brings math and data into the otherwise very subjective world of ecommerce. It helps companies quantify how well their ...

Jaden Baptista

Technical Writer

What is clustering?
ai

What is clustering?

Amid all the momentous developments in the generative AI data space, are you a data scientist struggling to make sense ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

What is a vector database?
product

What is a vector database?

Fashion ideas for guest aunt informal summer wedding Funny movie to get my bored high-schoolers off their addictive gaming ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

Unlock the power of image-based recommendation with Algolia’s LookingSimilar
engineering

Unlock the power of image-based recommendation with Algolia’s LookingSimilar

Imagine you're visiting an online art gallery and a specific painting catches your eye. You'd like to find ...

Raed Chammam

Senior Software Engineer

Empowering Change: Algolia's Global Giving Days Impact Report
algolia

Empowering Change: Algolia's Global Giving Days Impact Report

At Algolia, our commitment to making a positive impact extends far beyond the digital landscape. We believe in the power ...

Amy Ciba

Senior Manager, People Success

Retail personalization: Give your ecommerce customers the tailored shopping experiences they expect and deserve
e-commerce

Retail personalization: Give your ecommerce customers the tailored shopping experiences they expect and deserve

In today’s post-pandemic-yet-still-super-competitive retail landscape, gaining, keeping, and converting ecommerce customers is no easy ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

Algolia x eTail | A busy few days in Boston
algolia

Algolia x eTail | A busy few days in Boston

There are few atmospheres as unique as that of a conference exhibit hall: the air always filled with an indescribable ...

Marissa Wharton

Marketing Content Manager

What are vectors and how do they apply to machine learning?
ai

What are vectors and how do they apply to machine learning?

To consider the question of what vectors are, it helps to be a mathematician, or at least someone who’s ...

Catherine Dee

Search and Discovery writer

Why imports are important in JS
engineering

Why imports are important in JS

My first foray into programming was writing Python on a Raspberry Pi to flicker some LED lights — it wasn’t ...

Jaden Baptista

Technical Writer

What is ecommerce? The complete guide
e-commerce

What is ecommerce? The complete guide

How well do you know the world of modern ecommerce?  With retail ecommerce sales having exceeded $5.7 trillion worldwide ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

Data is king: The role of data capture and integrity in embracing AI
ai

Data is king: The role of data capture and integrity in embracing AI

In a world of artificial intelligence (AI), data serves as the foundation for machine learning (ML) models to identify trends ...

Alexandra Anghel

Director of AI Engineering

Looking for something?

facebookfacebooklinkedinlinkedintwittertwittermailmail

While answering Algolia forum posts last week, I did a deep dive on Optional Filters for Algolia Search. Similar to filters and facet filters, optional filters are applied at query-time, allowing you to use all sorts of contextual information to improve results. Unlike the other filters, optional filters don’t remove records from the result set. Instead, they allow you to say, “If records match this filter, then move them up or down the ranking,” without changing the number of records returned.

Some interesting use cases:

  • Move posts that mention a particular user to the top of the result set
  • Up-rank products available at a customer’s local store
  • Down-rank products that are out-of-stock
  • Pin a specific record to the top of the listing based on an external recommendations engine

You can use filters and facet filters to reduce the number of records in the result set at query-time, then optional filters to manipulate the rankings for the remaining records. You can even apply filter scoring to control the order of the records further.

Here’s an example that applies facet filters for product_type and price_range to an index from a Shopify store. The code selects the objectID of two records to promote, then injects them as optional filters into the query. If either of those products is part of the result set that matches the other criteria in the query, those products are pushed to the top of the ranking. The code uses filter scoring to ensure the featuredProduct will always appear above the alternateProduct.

import algoliasearch from 'algoliasearch';

const featuredProduct = '41469303161004';
const alternateProduct = '41469346644140';

const client = algoliasearch('H2M6B61JEG', 'b1bdfc3258823bb4468815a664dce649');

// Standard replica
const index = client.initIndex('shopify_algolia_products_price_asc_standard');

// with params
index.search(query, {
    facetFilters: [[
        "product_type:HardGood",
        "price_range:75:100"
    ]],
    optionalFilters: [[
        `objectID:${featuredProduct}<score=500>`,
        `objectID:${alternateProduct}<score=200>`
    ]],
    hitsPerPage: 50,
}).then(({ hits }) => {
    console.log(hits.map(item => `- ${item.title} | ${item.product_type} | ${item.objectID} | ${item.price_range}`).join('\n'));
});

Notice that this code uses a standard replica of the Shopify index sorted by price. Optional filters don’t play well with Virtual Replica indices since both re-rank records at query-time, leading to unpredictable results. If you plan to use optional filters, you should use a standard replica that applies ranking at index-time.

You can also use negative optional filters to push records down the ranking. For example, if you wanted to push posts written by the current user lower in the rankings but not remove them completely:

index.search('', {
    filters: `date_timestamp > ${Math.floor(d.setDate(d.getDate() - 7) / 1000)}`,
    optionalFilters: [
      `author:-${user.name}`
    ],
    hitsPerPage: 50,
}).then(({ hits }) => {
    console.log(hits};
});

Optional filters are a powerful tool to add to your ranking tool belt, but remember that any query-time calculations will impact search performance. For instance, you shouldn’t use filter scoring on searches that may return more than 100,000 results. Always try to move ranking criteria to index configuration when possible. Use optional filters only when you need to further tune your results at query-time using more real-time context.

Let me know if you find a great (or not so great) use case for optional filters in your search UI!

About the author
Chuck Meyer

Sr. Developer Relations Engineer

githubtwitter

Recommended Articles

Powered byAlgolia Algolia Recommend

Enhance your Shopify store experience with search filters and facets
ux

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

Search filters: 5 best practices for a great UX
ux

Louise Vollaire
Alexandra Prokhorova

Louise Vollaire &

Alexandra Prokhorova

Taking documentation search to new heights with Algolia and Autocomplete
ux

Sarah Dayan

Principal Software Engineer