问题
A SubjectTeacherPeriod
has a num_attribute_map
, which is a map that maps certain attributes (such as "boringness") with their respective scores. I use the following code to sum attributes (such as "boringness") over each day of the week.
But a certain line causes an error.
rule "insertAttributeDayTotal"
//salience 1 // Do these rules first (optional, for performance)
when
$sum_regression_constraint : SumRegressionConstraint(
$class : class_,
$attribute : attribute//,
//$weight : weight;
)
$day_of_week : DayOfWeek()
$attribute_day_total : Number() from accumulate(
SubjectTeacherPeriod(
//period != null,
period.class_ == $class,
period.dayOfWeek == $day_of_week,
$total : num_attribute_map[$attribute] //PROBLEM LINE
),
sum($total)
)
then
//System.out.println("BUCKET TOTAL "+$id+" "+$bucket_total.intValue());
insertLogical(new AttributeDaySum($class, $attribute, $day_of_week, $attribute_day_total.intValue()));
end
The error is:
jesvin@Jesvin-Technovia:~/dev/drools/timetabler$ java -server in.co.technovia.timetabler.TimeTableApp
Exception in thread "main" java.lang.IllegalStateException: There are errors in the scoreDrl's:
Variables can not be used inside bindings. Variable [$attribute] is being used in binding 'num_attribute_map[$attribute]' : [Rule name='insertAttributeDayTotal']
Rule Compilation error : [Rule name='insertAttributeDayTotal']
in/co/technovia/timetabler/domain/Rule_insertAttributeDayTotal_bb39fd28b3c8457cb8d86fc15b34a0e7.java (7:905) : Syntax error on token "null", invalid Type
in/co/technovia/timetabler/domain/Rule_insertAttributeDayTotal_bb39fd28b3c8457cb8d86fc15b34a0e7.java (9:1050) : $total cannot be resolved
SubjectTeacherPeriod
has the curious num_attribute_map
so that I can define attributes at runtime. If I wanted a boringness
(int) attribute for SubjectTeacherPeriod
, I can do num_attribute_map.put("boringness",1)
instead of adding a new attribute to SubjectTeacherPeriod
.
A SumRegressionConstraint
cares about a particular $attribute
. That attribute's value is stored in num_attribute_map
of SubjectTeacherPeriod
. I want to access num_attribute_map[$attribute]
but this problem shows up.
What am I doing wrong?
Is there any other way to get dynamic attributes to work?
回答1:
At the moment, you can't bind a variable to expressions, only to field names. So instead of binding it to:
$total : num_attribute_map[$attribute]
Bind it to:
$total : num_attribute_map
Then, you can use the expression on the function. If you are using the MVEL dialect:
sum( $total[$attribute] )
Or if you are using the java dialect:
sum( $total.get($attribute) )
来源:https://stackoverflow.com/questions/9444470/summing-values-of-an-objects-map-gives-me-errors