Skip to content
Advertisement

aggregating Posts with all their Hashtags using Postgres

I have something like Posts in FB/instagram. When a user searches for something, the input query is used to either find Posts that either have this query in their content, OR – one or more of post’s hashtags match this query.

The problem :

I can’t figure out how to have Posts returned with a nested array of all its pertinent Tags. So for example Post -> {post_id: 123 , tags : [{id: 1, title: a}, {id: 2, title : b}, ...]}

Also, it results in duplicate records since I can’t GROUP BY only by one column (post_id).

Examples:

posts tables has:

tags tables has:

post_tags has:

So in this example, post_id = 1 has the “user_query” inside one of its tags, and post_id = 3 has the “user_query” inside its content. So, both of them should be returned.

Advertisement

Answer

Do you want JSON aggrgation?

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement