How to filter your data
Most records have one or more attributes, such as color, brand, genre, or category, that you can choose as a filter. A filter attribute can be a list of single words, more complex phrases, numbers, booleans, dates, or even arrays and nested arrays of related data. Users may use any filter combination to group records. Filtering creates more targeted and therefore relevant subsets of results, and increases the chance that only the best results appear at the top.Define filterable attributes
First, define filter attributes as attributes for faceting. You can do this on the dashboard or with an API client. If you only want to use an attribute for filtering, use thefilterOnly
modifier.
This reduces the index size and improves search speed.
For example, if you plan to filter on an attribute, such as color
, but donโt need to calculate or display the number of items with color:green
, color:blue
, or similar, use filterOnly
.
If you use
filters
or numericFilters
to filter on numeric attributes, you donโt need to set these attributes as attributesForFaceting
.Filter by attributes
- Filter by string
- Filter by numeric value
- Filter by date
- Filter by array
- Filter by tags
- Filter by boolean
- Filter by null or missing attributes
- Filter by
objectID
How to apply filtering to the search UI
After defining filterable attributes and ensuring users can filter every record with the appropriate attributes, ensure your frontend represents all these possibilities by using InstantSearchโs refinements. Youโll typically want to display all filtering categories. Thus, if you have created two filters,brand
and price_range
, youโll always want to display a list of brands and a price range slider for every query in your UI.
For example, a search for โphonesโ returns brands like Apple and Samsung, while a search for โspeakersโ returns Panasonic and Bose.
While the values may change, the brand
filter is always present.
To learn more, see:
Other uses for filtering
Although the most common use for filtering is to enable users to refine their search and limit the records they search within, there are other ways to use filters. For example:- Security-filtering: using filters as a security measure, where each user has access to only their private data.
- Geo-filtering: filtering on userโs geolocation (if your index has geographical data).
- Filter scoring: using filters to help promote some records over others.
- Query-based filtering: setting rules that parse your usersโ queries and use specific query terms as filters instead of search terms. For example, if a user types in โredโ, โredโ can be used as a filter instead of a search term, thereby returning all red records.