1
[
    {
        "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)

1 Answer 1

2

Ughh, i guess you need to articulate a proper question before you can find a proper solution.

Anyway, here is the answer for all posterity:


{
  "size": 3,
  "query": {
    "function_score": {
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "my_column1": "805"
              }
            },
            {
              "match": {
                "my_column2": "30"
              }
            },
            {
              "range": {
                "product_price": {
                  "gt": "500",
                  "lt": "1000"
                }
              }
            },
            {
              "match": {
                "my_column3": "0"
              }
            }
          ]
        }
      },
      "functions": [
        {
          "random_score": {
            "seed": "1477072619038"
          }
        }
      ]
    }
  },
  "sort": [
    {
      "priority": "asc"
    },
    {
      "date_added": "asc"
    },
    {
      "_score": "asc"
    }
  ]
}

This is how you mix function score with query filtering and multiple sorting using also random seed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.