#19061·nushell

Which `record` commands do we need?

Author: fdncredCreated Sep 21, 2026Updated Sep 28, 2026

Proposal: ten new commands for working with records

Status: discussion draft, nothing implemented. Written against nushell 0.115.2 (main at dc1d81a4f, 2026-09-21).

Records are half of nushell's data model, but the command set treats them as second class. Lists and tables get each, where, reduce, any, all, first, length, find, zip, group-by, window, and so on. Records get items, transpose, columns, values, and the cell-path commands, and everything else is done by bouncing through a table and back. This document surveys what we have, looks at what other languages give their dictionary/map/struct types, and proposes ten commands. Each proposal has a signature sketch, the problem it solves, examples, how you do it today, and prior art.

1. What we have today

Commands that accept record input on main (from scope commands, filtered by input type), grouped by what they do:

Group Commands
Shape columns, values, items, transpose, into record, wrap, flatten, rotate, roll left/right
Pick fields select, reject, get, drop column, compact
Change fields insert, update, upsert, default, rename, move, update cells, sort
Combine merge, merge deep
Language cell paths ($r.a.b?), in operator on keys, spread {...$r}, match destructuring, record<a: int> type annotations

Things that do not accept a record, checked on main:

nushell
{a:1 b:2} | where {|x| $x > 1}   # input_type_mismatch
{a:1 b:2} | each {|x| $x}        # passes the whole record through once
{a:1 b:2} | reduce -f 0 {...}    # input_type_mismatch
{a:1 b:2} | any {...}            # input_type_mismatch
{a:1 b:2} | length               # input_type_mismatch
{a:1 b:2} | first                # input_type_mismatch
{a:1 b:2} | find 1               # input_type_mismatch
{a:1 b:2} | zip {c:3}            # input_type_mismatch

The two idioms people reach for instead, and both are what this proposal wants to retire from everyday use:

nushell
# transpose round trip
{a:1 b:2 c:3} | transpose k v | where v > 1 | transpose -r -d
# => {b: 2, c: 3}

# items + into record (into record merges a list of records)
{a:1 b:2 c:3} | items {|k v| if $v > 1 { {$k: $v} } } | compact | into record
# => {b: 2, c: 3}

They work. They are also the kind of thing you have to look up every time, and neither reads as "keep the fields where the value is greater than one".

2. What other languages do with their map type

Looking across languages for the operations that show up over and over on dictionaries/maps/attribute sets. The right-hand column is what nushell has for the same thing.

Operation Prior art Nushell today
filter entries by key/value Clojure filter on maps, Elixir Map.filter, Kotlin filterKeys/filterValues, Haskell Map.filterWithKey, jq with_entries(select(..)), Python dict comprehension transpose round trip
map over entries, rebuilding the map jq with_entries, Elixir Map.new(m, fn), Kotlin associate, Clojure into {} (map ...), Nix lib.mapAttrs' `items ...
map values only Kotlin mapValues, Nix mapAttrs, lodash mapValues update cells (one level)
map keys only Kotlin mapKeys, Clojure rename-keys, lodash mapKeys rename --block
recursive map over leaves jq walk, Clojure clojure.walk/postwalk, Nix lib.mapAttrsRecursive, Elixir none none
flatten to dotted paths pandas json_normalize, lodash flat, Nix flattenAttrs (community), jq paths/leaf_paths, Java properties, Terraform outputs none (flatten does something else)
unflatten dotted paths lodash unflatten, dotenv-style loaders, Spring @ConfigurationProperties none
structural diff Clojure clojure.data/diff, Python DeepDiff, jq (via to_entries gymnastics), Elixir MapDiff none
apply a patch JSON Patch RFC 6902, JSON Merge Patch RFC 7396, kubectl patch, Clojure diff + merge merge deep only
merge with a conflict resolver Clojure merge-with, Haskell Map.unionWith, Elixir Map.merge/3, Scala merged, Python Counter merge deep --strategy (fixed set: table, overwrite, append, prepend)
per-key transformer map Ramda evolve, Clojure update chains, Elm record update chained update calls
schema check / conform Clojure spec, Elm decoders, Zod, Pydantic, JSON Schema, PowerShell [ValidateSet] record<a: int> on def params only
invert keys and values Clojure set/map-invert, lodash invert, Python {v: k for ...} `items {
partition/split Elixir Map.split, Haskell Map.partition, F# Map.partition select + reject
group entries Kotlin entries.groupBy, Clojure group-by `transpose

jq is the closest neighbour to nushell in spirit (JSON in, JSON out, composed with |), and with_entries, walk, paths, and del are the four verbs jq users lean on hardest for object manipulation. Two of those four have no nushell equivalent at all.

3. Design rules used to pick the ten

  • Record in, record out where it makes sense. The transpose round trip exists because the natural record commands are missing, not because tables are the right intermediate form.
  • Closures get the same shape as items: {|key value| ...}. People already know that.
  • Prefer a record namespace (record where, record diff) over overloading existing list commands. str, bytes, path, url, and math all set this precedent, and it keeps where on a record from meaning something different from where on a table. Whether some of these should instead be overloads is an open question at the end.
  • Cell paths are the currency for "where in the structure". Anything that reports a location (diff, walk, flatten) reports it as a cell path, so the result can go straight back into get, update, or reject.
  • Nothing here needs new syntax or parser work. All ten are plain commands in nu-command.
  • Candidates could start in std-rfc as .nu implementations to bake the semantics before being ported to Rust. Several of them (filter, map, apply) are a dozen lines of nu each.

4. The proposals

4.1 record where (could be record filter)

record where <closure(key, value) -> bool>
  --keys    # closure receives only the key
  --values  # closure receives only the value
input: record  output: record

The where of records. Keeps entries for which the closure returns true, preserves field order.

Problem: any "keep the fields where ..." task today goes through transpose or items. This is the single most common record question on Discord and it has no direct answer.

nushell
# keep only the env vars nushell itself sets
$env | record where {|k v| $k starts-with "NU_"}

# drop fields with empty values before writing a config
{name: app, desc: "", tags: []} | record where {|k v| not ($v | is-empty)}
# => {name: app}

# only the numeric settings, so you can `math sum` them
$env.config.table | record where --values {|v| ($v | describe) == int}

# strip null-valued fields from a parsed API response before `to toml`
http get $url | record where --values {|v| $v != null}

Today: transpose k v | where ... | transpose -r -d, or items {..} | compact | into record.

Prior art: Elixir Map.filter, Kotlin filterKeys/filterValues, jq with_entries(select(...)).

Notes: compact already drops nulls on a record, so the last example is only illustrating the value-only form. --keys and --values are sugar; the two-arg closure covers everything.

4.2 record each (could be record map)

record each <closure(key, value) -> record | list<any> | nothing>
input: record  output: record

The each of records, modelled on jq's with_entries. The closure returns a new entry as a one-field record {newkey: newvalue} or a two-element list [newkey newvalue]. Returning null drops the entry. Results are merged in order into a fresh record.

Problem: update cells transforms values without seeing the key, and rename --block transforms keys without seeing the value. There is no way to do both, or to compute a new key from the value, without leaving record-land. items gets you the pairs but hands back a list, so every use ends in | into record.

nushell
# prefix keys and stringify values in one pass, for a .env file
$config | record each {|k v| {($"APP_($k | str uppercase)"): ($v | to text)}}

# key by a value field: {alice: {id: 7 ..}} from {7: {name: alice ..}}
$users_by_id | record each {|id u| {($u.name): ($u | insert id $id)}}

# drop and rewrite in one place instead of `reject` then `update cells`
$headers | record each {|k v|
    if $k == "authorization" { null } else { {($k | str lowercase): ($v | str trim)} }
}

Today: items {|k v| {..}} | into record. That works because into record merges a list of records, but it is not discoverable and it silently keeps the last value on duplicate keys.

Prior art: jq with_entries, Elixir Map.new/2, Kotlin associate, Nix mapAttrs'.

Open question: on duplicate result keys, last-wins (like into record) or error? I lean toward last-wins with the same behaviour as into record, documented.

4.3 record walk

record walk <closure(value, path) -> any>
  --depth-first   # visit children before parents (post-order); default is leaves only
  --lists         # also descend into lists (default true; flag exists to turn it off)
input: record  output: record

Recursively apply a closure to every leaf value in a nested record, rebuilding the structure. The closure receives the leaf and its full cell path. Lists are descended into by default so a leaf inside servers.0.host is visited.

Problem: update cells stops at depth one. Real data from open config.toml, http get, from json is nested, and "do X to every string in this thing" is a common job: redact, trim, convert timestamps, resolve $HOME, coerce numeric strings. Today you write a recursive def every time, and everyone's version handles lists slightly differently.

