{
  "id": "foreach-example",
  "title": "Write-behind foreach example",
  "url": "https://redis.io/docs/latest/integrate/write-behind/data-transformation/transformation-examples/foreach-example/",
  "summary": "",
  "tags": [
    "docs",
    "integrate",
    "rs",
    "rdi"
  ],
  "last_updated": "2026-04-01T08:10:08-05:00",
  "page_type": "content",
  "content_hash": "ee1cc762d25a8dac2a8d4eef0dbb546ae827b044504a665623bf86a94f5cf923",
  "sections": [
    {
      "id": "content",
      "title": "Content",
      "role": "content",
      "text": "The `foreach` section is used to explode a list of objects or arrays to rows in a selected target.\nThe `foreach` expression is structured as `<field_name>:<JMESPath expression>`.\nThe following example uses the `add_field` transformation to prepare the input JSON to the desired structure. Then, it applies `foreach` to write each `order` object as a relational database record using `keys` and `mapping`.\nIn this example, the `JMESPath` function `to_string` is used to flatten an array of objects, `specs`, to a string.\n\n[code example]"
    }
  ],
  "examples": [
    {
      "id": "content-ex0",
      "language": "yaml",
      "code": "source:\n  redis:\n    key_pattern: orderdetail:*\n    trigger: write-behind\n    exclude_commands: [\"json.del\"]\ntransform:\n  - uses: add_field\n    with:\n      fields:\n        - field: my_orders\n          language: jmespath\n          expression: |\n            orders[*].{\n              code: code\n              periodStartTime: periodStartTime\n              periodEndTime: periodEndTime\n              specs: to_string(specs)\n            }\noutput:\n  - uses: relational.write\n    with:\n      connection: mssql\n      schema: dbo\n      table: OrderMaster\n      keys:\n        - Code: orderDetail.code\n      mapping:\n        - DeliveryDate: orderDetail.deliveryDate\n        - ProductCode: orderDetail.productCode\n        - CountryCode: orderDetail.countryCode\n  - uses: relational.write\n    with:\n      connection: mssql\n      schema: dbo\n      table: Order\n      foreach: \"order: my_orders[]\"\n      keys:\n        - Code: order.code\n      mapping:\n        - OrderDetailCode: orderDetail.code\n        - PeriodStartTime: order.periodStartTime\n        - PeriodEndTime: order.periodEndTime\n        - Specs: order.specs",
      "section_id": "content"
    }
  ]
}
