Issue
I have I have order of ids, [1, 4, 2, 5] and some filters { match: {...} } and I want the resulting documents to be returned in the order [1, 4, 2, 5]. What would be the best way to achieve this?
Sample document:
{
"id": <uuid>,
"name": "Some name",
"description": "Some description"
}
Now I am aware that ES stores _id for each document and _id for es doc and id field inside my doc are same.
So I want to provide array of ids and get the results in that order after all the filtering.
For example I have 4 documents
{
"id": "abcd",
"name": "test1",
"description": "test1"
},
{
"id": "bcde",
"name": "test2",
"description": "test2"
},
{
"id": "cdef",
"name": "test3",
"description": "test3"
}
now i have array of ids ["cdef", "abcd", "bcde"] so I want to query es and get results in the above specified order meaning doc with cdef
has to be first in the hits then doc with abcd
and then doc with bcde
Solution
This answer is based on sorting using script. here you need to pass all your array term with score value and based on that, the script will assign the score to the specific document when it match to the id.
{
"sort": {
"_script": {
"type": "number",
"script": {
"lang": "painless",
"source": """for (int i = 0; i < params.scoring.length; i++) { if(doc['id.keyword'].value == params.scoring[i]['id']) return params.scoring[i]['score']; } return 0;""",
"params": {
"scoring": [
{
"id": "cdef",
"score": 1
},
{
"id": "abcd",
"score": 2
},
{
"id": "bcde",
"score": 3
}
]
}
},
"order": "asc"
}
},
"query": {
"terms": {
"id": [
"cdef",
"abcd",
"bcde"
]
}
}
}
Answered By - Sagar Patel Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.