Elastic search order by date and indexing with Ruby-on-Rails

The elastic search date field type seems like a lot of work. You have to manually map each date field parameter. All I really wanted to do was order by date, and this doesn’t necessarily ruleĀ out more complicated date range filtering. You just have to convert everything to Epoch millisecond time. Sometimes it just seems like the most standard format.

Map the field type in your elastic search index as a float. Changing a field type requires recreating the index.

mappings dynamic: 'false' do
 indexes :created_at, type: 'float'
end

In your method that converts the model to json for indexing, convert the date to milliseconds.

def as_indexed_json(options={})
  model_attrs = {
    :created_at => self.created_at.to_f
  }
end

Now you can easily order by asc and desc.

Published by

Anthony

Anthony loves open source software. Especially Linux and Ruby on Rails. He enjoys tinkering with his Raspberry Pi projects, writing code late at night, and drinking coffee. He aspires to be a Linux guru and software development magician. He is currently reading books on AI.

Leave a Reply

Your email address will not be published. Required fields are marked *