Search code examples
elasticsearchtire

Keep id order as in query


I'm using elasticsearch to get a mapping of ids to some values, but it is crucial that I keep the order of the results in the order that the ids have.

Example:

  def term_mapping(ids)
    ids = ids.split(',')
    self.search do |s|
      s.filter :terms, id: ids
    end
  end

  res = term_mapping("4,2,3,1")

The result collection should contain the objects with the ids in order 4,2,3,1...

Do you have any idea how I can achieve this?


Solution

  • If you need to use search you can sort ids before you send them to elasticsearch and retrive results sorted by id, or you can create a custom sort script that will return the position of the current document in the array of ids. However, a simpler and faster solution would be to simply use Multi-Get instead of search.