Painless scripts: "else if" and ternary conditionals checking field existence don't work properly

ES: 6.1.1
NEST: 6.1

As I've researched, I've tried two different methods of conditionally populating a "date" variable using both containsKey and doc['field'].value != null with the same outcome. I've used both "else if" and, having read somewhere that painless doesn't support "else if", I tried a ternary construct. The issue is, only the first conditional check seems to engage. Both methods not only compile but also produce the same results when used for filtering. Here are the two methods:
1.

POST _scripts/filterImpliedPublishDateRange
{
 "script": {
  "lang": "painless",
  "source":
"""
double now = params['now'];
double from = params['from'], to = params['to'];
double impliedPublishDate = 0.0;
if (doc.containsKey('publishDate'))
{
 impliedPublishDate = doc['publishDate'].value.getMillis();
}
else if (doc.containsKey('dateCreated'))
{
 impliedPublishDate = doc['dateCreated'].value.getMillis();
}
else if (doc.containsKey('modifiedDate'))
{
 impliedPublishDate = doc['modifiedDate'].value.getMillis();
}
double days = (now - impliedPublishDate) / (3600000.0*24);
return ((days > from) && (days <= to));
"""
 }
}
POST _scripts/filterImpliedPublishDateRange
{
  "script": {
    "lang": "painless",
    "source":
"""
double now = params['now'];
double from = params['from'], to = params['to'];
double impliedPublishDate = doc['publishDate'].value != null ? doc['publishDate'].value.getMillis() : doc['dateCreated'].value != null ? doc['dateCreated'].value.getMillis() : doc['modifiedDate'].value != null ? doc['modifiedDate'].value.getMillis() : 0.0;
double days = (now - impliedPublishDate) / (3600000.0*24);
return ((days > from) && (days <= to));
"""
  }
}

Both of these approaches evidently only use whichever is the first field I specify, publishDate, dateCreated, etc. and it doesn't seem to fall back to the next conditional for documents which don't have the field I specify in the first if. There are many documents that have one of the fields I'm checking for. Whichever field I choose first does yield the correct number and range of documents. For some reason, it just doesn't consider the documents where the first conditional is false.

So, a co-worker of mine discovered that what I needed was !doc['publishDate'].empty. How that differs from containsKey or value != null escapes me because I haven't found any comprehensive documentation any of those 3 expressions but I can say that the empty approach produces the result I expect.

Anyone have any pointers to painless documentation on these 3? I found Lucene Expressions Language but that still doesn't really distinguish the difference between checking the value for null and empty.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.