Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Sql like join in clojure
(ns sql-like-join
(:require [clojure.set :refer [difference
(defn inner-join
[left-keys right-keys]
(intersection (set left-keys) (set right-keys)))
(defn outer-join
[left-keys right-keys]
(union (difference (set left-keys) (set right-keys)) (difference (set right-keys) (set left-keys))))
(defn full-join
[left-keys right-keys]
(union (set left-keys) (set right-keys)))
(defn left-join
[left-keys right-keys]
(defn map-combine [group1 group2 dumy-map]
(for [map1 group1
map2 group2]
(merge-with #(or %2 %1) dumy-map map2 map1)))
(defn joiner [left-coll right-coll left-fn right-fn join-type keys-fn & args]
(let [left-idx (group-by left-fn left-coll)
right-idx (group-by right-fn right-coll)
join-keys (set (join-type (keys left-idx) (keys right-idx)))]
(apply concat
(map #(map-combine (get left-idx % [{}])
(get right-idx % [{}])
(zipmap (set (union (keys (first left-coll)) (keys (first right-coll))))(repeat nil)) ) join-keys))))
(def one
[{:foo "bar" :key1 "test1"}
{:foo "test" :key1 "test2"}])
(def two
[{:bar "foo" :foo1 "bar"}
{:bar "bar1" :foo1 "foo1"}])
#_(joiner one two :foo :foo1 left-join)

This comment has been minimized.

Copy link

@rbxbx rbxbx commented Feb 8, 2018

Saved me today - thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment