Search in sources :

Example 1 with Scope

use of parsii.eval.Scope in project pinot by linkedin.

the class MetricExpression method evaluateExpression.

public static double evaluateExpression(String expressionString, Map<String, Double> context) throws Exception {
    Scope scope = Scope.create();
    expressionString = expressionString.replace(COUNT_METRIC, COUNT_METRIC_ESCAPED);
    Map<String, Double> metricValueContext = context;
    if (context.containsKey(COUNT_METRIC)) {
        metricValueContext = new HashMap<>(context);
        metricValueContext.put(COUNT_METRIC_ESCAPED, context.get(COUNT_METRIC));
    }
    Expression expression = Parser.parse(expressionString, scope);
    for (String metricName : metricValueContext.keySet()) {
        Variable variable = scope.create(metricName);
        if (!metricValueContext.containsKey(metricName)) {
            throw new Exception("No value set for metric:" + metricName + "  in the context:" + metricValueContext);
        }
        variable.setValue(metricValueContext.get(metricName));
    }
    return expression.evaluate();
}
Also used : Variable(parsii.eval.Variable) Scope(parsii.eval.Scope) Expression(parsii.eval.Expression) ParseException(parsii.tokenizer.ParseException)

Example 2 with Scope

use of parsii.eval.Scope in project pinot by linkedin.

the class MetricExpression method computeMetricFunctions.

public List<MetricFunction> computeMetricFunctions() {
    try {
        Scope scope = Scope.create();
        Set<String> metricNames = new TreeSet<>();
        // expression parser errors out on variables starting with _
        // we're replacing the __COUNT default metric, with an escaped string
        // after evaluating, we replace the escaped string back with the original
        String modifiedExpressions = expression.replace(COUNT_METRIC, COUNT_METRIC_ESCAPED);
        Parser.parse(modifiedExpressions, scope);
        metricNames = scope.getLocalNames();
        ArrayList<MetricFunction> metricFunctions = new ArrayList<>();
        for (String metricName : metricNames) {
            if (metricName.equals(COUNT_METRIC_ESCAPED)) {
                metricName = COUNT_METRIC;
            }
            metricFunctions.add(new MetricFunction(aggFunction, metricName));
        }
        return metricFunctions;
    } catch (ParseException e) {
        throw new RuntimeException("Exception parsing expressionString:" + expression, e);
    }
}
Also used : Scope(parsii.eval.Scope) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) ParseException(parsii.tokenizer.ParseException)

Aggregations

Scope (parsii.eval.Scope)2 ParseException (parsii.tokenizer.ParseException)2 ArrayList (java.util.ArrayList)1 TreeSet (java.util.TreeSet)1 Expression (parsii.eval.Expression)1 Variable (parsii.eval.Variable)1