Justin Taft - Home / Posts

A better way to store nested maps and relationships in clojure?

In clojure, nested maps are used often to store data and materialized relationships.

If you need to refactor a data structure though, you have to change everywhere in code that uses a hierarchy of keys/index positions to access data. Oof, this makes refactoring a nightmare.

Some tame the complexity by writing functions to handle getting/setting values, so key structure doesn’t have to be repeated in places. (See https://ericnormand.me/speaking/you-are-in-a-maze-of-deeply-nested-maps-all-alike-talk).

What if there is a better way though? What if we do away with materializing relationships when not necessary? Every piece of information could be stored as an entity in a flat hashmap with a unique id. If a object needs to nest another entity, it would just do so by referring to it’s entity id.

Updating a deeply nested item is now simple. We just grab the entity by it’s id, and update values accordingly. No more need to do a deep fetch! Sure there are cases where business logic checks might need a parent or child element, but it’s still workable into the system.

A separate utility function could “Materialize” data found in relationships if it’s needed too (such as displaying data).

For database performance, I imagine simple logic can be added to auto-fetch relationships greedly if wanted.

Leave a Reply

Your email address will not be published. Required fields are marked *