Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter applying to only one model with Tire and ElasticSearch in Rails

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!

like image 854
alony Avatar asked Nov 14 '22 06:11

alony


1 Answers

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}
like image 94
abhas Avatar answered Dec 19 '22 17:12

abhas