# Data Lookup

> 根据指定键，从给定的字典或映射中取值。

Source: https://docs.sommatic.ai/zh/nodes/data.lookup/

- 标识: `data.lookup`
- 类别: 数据
- 版本: 1.0.0
- 状态: 可用
- 执行方式: sync

根据指定键，从给定的字典或映射中取值。

该算子用于简单的参考数据增强。它接收一个静态或动态的源映射，并尝试为输入键找到匹配项。

**适用场景：**
- **数据增强：** 根据“国家代码”查找“国家名称”（例如“US” -> “United States”）。
- **映射：** 转换状态码（例如 200 -> “OK”）。
- **授权：** 检查某个用户 ID 是否在“管理员列表”中。

## 配置

- `source` (object, 必填): 用于查找的键值对（例如 {"US": "United States"}）。
- `key_template` (string, 必填, 支持表达式): 在字典中查找的键或点分路径（lodash get）。使用 {{ }} 从载荷中推导，例如 {{ $json.country_code }}。不支持 JSONata。

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `found` (默认): 字典中存在该键。
- `miss`: 未找到该键。
- `error`: Error

## 输入契约

- `payload` (object, 可选): 用于解析键的上下文。

## 输出契约

- `value` (any, 可选): 从字典中取得的值。
- `found` (boolean, 可选)

## 在表达式中

后续节点可通过 `$("Data Lookup").item.json.<路径>` 读取此节点输出中的内容（请把 `Data Lookup` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `found` 返回的路径，依据“端口”一节所示的输出。

- `$("Data Lookup").item.json.value` (any): 从字典中取得的值。 **worker 不返回：读取结果为 undefined.**
- `$("Data Lookup").item.json.found` (boolean) **worker 不返回：读取结果为 undefined.**
- `$("Data Lookup").item.json.country_code` (string) = `"US"` (编辑器不提示)
- `$("Data Lookup").item.json.lookup_result` (string) = `"United States"` (编辑器不提示)


## 工作原理

使用 lodash `get` 在字典中查找键或点分路径：找到时走 `found` 并以 `lookup_result` 添加值，否则走 `miss` 且 payload 不变。

1. 解析配置：`source` 和 `key_template` 中的 `{{ }}` 由 Expression Engine 求值。
2. `key_template` 缺失或解析为空值时失败。
3. 将键转为字符串并用 `_.get(source, key)` 读取：支持点分路径和 `regions.north[0]` 这类索引。不使用 JSONata。
4. 除 `undefined` 以外的任何值（包括 `null`）都算找到：通过 `found` 返回 payload 加上 `lookup_result`。
5. 否则通过 `miss` 原样返回 payload。两种情况都会设置 `meta` `{ found, key }`。

## 在工作流中

### 节点

```json
{
  "node_id": "node-country-name",
  "label": "Country name",
  "operator_slug": "data.lookup",
  "operator_version": "1.0.0",
  "config": {
    "source": {
      "US": "United States",
      "CO": "Colombia",
      "MX": "Mexico"
    },
    "key_template": "{{ $json.country_code }}"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "country_code": "US",
    "lookup_result": "United States"
  },
  "meta": {
    "found": true,
    "key": "US"
  },
  "port": "found"
}
```

## 输出端口 (代码中的行为)

### `found`

`source` 中存在该键。

```json
{
  "country_code": "US",
  "lookup_result": "United States"
}
```

### `miss`

`source` 中不存在该键。

```json
{
  "country_code": "BR"
}
```

### `error`

`key_template` 为空。

```json
{
  "ok": false,
  "errors": [
    "Key template is required"
  ],
  "port": "error"
}
```

## 代码中的行为

