I have several models indexed with elasticsearch and one of them has an association that needs to be filtered, but if I add something like this into the search
method
search.filter :range, 'sessions.starts_on' => {:gte => start_date,
:lte => ends_on}
then all the models are filtered out because they don't have such an association sessions
.
So is there a way to apply filter to only one model?
Any thoughts are much appreciated!
Create a module for tire index specifically related to that model and include it in the model. As sessions is only association with the model its reference will be there in document which is going to elasticsearch. You have to merge the sessions document in your model document like this as we passed the json of document to elasticsearch in tire index module
def to_model_json
self.document.merge({"sessions" => sessions.as_json}).to_json
end
this method is passing a document in json to elasticsearch through tire which will be having their sessions merged in the document.
in tire index module give a index name which you can pass in the tire search object to run the filter queries
Now create a tire search object
search_object = Tire::Search::Search::new(Model.index_name, other attributes)
you can check other attributes which you can pass from https://github.com/karmi/tire
then run your search method like this it will give the desired result
search_object.filter :range, 'sessions.starts_on' => {:gte => start_date,
:lte => ends_on}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With