I have a Rails app with a Postgres database that has an Artists table with a jsonb genres column.
There are hundreds of thousands of rows.
Each genre column in the row has an array like ["rock", "indie", "seen live", "alternative", "indie rock"] with different genres.
What I want to do is output a count of each genre in JSON across all the rows.
Something like: {"rock": 532, "power metal": 328, "indie": 862}
Is there a way to efficiently do that?
Update...here's what I've got at the moment...
genres = Artist.all.pluck(:genres).flatten.delete_if &:empty?
output = Hash[genres.group_by {|x| x}.map {|k,v| [k,v.count]}]
final = output.sort_by{|k,v| v}.to_h
Output is a hash instead of JSON, which is fine.
But already feels pretty slow, so I'm wondering if there's a better way to do it.