- `key_template`: 不含 `{{ }}` 的文本被视为字面键。要从 payload 读取键，请写 `{{ $json.country_code }}`。
- `source`: 缺失时默认为 `{}`，因此所有查找都会落空。也可以是返回先前节点对象的 `{{ }}`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Key template is required` | `error` | `key_template` 缺失，或其 `{{ }}` 解析为 `undefined`、`null`、`""`、`0` 或 `false`。 |

## 说明与限制

- 输出键为 `lookup_result`；输出契约中的 `value` 和 `found` 字段不会生成（`found` 只存在于 `meta`）。
- `meta` 只记录在运行步骤中：下游节点收到的 payload 是 `data`，无法通过 `$json` 或 `$("Node")` 读取 `meta`。
- 当返回的信封没有 `data`（或 `data` 为假值）时，引擎会把整个信封作为节点输出：经 `error` 端口时，下一个节点收到的 payload 是 `{ ok: false, errors: [...], port: "error" }`。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "data.lookup",
  "name": "Data Lookup",
  "category": "data",
  "version": "1.0.0",
  "description": "Retrieves a value from a provided dictionary or map based on a specific key.\n\n  This operator is used for simple reference data enrichment. It takes a static or dynamic source map and attempts to find a match for the input key.\n\n  **Use Cases:**\n  - **Enrichment:** looking up a \"Country Name\" from a \"Country Code\" (e.g., \"US\" -> \"United States\").\n  - **Mapping:** Translating status codes (e.g., 200 -> \"OK\").\n  - **Authorization:** Checking if a User ID exists in an \"Admin List\".",
  "capabilities": [
    "enrichment",
    "map",
    "dictionary"
  ],
  "config_schema": {
    "type": "object",
    "required": [
      "source",
      "key_template"
    ],
    "properties": {
      "source": {
        "type": "object",
        "title": "Dictionary / Map",
        "description": "Key-Value pairs to search within (e.g., {\"US\": \"United States\"})."
      },
      "key_template": {
        "type": "string",
        "title": "Key Expression",
        "format": "expression",
        "description": "Key or dotted path looked up in the dictionary (lodash get). Use {{ }} to derive it from the payload, e.g. {{ $json.country_code }}. JSONata is not supported."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "payload": {
        "type": "object",
        "description": "Context for key resolution."
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "description": "The found value or original payload.",
    "properties": {
      "value": {
        "type": "any",
        "description": "The retrieved value from the dictionary."
      },
      "found": {
        "type": "boolean"
      }
    }
  },
  "ports": [
    {
      "port_id": "found",
      "label": "Found",
      "is_default": true,
      "description": "Key exists in dictionary."
    },
    {
      "port_id": "miss",
      "label": "Missing",
      "description": "Key not found."
    },
    {
      "port_id": "error",
      "label": "Error"
    }
  ],
  "execution_mode": "sync",
  "tags": [
    "map",
    "dictionary",
    "lookup"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_link_loom",
    "profile": {
      "name": "Link Loom",
      "verified": true,
      "url": "https://me.veripass.com/link-loom",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "required": [
    "source",
    "key_template"
  ],
  "properties": {
    "source": {
      "type": "object",
      "title": "Dictionary / Map",
      "description": "Key-Value pairs to search within (e.g., {\"US\": \"United States\"})."
    },
    "key_template": {
      "type": "string",
      "title": "Key Expression",
      "format": "expression",
      "description": "Key or dotted path looked up in the dictionary (lodash get). Use {{ }} to derive it from the payload, e.g. {{ $json.country_code }}. JSONata is not supported."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "payload": {
      "type": "object",
      "description": "Context for key resolution."
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "description": "The found value or original payload.",
  "properties": {
    "value": {
      "type": "any",
      "description": "The retrieved value from the dictionary."
    },
    "found": {
      "type": "boolean"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "found",
    "label": "Found",
    "is_default": true,
    "description": "Key exists in dictionary."
  },
  {
    "port_id": "miss",
    "label": "Missing",
    "description": "Key not found."
  },
  {
    "port_id": "error",
    "label": "Error"
  }
]
```
