Random function in Painless?

Hello,
What is the way to genereate a random value in Painless?

Being able to draw one value from a set would be particularly great - I want to use it to add a new field to my mock data and I need a possibility to add one of the statuses ('Working', 'Archived', 'InReview') to my documents at random.

You have access to Random in painless. Alternatively, if you have something like a timestamp in your mock data, you can calculate something like timestamp % 3 and assign 'Working', 'Archived', or 'InReview' based on the value.

1 Like

Thank you, that's what I was looking for!

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

Just commenting here so we have a complete example to copy/paste for anyone else reading this thread:

# choose random element from array with 6 entries:
PUT _ingest/pipeline/random_element_pipeline
{
  "processors": [
    {
      "script": {
        "source": """ 
        Random r = new Random();
        ctx.region = ctx.region[r.nextInt(6) - 1];
        """
      }
    }
  ]
}

You have access to

class java.util.Random {
  () @nondeterministic
  (long)
  DoubleStream doubles(long) @nondeterministic
  DoubleStream doubles(long,double,double) @nondeterministic
  IntStream ints(long) @nondeterministic
  IntStream ints(long,int,int) @nondeterministic
  LongStream longs(long) @nondeterministic
  LongStream longs(long,long,long) @nondeterministic
  boolean nextBoolean() @nondeterministic
  void nextBytes(byte[]) @nondeterministic
  double nextDouble() @nondeterministic
  float nextFloat() @nondeterministic
  double nextGaussian() @nondeterministic
  int nextInt() @nondeterministic
  int nextInt(int) @nondeterministic
  long nextLong() @nondeterministic
  void setSeed(long)
}