Skip to content

n8n 条件逻辑与分支控制 - 让工作流更智能

在实际的业务场景中,我们经常需要根据不同的条件执行不同的操作。今天我们来学习如何在 n8n 中实现条件逻辑和分支控制,让工作流变得更加智能和灵活。

条件控制节点概览

n8n 提供了几种不同的条件控制节点:

节点类型用途适用场景
IF二分支条件判断简单的是/否判断
Switch多分支条件判断多种情况的分类处理
Merge合并多个分支分支处理后的数据合并

IF 节点详解

IF 节点是最常用的条件控制节点,提供 true 和 false 两个分支。

基本配置

json
{
  "conditions": {
    "string": [
      {
        "value1": "={{ $json.status }}",
        "operation": "equal",
        "value2": "active"
      }
    ]
  }
}

支持的条件类型

字符串条件

  • equal:等于
  • notEqual:不等于
  • contains:包含
  • notContains:不包含
  • startsWith:以...开始
  • endsWith:以...结束
  • regex:正则表达式匹配

数字条件

  • equal:等于
  • notEqual:不等于
  • larger:大于
  • largerEqual:大于等于
  • smaller:小于
  • smallerEqual:小于等于

布尔条件

  • equal:等于
  • notEqual:不等于

日期条件

  • equal:等于
  • notEqual:不等于
  • after:之后
  • before:之前

实际应用案例

案例1:订单状态处理

json
{
  "conditions": {
    "string": [
      {
        "value1": "={{ $json.orderStatus }}",
        "operation": "equal",
        "value2": "paid"
      }
    ],
    "number": [
      {
        "value1": "={{ $json.amount }}",
        "operation": "larger",
        "value2": 1000
      }
    ]
  },
  "combineOperation": "all"
}

案例2:用户权限检查

json
{
  "conditions": {
    "string": [
      {
        "value1": "={{ $json.userRole }}",
        "operation": "equal",
        "value2": "admin"
      }
    ]
  }
}

案例3:时间范围判断

json
{
  "conditions": {
    "dateTime": [
      {
        "value1": "={{ $json.createdAt }}",
        "operation": "after",
        "value2": "={{ $now.minus({days: 7}) }}"
      }
    ]
  }
}

Switch 节点详解

Switch 节点适合处理多种情况的分支逻辑,类似编程语言中的 switch 语句。

基本配置

json
{
  "mode": "expression",
  "output": "input",
  "rules": {
    "rules": [
      {
        "type": "expression",
        "value": "={{ $json.priority === 'high' }}",
        "output": 0
      },
      {
        "type": "expression", 
        "value": "={{ $json.priority === 'medium' }}",
        "output": 1
      },
      {
        "type": "expression",
        "value": "={{ $json.priority === 'low' }}",
        "output": 2
      }
    ]
  }
}

实际应用案例

案例1:客服工单分配

javascript
// 在 Code 节点中预处理数据
const ticket = items[0].json;
let routingKey = 'general';

if (ticket.category === 'technical') {
  routingKey = 'tech_support';
} else if (ticket.category === 'billing') {
  routingKey = 'billing_team';
} else if (ticket.priority === 'urgent') {
  routingKey = 'urgent_queue';
}

return [{
  json: {
    ...ticket,
    routingKey
  }
}];

案例2:邮件分类处理

json
{
  "rules": {
    "rules": [
      {
        "type": "expression",
        "value": "={{ $json.subject.includes('订单') }}",
        "output": 0
      },
      {
        "type": "expression",
        "value": "={{ $json.subject.includes('退款') }}",
        "output": 1
      },
      {
        "type": "expression",
        "value": "={{ $json.subject.includes('投诉') }}",
        "output": 2
      }
    ]
  }
}

复杂条件逻辑

多条件组合

AND 逻辑(所有条件都满足)

json
{
  "conditions": {
    "string": [
      {
        "value1": "={{ $json.status }}",
        "operation": "equal",
        "value2": "active"
      }
    ],
    "number": [
      {
        "value1": "={{ $json.score }}",
        "operation": "largerEqual",
        "value2": 80
      }
    ]
  },
  "combineOperation": "all"
}

OR 逻辑(任一条件满足)

json
{
  "conditions": {
    "string": [
      {
        "value1": "={{ $json.type }}",
        "operation": "equal",
        "value2": "premium"
      },
      {
        "value1": "={{ $json.type }}",
        "operation": "equal",
        "value2": "vip"
      }
    ]
  },
  "combineOperation": "any"
}

使用表达式进行复杂判断

javascript
// 在表达式中使用复杂逻辑
{{ 
  $json.age >= 18 && 
  $json.income > 50000 && 
  ($json.creditScore > 700 || $json.hasCollateral === true)
}}

嵌套条件

javascript
// 在 Code 节点中实现嵌套条件
const user = items[0].json;
let category = 'standard';

if (user.isPremium) {
  if (user.loyaltyYears >= 5) {
    category = 'platinum';
  } else if (user.loyaltyYears >= 2) {
    category = 'gold';
  } else {
    category = 'silver';
  }
} else {
  if (user.totalSpent > 10000) {
    category = 'potential_premium';
  }
}

return [{
  json: {
    ...user,
    category
  }
}];

数据驱动的条件逻辑

动态条件配置

javascript
// 从配置数据中读取条件规则
const rules = [
  { field: 'amount', operator: '>', value: 1000, action: 'approve' },
  { field: 'riskScore', operator: '<', value: 30, action: 'approve' },
  { field: 'country', operator: '==', value: 'CN', action: 'manual_review' }
];

const data = items[0].json;
let action = 'reject'; // 默认动作

