Filter By Numeric Value
On this page
Algolia allows you to numerically filter results, via a comparison or a range. This only works if you’re using numeric values. Imagine you have an ecommerce website, and you want to filter by price. With filters, you could allow users to refine results and only see items which cost more or less than a certain price, or those comprised in a specific price range.
Dataset Example
Let’s say we have an index called products
that looks like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[
{
"name": "Samsung Galaxy",
"description": "Samsung Galaxy Express 3 4G LTE with 8GB Memory Prepaid Cell Phone",
"price": 49.99
},
{
"name": "AT&T GoPhone - Apple iPhone 5s 4G LTE 16GB Memory Prepaid Cell Phone w\/Airtime Card - Gray",
"description": "Enjoy exceptional service on a popular phone with this AT&T GoPhone iPhone 5s. Enjoy all the features of the iPhone 5s, including its 4-inch Retina display and 8.0-megapixel camera, in tandem with AT&T's GoPhone mobile service, which provides a flexible plan with no annual contract. Stay connected with family and friends with this AT&T GoPhone iPhone 5s.",
"price": 194.99
},
{
"name": "Huawei - Mate 9 4G LTE with 64GB Memory Cell Phone (Unlocked) - Space Gray",
"description": "Keep connected on the go with this unlocked Huawei Mate9 smartphone. Its Kirin 960 processor delivers blazing performance, while the 4000 mAh battery and power-saving technology provide up to 2 days of usage. The glamorous 5.9-inch Full HD display delivers immersive visuals, while 3D fingerprint recognition technology keeps this 64GB Huawei Mate9 smartphone secure and safe.",
"price": 599.99
},
...
]
Notice that we’re using numeric values for the price
attribute, not strings. This way, Algolia can interpret them when using comparison or range operators.
Applying a numeric filter
Setting a limit
Imagine we want to let users define a price limit over which they don’t want to retrieve results. For example, they may want to look for a phone under $100.
Algolia filters use an SQL-like syntax, which allows you to use comparison operators.
1
2
3
$results = $index->search('query', [
'filters' => 'price < 100'
]);
Algolia supports <
, <=
, =
, !=
, >=
and >
operators with the same semantics as in virtually all programming languages.
Filtering by price range
Now imagine we only want to retrieve products between $100 and $200. We can achieve this by setting a range filter.
1
2
3
$results = $index->search('query', [
'filters' => 'price:100 TO 200'
]);