-
Notifications
You must be signed in to change notification settings - Fork 0
Scoping by attribute fields
Scoping in Sunspot is the equivalent of placing conditions on a database query – values against which to compare fields are passed in and processed verbatim. Scopes in Sunspot’s DSL are built using the with
method:
Sunspot.search(Post) do
with(:published_at).less_than(Time.now)
end
This will send a query to Sunspot that is roughly the equivalent of the MySQL query:
SELECT `posts`.* FROM `posts` WHERE `published_at` < NOW();
The argument to the with
method is always the name of an attribute field (e.g., one defined using a type other than text
). The chained method is the name of a restriction; the available restrictions are:
equal_to
less_than
greater_than
between
first
and last
.any_of
all_of
Sunspot also provides shorthand restrictions, wherein a second argument is passed to with
; the restriction type is determined based on the class of the second argument:
- If an Array is passed, an any_of
restriction is created.
- If a Range is passed, a between
restriction is created.
- Otherwise, an equal_to
restriction is created.
For example, the following pairs of restriction calls are equivalent:
with(:blog_id, 1)
with(:blog_id).equal_to(1)
with(:average_rating, 3.0..5.0)
with(:average_rating).between(3.0..5.0)
with(:category_ids, [1, 3, 5])
with(:category_ids).any_of([1, 3, 5])
The simplest way to combine restrictions is to specify more than one within the search block; this will match documents to whom all of the restrictions apply:
Sunspot.search(Post) do
with(:published_at).less_than(Time.now)
with(:blog_id, 1)
end
The above will match all documents whose published date is in the past, and whose blog_id is 1.