Search by Algolia
Introducing new developer-friendly pricing
algolia

Introducing new developer-friendly pricing

Hey there, developers! At Algolia, we believe everyone should have the opportunity to bring a best-in-class search experience ...

Nick Vlku

VP of Product Growth

What is online visual merchandising?
e-commerce

What is online visual merchandising?

Eye-catching mannequins. Bright, colorful signage. Soothing interior design. Exquisite product displays. In short, amazing store merchandising. For shoppers in ...

Catherine Dee

Search and Discovery writer

Introducing the new Algolia no-code data connector platform
engineering

Introducing the new Algolia no-code data connector platform

Ingesting data should be easy, but all too often, it can be anything but. Data can come in many different ...

Keshia Rose

Staff Product Manager, Data Connectivity

Customer-centric site search trends
e-commerce

Customer-centric site search trends

Everyday there are new messages in the market about what technology to buy, how to position your company against the ...

Piyush Patel

Chief Strategic Business Development Officer

What is online retail merchandising? An introduction
e-commerce

What is online retail merchandising? An introduction

Done any shopping on an ecommerce website lately? If so, you know a smooth online shopper experience is not optional ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

5 considerations for Black Friday 2023 readiness
e-commerce

5 considerations for Black Friday 2023 readiness

It’s hard to imagine having to think about Black Friday less than 4 months out from the previous one ...

Piyush Patel

Chief Strategic Business Development Officer

How to increase your sales and ROI with optimized ecommerce merchandising
e-commerce

How to increase your sales and ROI with optimized ecommerce merchandising

What happens if an online shopper arrives on your ecommerce site and: Your navigation provides no obvious or helpful direction ...

Catherine Dee

Search and Discovery writer

Mobile search UX best practices, part 3: Optimizing display of search results
ux

Mobile search UX best practices, part 3: Optimizing display of search results

In part 1 of this blog-post series, we looked at app interface design obstacles in the mobile search experience ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

Mobile search UX best practices, part 2: Streamlining search functionality
ux

Mobile search UX best practices, part 2: Streamlining search functionality

In part 1 of this series on mobile UX design, we talked about how designing a successful search user experience ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

Mobile search UX best practices, part 1: Understanding the challenges
ux

Mobile search UX best practices, part 1: Understanding the challenges

Welcome to our three-part series on creating winning search UX design for your mobile app! This post identifies developer ...

Vincent Caruana

Sr. SEO Web Digital Marketing Manager

Teaching English with Zapier and Algolia
engineering

Teaching English with Zapier and Algolia

National No Code Day falls on March 11th in the United States to encourage more people to build things online ...

Alita Leite da Silva

How AI search enables ecommerce companies to boost revenue and cut costs
ai

How AI search enables ecommerce companies to boost revenue and cut costs

Consulting powerhouse McKinsey is bullish on AI. Their forecasting estimates that AI could add around 16 percent to global GDP ...

Michelle Adams

Chief Revenue Officer at Algolia

What is digital product merchandising?
e-commerce

What is digital product merchandising?

How do you sell a product when your customers can’t assess it in person: pick it up, feel what ...

Catherine Dee

Search and Discovery writer

Scaling marketplace search with AI
ai

Scaling marketplace search with AI

It is clear that for online businesses and especially for Marketplaces, content discovery can be especially challenging due to the ...

Bharat Guruprakash

Chief Product Officer

The changing face of digital merchandising
e-commerce

The changing face of digital merchandising

This 2-part feature dives into the transformational journey made by digital merchandising to drive positive ecommerce experiences. Part 1 ...

Reshma Iyer

Director of Product Marketing, Ecommerce

What’s a convolutional neural network and how is it used for image recognition in search?
ai

What’s a convolutional neural network and how is it used for image recognition in search?

A social media user is shown snapshots of people he may know based on face-recognition technology and asked if ...

Catherine Dee

Search and Discovery writer

What’s organizational knowledge and how can you make it accessible to the right people?
product

What’s organizational knowledge and how can you make it accessible to the right people?

How’s your company’s organizational knowledge holding up? In other words, if an employee were to leave, would they ...

Catherine Dee

Search and Discovery writer

Adding trending recommendations to your existing e-commerce store
engineering

Adding trending recommendations to your existing e-commerce store

Recommendations can make or break an online shopping experience. In a world full of endless choices and infinite scrolling, recommendations ...

Ashley Huynh

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

Staff Software Engineer