My app has Machines
that have and belong to many Specifications
class Machine < ActiveRecord::Base
has_and_belongs_to_many :specs
Specifications have both field
(width, weight, capacity, horsepower) and value
attributes.
The search is done entirely through Solr through Sunspot.
I'd like to be able to find a Machine based on its Specifications, such as find all machines with Width greater than 50.
I know I can index spec_field
and spec_value
separately, but it will filter for specs with value more than 50, which could include fields I don't want, such as height or capacity (so searching for width > 50 will yield capacity > 50 in results).
Ideally, I'd like to assign each Specification of a Machine to its own indexed field along with its value, so that my index has field such as "height" or "weight", but the specifications are flexible, and some machines have one set of specs while another machine has a different set, so it doesn't look like it can work out.
Can it even be done with Solr?
Solution Found
The Solution I found was to use "Dynamic Fields" as described here
INDEXING
dynamic_integer :specs do
specs.inject({}) do |hash,spec|
hash.merge(spec.spec_field.label.to_sym => spec.value)
end
end
QUERY
dynamic :specs do
if params[:specs].present?
for spec in params[:specs]
case spec[:condition]
when "gt"
with(spec[:field]).greater_than(spec[:value])
when "lt"
with(spec[:field]).less_than(spec[:value])
else
with(spec[:field],spec[:value])
end
end
end
end
SOLR keeps looking better and better to me!