PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 24, 2022

[FIXED] How to get Elastic search docs in the provided order of ids

 October 24, 2022     elasticsearch, typescript     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing