I’m using ELK – 7.12.1 and in Kibana dashboard i need to filter below holidays date using painless.
01-Jan-2021
14-Jan-2021
26-Jan-2021
11-Mar-2021
02-Apr-2021
13-Apr-2021
14-May-2021
21-Jul-2021
10-Sep-2021
15-Oct-2021
01-Nov-2021
05-Nov-2021
Scripted Painless that i have as follows.
Language: painless
Type: string
Format: String
Script:
def month = doc['@timestamp'].value.getMonthValue();
def day = doc['@timestamp'].value.getDayOfMonth();
if (month == 1){
if ((day == 01) || (day == 14) || (day == 26) || (day == 11) || (day == 02) || (day == 13) || (day == 21) || (day == 10) || (day == 15) || (day == 05)) {
return true
}
else {
return false
}
}
Index Patterns > my-index > Scripted fields > holidays > Preview result
[
{
"_id": "38009464",
"@timestamp": "2021-02-26T11:11:39.707Z",
"holidays": [
null
]
},
{
"_id": "38026158",
"@timestamp": "2021-02-26T11:11:39.727Z",
"holidays": [
null
]
},
{
"_id": "38030065",
"@timestamp": "2021-02-26T11:11:39.735Z",
"holidays": [
null
]
It returns null
. So how i can fix this to filter true (or) false? As
this will check if the timestamp is in any of those days and returns true if it is. And then just need to filter on the dashboard for holiday = False is the idea.
Can someone help me to fix this? It ll be helpful.
You are seeing a null-value because your script, when it is not January does not return anything. The external if does not have an else counterpart. What happens when no condition match?
NOTE: Currently, despite your introduction, your script is returning:
You need to fix your script to cover all cases not only January. You can simply add an else condition as follows.
def month = doc['@timestamp'].value.getMonthValue();
def day = doc['@timestamp'].value.getDayOfMonth();
if (month == 1){
if ((day == 01) || (day == 14) || (day == 26) || (day == 11) || (day == 02) || (day == 13) || (day == 21) || (day == 10) || (day == 15) || (day == 05)) {
return true
}
else {
return false
}
} else {
return false;
}
or even better:
def month = doc['@timestamp'].value.getMonthValue();
def day = doc['@timestamp'].value.getDayOfMonth();
if (month == 1){
if ((day == 01) || (day == 14) || (day == 26) || (day == 11) || (day == 02) || (day == 13) || (day == 21) || (day == 10) || (day == 15) || (day == 05)) {
return true
}
}
// No previous condition matches, return false
return false;
So you are pretty far from the solution you are searching.
To fix your script to work you should cover all cases (correctly). Given a shorter list:
01-Jan-2021 --> 01.01.2021
14-Jan-2021 --> 14.01.2021
26-Jan-2021 --> 26.01.2021
11-Mar-2021 --> 11.03.2021
if(month == 1) {
// Given is January
if([01, 14, 26].contains(day)) {
return true;
}
} else if (month == 3) {
// Given is March
if (day == 11) {
return true;
}
}
// If the date is not in the blacklist
return false;
Obviously, here I did not cover all the cases (which provided this answer should easy to implement) nor the year, but perhaps you should consider it.
Kind regards, Mirko