nushell
# redact anything that looks like a secret before printing a config
open config.toml | record walk {|v p| if ($p | to text) =~ "(?i)secret|token|password" { "***" } else { $v } }

# every ISO string becomes a datetime
http get $url | record walk {|v| if ($v | describe) == string and ($v =~ '^\d{4}-\d\d-\d\d') { $v | into datetime } else { $v } }

# expand ~ in every path-looking value of a settings file
open settings.json | record walk {|v| if ($v | describe) == string and ($v starts-with "~") { $v | path expand } else { $v } }

# trim every string in a parsed CSV row (via each)
open data.csv | each { record walk {|v| if ($v | describe) == string { $v | str trim } else { $v } } }

Today: hand-rolled recursive def, or std-rfc iter recurse (which gives you the paths but not a rebuilt record).

Prior art: jq walk, Clojure postwalk, Nix mapAttrsRecursive.

Notes: the leaf-only default keeps the closure simple. --depth-first is the escape hatch for closures that want to see containers too (for example to collapse {value: x} wrappers). Type dispatch inside the closure via describe is clunky; a future match on types would make these examples much shorter, but that is a separate discussion.

4.4 record flatten

record flatten
  --separator <string>   # default "."
  --depth <int>          # stop after N levels
input: record  output: record

Collapse a nested record into a single level whose keys are the cell paths of the leaves. Lists are indexed (tags.0, tags.1). With the default separator the keys are valid cell paths, so get, update, and reject accept them.

Problem: several targets are flat by nature: environment variables, .properties and .env files, CSV columns, kubectl label selectors, Terraform variables, most CLI --set a.b=c flags. Getting a nested config into any of them is a recursive def. The existing flatten command was designed for tables and produces surprising output on records (see section 1).

nushell
# nested config to environment variables for a child process
open app.toml | record flatten --separator "_" | record each {|k v| {($k | str uppercase): ($v | to text)}} | with-env $in { ./app }

# all leaf paths, for discovery
open big.json | record flatten | columns

# search a nested structure for a value; the key tells you where it was
open big.json | record flatten | record where --values {|v| $v == "prod-db-01"}
# => {clusters.2.primary.host: prod-db-01}

# nested record as CSV row
[$a $b $c] | each { record flatten } | to csv

Today: recursive def, or std-rfc iter recurse | where item is a leaf | ... followed by manual reassembly.

Prior art: pandas json_normalize, npm flat, Java Properties, jq [paths(scalars)].

Open question: what to do with empty records and lists. Dropping them loses information on round trip through unflatten; keeping them as {} / [] leaves means the output is not strictly flat. I lean toward keeping them.

4.5 record unflatten

record unflatten
  --separator <string>   # default "."
input: record  output: record

The inverse of record flatten. Keys are split on the separator and rebuilt into nested records. Consecutive integer segments starting at 0 become lists.

Problem: the same flat sources, in the other direction. $env with an APP_ prefix, a .properties file, --set a.b.c=1 style arguments, Terraform/GitHub Actions outputs, dotenv files, flag parsing in scripts. Every one of these is a recursive upsert loop today.

nushell
# env vars back into a config record
$env | record where {|k| $k starts-with "APP_"} | record each {|k v| {($k | str replace "APP_" "" | str lowercase): $v}} | record unflatten --separator "_"

# parse KEY=VALUE lines from a .properties file
open server.properties | lines | parse "{k}={v}" | transpose -r -d | record unflatten

# collect --set style args in a script
def main [...sets: string] {
    $sets | parse "{k}={v}" | transpose -r -d | record unflatten
}
# main server.port=8080 server.tls.enabled=true
# => {server: {port: "8080", tls: {enabled: "true"}}}

Today: reduce -f {} {|it acc| $acc | upsert ($it.k | split row "." | into cell-path) $it.v}, plus separate handling for list indexes.

Prior art: npm flat.unflatten, Spring relaxed binding, Nix lib.attrsets.setAttrByPath in a fold.

Notes: flatten and unflatten should be exact inverses for the default separator on records without keys containing the separator. Keys that contain the separator should be quoted on the way out, since cell paths support quoted segments. Values stay as-is; use record apply or record walk to coerce.

4.6 record diff

record diff <other: record>
  --shallow    # compare top-level values only, no recursion
