I need to obtain a random sample from an ElasticSearch index, i.e. to issue a query that retrieves some documents from a given index with weighted probability Wj/ΣWi
(where Wj
is a weight of row j
and Wj/ΣWi
is a sum of weights of all documents in this query).
Currently, I have the following query:
GET products/_search?pretty=true
{"size":5,
"query": {
"function_score": {
"query": {
"bool":{
"must": {
"term":
{"category_id": "5df3ab90-6e93-0133-7197-04383561729e"}
}
}
},
"functions":
[{"random_score":{}}]
}
},
"sort": [{"_score":{"order":"desc"}}]
}
It returns 5 items from selected category, randomly.
Each item has a field weight
. So, I probably have to use
"script_score": {
"script": "weight = data['weight'].value / SUM; if (_score.doubleValue() > weight) {return 1;} else {return 0;}"
}
as described here.
I have the following issues:
- What is the correct way to do this?
- Do I need to enable Dynamic Scripting?
- How to calculate the total sum of the query?
Thanks a lot for your help!