How to access java methods inside of painless

I would like to do a popcount over a long field inside of a painless script, but I do not understand the documentation here. There is no single example in how to access native java functions inside of painless.

"script": {
"lang": "painless",
"source": "return BitCount(params.p1^doc[params.p2].value);"

This does not work...

I think there's no way to call java functions inside scripts, if there's an option to that, there's no documentation talking about it.

Besides that, if it fixes your problem, the JS API allows functions inside scripts, so you could use it, depending on what are your goals.

The stuff I need is there: I simply have no Idea how to access them, it would be awesome if the documentation could cover that...

are you trying to do something like this?

script(new Script(ScriptType.INLINE,ctx._source.field = "+java method,"painless", Collections.emptyMap()));

No I want to access the BitCount method of java.lang.Long and it simply does not work...

return Long.bitCount(31416);

(You also had a typo.)
This also works although I think I never saw an example doing it like that:

return java.lang.Long.bitCount(31416);

Imagine the package is imported:

import java.lang.*;

Apply this to all available packages in the context in which your are.

There are example in the docs but I'm not saying that because I disagree with your documentation improvement suggestion. I'm not a born developer and I'm intimidated by painless myself and it's kinda required to do alarming with the Watcher feature.

See the example on this page for an example of an example :slight_smile: :

int hours = Integer.parseInt(timeSplit[0].trim());
ZonedDateTime dt = ZonedDateTime.parse(
         dts, DateTimeFormatter.ISO_OFFSET_DATE_TIME);               
ctx.datetime = dt.getLong(ChronoField.INSTANT_SECONDS)*1000L;

From a Kibana dev tool console:

POST /_scripts/painless/_execute
  "script": {
    "source": "return Long.bitCount(params.var1);",
    "params": {
      "var1": 666,
      "var2": 66666


  "result": "5"

Not directly related but sites like this one (first link out of googling "java Long.bitCount example") help me sometimes because as I said not a formally trained developer:


Awesome thank you.

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