在 Drools 中获取相似对象

Get similar objects in Drools

假设我有一个衬衫类型的对象列表,并且每件衬衫都有一种颜色 属性。 有没有一种方法可以创建一个规则,该规则将只获得相同颜色的衬衫(无论颜色是什么)?

您正在寻找 collect function。 (Link 指向 Drools 文档,向下滚动一点找到“收集”。)正如其名称所示,它收集符合条件的内容。

让我们假设一个简单的 class Shirt 和一个字符串 color 变量。我们还假设工作记忆中有各种衬衫实例。

rule "Collect shirts by color"
when
  Shirt( $color: color )
  $shirts: List() from collect( Shirt( color === $color ) )
then
  // $shirts will now contain all shirts of $color
end

此规则将单独考虑每件衬衫,然后收集所有其他颜色相同的衬衫。因此,如果您有红色、蓝色和绿色衬衫,您将至少一次进入右侧 $shirts 这种单一颜色。

当然,这里的问题是您将在每件衬衫的基础上而不是在每种颜色的基础上触发规则。因此,如果您有两件红色衬衫,您将触发所有红色衬衫的 'then' 子句两次(每件红色衬衫一次,因为每件红色衬衫将独立满足第一个条件。)

如果您不介意这一点,那么您可以按原样使用它。但是,如果您只想让您的结果针对每种衬衫颜色触发一次,我们就必须更巧妙一些。

为了让颜色成为第一个 class 公民,我们需要提取不同的衬衫颜色集(不是列表!),然后根据需要使用它们来收集我们的列表。这里我使用了accumulate函数;您可以在我之前与 Drools 文档共享的 link 中阅读更多相关信息(accumulate 直接在 collect 之后。)

rule "Get shirt colors"
when
  // Get all unique shirt colors
  $colors: Set() from accumulate( Shirt( $color: color), collectSet( $color ))

  // Get one of those colors
  $color: String() from $colors

  // Find all shirts of that color
  $shirts: List() from collect( Shirt( color === $color ) )
then
  // $shirts is all shirts of $color
end

在第二条规则中,每种颜色只会触发一次右侧,因为我们首先将所有可能的颜色提炼成一组不同的独特颜色。


反之则更简单。如果您需要做的只是确认至少有一件衬衫颜色不同,我们只需要获取所有颜色并验证至少存在 2 种不同颜色。

rule "At least one shirt of a different color"
when
  $colors: Set( size > 1 ) from accumulate( 
    Shirt( $color: color), 
    collectSet( $color )
  )
then
  // $colors contains more than 1 color, so there's at
  // least 1 shirt present that is not the same color
  // as the rest
end