lundi 30 septembre 2019

Elasticsearch sort based on multiple fields and then by random seed

[
    {
        "id": "1",
        "title": "example title 1",
        "priority": "high"
    },
    {
        "id": "2",
        "title": "example title 2",
        "priority": "high"
    },
    {
        "id": "3",
        "title": "example title 3",
        "priority": "high"
    },
    {
        "id": "4",
        "title": "example title 4",
        "priority": "low"
    },
    {
        "id": "5",
        "title": "example title 5",
        "priority": "low"
    },
    {
        "id": "6",
        "title": "example title 6",
        "priority": "low"
    }
]

I have the following items in my elasticsearch index and i can easily sort by multiple fields but i didnt find a way to sort by multiple fields and then random.

So, for example i would need to do this:

  "sort": [
    {
      "priority": "asc"
    },

    _script: {
        script: "Math.random() * 200000",
        type: "number",
        params: {},
        order: "asc"
    }

  ]

So, lets say on first query, you would get these results:

3,2,1(high priority comes first but randomized),5,4,6(low priority comes next, but also randomized)

Second query could also look like this:

2,1,3(high),6,5,4(low)




Aucun commentaire:

Enregistrer un commentaire