Couldn't a recursive query help here? Oracle has had CONNECT BY for years, and SQL Server has had recursive queries since 2005 (not sure about open source).
And, if SQL isn't the best way, what is? Map-reduce seems hellish to write to me, requiring very advanced developer skills - maybe some Python code?