es 商品搜索自定义评分案例
需求:商品搜索按相关比例排序
搜索相关度(es已知分值)60% * 销量(未知分值)40%
如果总分是10 = 搜索相关度得分6 + 销量得分4
假设搜索相关度=6分。那么销量最高分为4分。根据销量值比例算出相关的分值。假如销量最高值是4,那就是4分。但是目前不知道销量的最高值:
y = x / 6 * 4
x=搜索分值,y的销量总分分值
/skus/_search?explain
{
"query": {
"function_score": {
"query": {
"match": {
"name": "手机"
}
},
"script_score": {
"script": "return (_score * 4.0 / 6.0) * (1d / (1d + exp(-log(doc['categoryId'].value+1d)/10)))"
}
,
"boost_mode": "sum"
}
}
}
公式说明:
(_score * 4.0 / 6.0)为计算出来的销量最高得分值(如总分是10分,那么就是4分)
(1d / (1d + exp(-log(doc['categoryId'].value+1d)/10))) 将categoryId字段衰减至 0 - 1 的小数。
1.搜索相关度 50%
2.促销活动 30%
3.商品利润 20% (gross)
多个字段,判断是否为null
{
"query": {
"function_score": {
"query": {
"match": {
"name": "手机"
}
},
"script_score": {
"script": "categoryIdScore = 0; if(_source.categoryId!=null){(_score * 3.0 / 5.0) * (1d / (1d + exp(-log(doc['categoryId'].value+1d)/10))) }; preferentialScore = 0 ; if(_source.preferentialType!=null && _source.preferentialType!=0){preferentialScore = (_score * 2.0 / 5.0)}; return categoryIdScore + preferentialScore;"
}
,"boost_mode": "sum"
}
}
}