Skip to content

Instantly share code, notes, and snippets.

@darklow
Last active May 31, 2022 05:25
Show Gist options
  • Save darklow/7132077 to your computer and use it in GitHub Desktop.
Save darklow/7132077 to your computer and use it in GitHub Desktop.
ElasticSearch custom sort, based on provided ids array order. Original code from here: http://damienalexandre.fr/post/elasticsearch-ids-query-order Rewritten to new "function_score" syntax Note: You need to remove \n new lines from "script" field in order to get it work.
q = {
"query": {
"function_score": {
"boost_mode": "replace",
"query": {
"ids": {
"values": [
50,
80,
44,
12
]
}
},
"script_score": {
"params": {
"ids": [
50,
80,
44,
12
]
},
"script": """
count = ids.size();
id = org.elasticsearch.index.mapper.Uid.idFromUid(doc['_uid'].value);
for (i = 0; i < count; i++) {
if (id == ids[i]) { return count - i; }
}""",
}
}
},
"size": 20,
"from": 0
}
@terrynguyen255
Copy link

"script_score": {
  "params": {
    "ids": [
        50,
        80,
        44,
        12
    ]
  },
  "script": """
    count = ids.size();
    id    = org.elasticsearch.index.mapper.Uid.idFromUid(doc['_uid'].value);
    for (i = 0; i < count; i++) {
      if (id == ids[i]) { return count - i; }
     }""",
}

This doesn't work in my case.

I update it to:

sort: {
  _script: {
    type: 'number',
    script: {
      lang: 'painless',
      params: {
        ids: [4,8,2,4,8,16],
      },
      source: `
        int idsCount = params.ids.size();
        def id = doc['slug.keyword'].value;
        int foundIdx = params.ids.indexOf(id);
        return foundIdx > -1 ? foundIdx: idsCount + 1;
      `
    }
  }
}

hope it helps someone

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment