MST
星途 面试题库

面试题:ElasticSearch脚本字段的复杂逻辑实现

假设文档中有一个日期字段'timestamp',现在要通过脚本字段根据'timestamp'计算文档距离当前时间的天数差,且仅在满足某个特定条件(如另一个字段'category'为'important')时才计算,写出完整的ElasticSearch查询语句及脚本实现。
49.7万 热度难度
数据库ElasticSearch

知识考点

AI 面试

面试题答案

一键面试
{
    "query": {
        "bool": {
            "filter": [
                {
                    "term": {
                        "category": "important"
                    }
                }
            ]
        }
    },
    "script_fields": {
        "days_since_timestamp": {
            "script": {
                "source": "def now = new Date(); def timestampDate = new Date(doc['timestamp'].value); return (now.getTime() - timestampDate.getTime()) / (24 * 60 * 60 * 1000);"
            }
        }
    }
}