ElasticSearch random score combined with boost?

Viewed 2486

I am building a iOS app with Firebase, and using ElasticSearch as a search engine to get more advanced queries.

I am trying to achieve a system where I can get a random record from the index, based on a query. I have already got this working using the "random_score" function with a seed.

So all documents should right now have equal chance of being selected. Is it possible to add a boost or something(sorry, I am new to ES)?

Let's say the the document has the field "boost_enabled" and it set to true, the document will be 3 times more likely to be selected, so "increasing" the chance of being selected as a random?

So in theory it should look like this:

Documents that matches the query:

"document1"
"document2"
"document3"

They all have an equal chance of being selected (33%)

What I wish to achieve is if "document1" has the field "boost_enabled" = true

It should look like this:

"document1"
"document1"
"document1"
"document2"
"document3"

So now "document1" is 3 times more likely to be selected as the random record.

Would really appreciate some help.

EDIT:

I've come up with something like this, is this correct or not? I am pretty sure it's not though...

"query" : {
        "function_score": {
            "query": {
                "bool" : {
                    "must": {
                        "match_all": {}
                    },
                    "should": [
                        { "exists" : {
                            "field" : "boost_enabled",
                            "boost" : 3
                            }
                        }
                    ]
                    "filter" : filterArray
                 }
            },

            "functions": [
                {
                    "random_score": {"seed": seed}
                }
            ]
        }
    }

/ Mads

2 Answers

In ES 7.15 i use {script_score} key, below you can see my example.

This code "source": "_score + Math.random()" added random 0.0 -> 1.0 number to my native boosted score. For more information you can see this

{
    "size": { YOUR_SIZE_LIMIT },
    "query": {
        "script_score": {
            "query": {
                "query_string": {
                    "fields": [
                        "{ YOUR_FIELD_1 }^6",
                        "{ YOUR_FIELD_2 }^3",
                    ],
                    "query": "{ YOUR_SEARCH_QUERY }"
                }
            },
            "script": {
                "source": "_score + Math.random()"
            }
        }
    }
}
Related