Keep id order as in query
Asked Answered
A

3

6

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?

Annelleannemarie answered 9/1, 2013 at 14:29 Comment(0)
V
0

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.

Valenta answered 9/1, 2013 at 14:49 Comment(1)
Ok, thank you, I guess Multi-Get is not supported by tire yet. I will stick to my simple ruby based solution till then...Annelleannemarie
S
0

One option is to use the Multi GET API. If this doesn't work for you, another solution is to sort the results after you retrieve them from es. In python, this can be done this way:

doc_ids = ["123", "333", "456"]  # We want to keep this order
order = {v: i for i, v in enumerate(doc_ids)} 
es_results = [{"_id": "333"}, {"_id": "456"}, {"_id": "123"}]
results = sorted(es_results, key=lambda x: order[x['_id']])
# Results:
# [{'_id': '123'}, {'_id': '333'}, {'_id': '456'}] 
Sopher answered 6/8, 2019 at 19:47 Comment(0)
P
0

May be this problem is resolved,, but someone will help with this answer

we can used the pinned_query for the ES. Do not need the loop for the sort the order

**qs = {
      "size" => drug_ids.count,
      "query" => {
        "pinned" => {
          "ids" => drug_ids,
          "organic" => {
              "terms": {
                "id": drug_ids
              }
          }
        }
      }
    }**

It will keep the sequence of the input as it

Pincenez answered 2/3, 2022 at 9:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.