需求:以索引中的boostapp列作为评分的基础分值,同时根据carpublishtime(数据的刷新时间字段)按时间进行衰减。
基于Groovy脚本实现。
1、query脚本方式:
{"fields": ["boost","ucarid","boostapp","carpublishtime"],"query": {"function_score": {"query": {"match_all": {}},"functions": [{"script_score": {"script": "import java.util.Date;import java.text.DateFormat;import java.text.SimpleDateFormat;time2=((new Date().getTime()- new SimpleDateFormat('yyyy-MM-dd HH:mm:ss').parse(_source.carpublishtime.replace('T',' ')).getTime())/60000);if(time2<=60)_source.boostapp+time2/5 else if(time2<=120)_source.boostapp+(time2/10-6)*8 else if(time2<=180)_source.boostapp+(time2/10-12)*5 else _source.boostapp"}}],"boost_mode": "replace","score_mode": "sum"}},"from": 0,"size": 10 }
2、Nest方式:
QueryContainer mainQuery = null;
FunctionScoreQuery funcQuery = new FunctionScoreQuery();
funcQuery.ScoreMode = FunctionScoreMode.Sum;
funcQuery.BoostMode = FunctionBoostMode.Replace;
funcQuery.MaxBoost = 1000.0f;
ScriptFilter scriptFilter = new ScriptFilter();
scriptFilter.Script = "import java.util.Date;import java.text.DateFormat;import java.text.SimpleDateFormat;time2=((new Date().getTime()- new SimpleDateFormat('yyyy-MM-dd HH:mm:ss').parse(_source.carpublishtime.replace('T',' ')).getTime())/60000);if(time2<=60)_source.boostapp+time2/5 else if(time2<=120)_source.boostapp+(time2/10-6)*8 else if(time2<=180)_source.boostapp+(time2/10-12)*5 else _source.boostapp";
funcQuery.ScriptScore = scriptFilter;
mainQuery &= funcQuery;