for (const rule of rules) {
  const fieldValue = data[rule.field];
  let conditionMet = false;
  
  switch (rule.operator) {
    case '>':
      conditionMet = fieldValue > rule.value;
      break;
    case '<':
      conditionMet = fieldValue < rule.value;
      break;
    case '==':
      conditionMet = fieldValue === rule.value;
      break;
  }
  
  if (conditionMet) {
    action = rule.action;
    break;
  }
}

return [{
  json: {
    ...data,
    action,
    processedAt: new Date().toISOString()
  }
}];

基于历史数据的条件判断

javascript
// 结合历史数据进行判断
const currentOrder = items[0].json;
const customerHistory = items[0].json.customerHistory || [];

// 计算客户统计信息
const totalOrders = customerHistory.length;
const totalSpent = customerHistory.reduce((sum, order) => sum + order.amount, 0);
const avgOrderValue = totalOrders > 0 ? totalSpent / totalOrders : 0;
const lastOrderDate = customerHistory.length > 0 
  ? new Date(Math.max(...customerHistory.map(o => new Date(o.date))))
  : null;

// 判断客户等级
let customerTier = 'new';
if (totalOrders >= 10 && totalSpent >= 5000) {
  customerTier = 'vip';
} else if (totalOrders >= 5 && totalSpent >= 2000) {
  customerTier = 'regular';
}

// 判断是否需要特殊处理
const needsSpecialHandling = 
  currentOrder.amount > avgOrderValue * 3 ||
  (lastOrderDate && (Date.now() - lastOrderDate.getTime()) > 90 * 24 * 60 * 60 * 1000);

return [{
  json: {
    ...currentOrder,
    customerTier,
    needsSpecialHandling,
    customerStats: {
      totalOrders,
      totalSpent,
      avgOrderValue
    }
  }
}];

错误处理与异常分支

使用 IF 节点处理错误

json
{
  "conditions": {
    "boolean": [
      {
        "value1": "={{ $json.hasError }}",
        "operation": "equal",
        "value2": true
      }
    ]
  }
}

数据验证分支

javascript
// 数据验证和错误处理
const data = items[0].json;
const errors = [];

// 验证必填字段
const requiredFields = ['name', 'email', 'phone'];
requiredFields.forEach(field => {
  if (!data[field] || data[field].toString().trim() === '') {
    errors.push(`${field} is required`);
  }
});

// 验证数据格式
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (data.email && !emailRegex.test(data.email)) {
  errors.push('Invalid email format');
}

const phoneRegex = /^1[3-9]\d{9}$/;
if (data.phone && !phoneRegex.test(data.phone)) {
  errors.push('Invalid phone format');
}

return [{
  json: {
    ...data,
    isValid: errors.length === 0,
    errors: errors,
    validationResult: errors.length === 0 ? 'success' : 'failed'
  }
}];

Merge 节点应用

Merge 节点用于合并不同分支的数据流。

合并模式

Append 模式

json
{
  "mode": "append",
  "output": "input1"
}

Pass-through 模式

json
{
  "mode": "passThrough",
  "output": "input1"
}

Wait 模式

json
{
  "mode": "wait",
  "output": "input1"
}

实际应用

数据处理后合并

数据输入 → IF 节点
           ├─ True 分支 → 处理A → Merge
           └─ False 分支 → 处理B → Merge

                               后续处理

性能优化技巧

条件优化

javascript
// 优化条件判断顺序,将最可能为真的条件放在前面
if (data.isVip) {
  // VIP 用户处理逻辑(假设大部分用户是 VIP)
  return processVipUser(data);
} else if (data.isPremium) {
  // Premium 用户处理逻辑
  return processPremiumUser(data);
} else {
  // 普通用户处理逻辑
  return processRegularUser(data);
}

避免重复计算

javascript
// 将复杂计算结果缓存
const data = items[0].json;
const riskScore = calculateRiskScore(data); // 假设这是一个复杂计算

let action;
if (riskScore > 80) {
  action = 'reject';
} else if (riskScore > 50) {
  action = 'manual_review';
} else {
  action = 'approve';
}

return [{
  json: {
    ...data,
    riskScore,
    action
  }
}];

调试条件逻辑

添加调试信息

javascript
// 在条件判断中添加调试信息
const data = items[0].json;
const debugInfo = {
  originalData: data,
  conditions: {},
  finalDecision: null
};

// 检查各个条件
debugInfo.conditions.ageCheck = data.age >= 18;
debugInfo.conditions.incomeCheck = data.income > 50000;
debugInfo.conditions.creditCheck = data.creditScore > 700;

// 最终决策
const approved = debugInfo.conditions.ageCheck && 
                debugInfo.conditions.incomeCheck && 
                debugInfo.conditions.creditCheck;

debugInfo.finalDecision = approved ? 'approved' : 'rejected';

return [{
  json: {
    ...data,
    approved,
    debug: debugInfo
  }
}];

使用 Console 节点

在关键分支点添加 Console 节点来输出调试信息:

javascript
console.log('Condition check:', {
  value: $json.status,
  condition: $json.status === 'active',
  timestamp: new Date().toISOString()
});

小结

条件逻辑是构建智能工作流的核心技能:

  1. 选择合适的节点:IF 用于简单分支,Switch 用于多分支
  2. 合理设计条件:考虑性能和可维护性
  3. 处理边界情况:确保所有可能的情况都有对应的处理
  4. 添加调试信息:便于问题排查和逻辑验证
  5. 优化性能:避免重复计算和不必要的条件检查

下一篇文章,我们将学习循环和批处理技术,这对于处理大量数据非常重要。

记住,好的条件逻辑设计不仅要功能正确,还要考虑可读性和维护性。清晰的逻辑结构会让工作流更容易理解和修改。