[英]ElasticSearch Rails: Sort by date1 if it's present and in the future, else sort by date2
Above are two different records from a Posts
model we have stored in elasticsearch.以上是来自Posts
model 的两条不同记录,我们存储在 elasticsearch 中。 We're trying to put in logic that will put our sticky posts in the feed like regular posts after they've expired.我们正在尝试添加逻辑,使我们的粘性帖子在它们过期后像常规帖子一样放在提要中。
We want to have it say我们想让它说
"If is_sticky
AND stickied_until
is in the future sort by stickied_until
, else sort by created_at
" “如果is_sticky
AND stickied_until
将来按stickied_until
排序,否则按created_at
排序”
I think I have it working in SQL (since we store the bulk of the data there and only the searchable fields in ES), which looks like我想我可以在 SQL 中使用它(因为我们将大部分数据存储在那里,并且只有 ES 中的可搜索字段),看起来像
ORDER BY
CASE
WHEN stickied_until >= '#{DateTime.now.utc}'
THEN stickied_until
ELSE created_at
END DESC
but then there's two things controlling the sort, which I'm pretty sure will cause bugs, and also just feels wrong.但是有两件事控制排序,我很确定这会导致错误,而且感觉不对。
Is it possible to do this kind of conditional sorting in ES?是否可以在 ES 中进行这种条件排序?
You'll have to use a sort script for this.您必须为此使用排序脚本。
{
"sort": [
{
"_script": {
"type": "number",
"script": {
"lang": "painless",
"source": """
def is_sticky = doc['is_sticky'].value;
def created_at = doc['created_at'].value.getMillis();
if (!is_sticky) {
return created_at;
}
def stickied_until = doc['stickied_until'].value.getMillis();
def now = params['now'];
if (is_sticky && stickied_until > now) {
return stickied_until;
}
return created_at;
""",
"params": {
"now": 1586798403888
}
},
"order": "desc"
}
}
]
}
Note that I've used query-time constant params['now']
due to reasons explained in the docs .请注意,由于文档中解释的原因,我使用了查询时间常量params['now']
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.