我想在弹性搜索中实现加权随机分布。在我的索引中,每个文档的权重从1到N。因此,权重为1的元素出现在结果中的次数必须比权重为2的文档少2倍。 例如,我有3个文档(一个文档权重为2,两个文档权重为1):
[
{
"_index": "we_recommend_on_main",
"_type": "we_recommend_on_main",
"_id": "5-0",
"_score": 1.1245852,
"_source": {
"id_map_placement": 6151,
"image": "/upload/banner1",
"weight": 2
}
},
{
"_index": "we_recommend_on_main",
"_type": "we_recommend_on_main",
"_id": "8-0",
"_score": 0.14477867,
"_source": {
"id_map_placement": 6151,
"image": "/upload/banner1",
"weight": 1
}
},
{
"_index": "we_recommend_on_main",
"_type": "we_recommend_on_main",
"_id": "8-1",
"_score": 0.0837487,
"_source": {
"id_map_placement": 6151,
"image": "/upload/banner2",
"weight": 1
}
}
]
我找到了这样的搜索解决方案:
{
"size": 1,
"query": {
"function_score": {
"functions": [
{
"random_score": {}
},
{
"field_value_factor": {
"field": "weight",
"modifier": "none",
"missing": 1
}
}
],
"score_mode": "multiply",
"boost_mode": "replace"
}
},
"sort": [
{
"_score": "desc"
}
]
}
我以10000次的结果测试了此查询后
{
"5-0": 6730,
"8-1": 1613,
"8-0": 1657
}
但不是
{
"5-0": 5000,
"8-1": 2500,
"8-0": 2500
}
如我所料怎么了?
答案 0 :(得分:0)
不幸的是,这里的问题是-您对这种分布的假设是错误的。我们在这里有一个经典的概率论问题。变量A,B,C均匀分布(A,B在0和1之间,C在0和2之间)。我们需要找到C大于A或B的可能性。
说明:由于C均匀地分布在0和2之间,因此通过简单的公式,很明显,它有 50%概率分布在1和2之间,这自动表示它将大于A或B。
但是,在某些情况下,C会小于1但仍大于A或B,这使得概率严格大于 50%且远远大于50%。
分布的第二部分-所有三个变量都在0和1之间。C大于A或B的概率为 1/3 。但是,C仅在50%的时间分布在此处,这使该概率为1/6。总概率为1/2 + 1/6 = 4/6
,这大致等于您在蒙特卡洛模拟中得到的数字
已更新。无法实现预期的行为,因为您无法控制计分的时间,即何时收集汇总(如权重之和)。我建议以重新评分的方式进行操作,首先在字段上请求求和汇总,然后再使用它。