input: record  output: table<path: cell-path, change: string, old: any, new: any>

Structural comparison. Output is one row per leaf that differs, with change one of added, removed, changed. Rows are ordered by path. An empty table means equal (which == already tells you, but not what differs).

Problem: "what changed between these two configs / API responses / $env snapshots" is a question with no answer in nushell beyond eyeballing two tables. Testing with assert equal on records prints both values in full and leaves you to spot the difference.

nushell
# what did sourcing that script change in my environment?
let before = $env
source setup.nu
$before | record diff $env

# compare two config files
(open prod.toml) | record diff (open staging.toml)
# ╭───┬────────────────────┬─────────┬──────────┬──────────╮
# │ # │        path        │ change  │   old    │   new    │
# ├───┼────────────────────┼─────────┼──────────┼──────────┤
# │ 0 │ database.host      │ changed │ prod-db  │ stage-db │
# │ 1 │ database.pool.size │ changed │ 50       │ 5        │
# │ 2 │ features.beta      │ added   │          │ true     │
# ╰───┴────────────────────┴─────────┴──────────┴──────────╯

# CI check: fail if the generated file drifted from the committed one
let d = (open expected.json) | record diff (open generated.json)
if ($d | is-not-empty) { $d | table | print; exit 1 }

# only the removals
$old | record diff $new | where change == removed | get path

Today: record flatten both sides by hand, then transpose and join --outer. Nobody does that; they print both and squint.

Prior art: clojure.data/diff, Python DeepDiff, Elixir MapDiff, git diff for the mental model.

Open questions: list comparison. Element-wise by index is simple and matches merge deep --strategy table. Treating lists as sets is sometimes what you want (tags) but is a different command. Start with index-wise, and let --shallow or a later --lists set flag handle the rest.

4.7 record patch

record patch <patch: table<path, change, old, new> | record>
  --reverse    # apply a diff backwards (undo)
  --merge      # treat the argument as an RFC 7396 merge patch: null deletes, records recurse
input: record  output: record

Apply a change set. The primary input shape is the table record diff produces, so the two commands round-trip. --merge accepts the JSON Merge Patch form that Kubernetes and most REST APIs use, where a null value means "delete this key". --reverse swaps old/new and added/removed, which gives you undo for free.

Problem: merge deep can add and overwrite but cannot delete, and it has no idea about lists beyond four fixed strategies. Once record diff exists, the obvious next question is "apply those same changes over here", and that is a patch.

nushell
# replay the changes from one environment's config onto another's
let changes = (open dev.toml) | record diff (open dev-next.toml)
open prod.toml | record patch $changes | save prod-next.toml

# undo
$after | record patch $changes --reverse   # == $before

# delete a key with a merge patch (merge deep can't do this)
$config | record patch --merge {logging: {file: null}, level: debug}

# review a change set before applying it
$changes | where path =~ "^database" | reject old | table
$config | record patch ($changes | where path !~ "secret")

Today: a reduce over a hand-built list of update/reject calls.

Prior art: RFC 6902 JSON Patch, RFC 7396 JSON Merge Patch, kubectl patch, git apply.

Notes: full RFC 6902 (move, copy, test ops) is deliberately out of scope. The diff table plus merge-patch covers the shell use cases and stays readable when printed.

4.8 record merge-with

record merge-with <other: record> <closure(key, left, right) -> any>
  --deep    # recurse into nested records before consulting the closure
input: record  output: record

merge, but keys present on both sides go through a closure instead of being overwritten. Keys on only one side are copied through.

Problem: merge is right-wins and merge deep picks from a fixed list of list strategies. Real merges have a policy that depends on the key or the value: sum the counts, keep the newer timestamp, union the tags, take the max version, concatenate the PATH. Every one of those is a transpose and join --outer today, and join on records is not something anyone reaches for.

nushell
# combine word counts from two files
$counts_a | record merge-with $counts_b {|k a b| $a + $b}

# merge two PATH-like configs, keeping both lists deduped
$base | record merge-with $override --deep {|k a b|
    if ($a | describe) starts-with "list" { $a | append $b | uniq } else { $b }
}

# keep whichever side has the later timestamp per key
$cache | record merge-with $fresh {|k a b| if $b.updated > $a.updated { $b } else { $a } }

# reduce many records with a resolver
$per_host_stats | reduce {|it acc| $acc | record merg