Using Postgres 9.4, I'm interested in having an array of integers like user_ids_who_like
and provide an array of users (like user_ids_i_am_following
) to sort that intersection.
Something like:
select *
from items
where [there is an intersection between
user_ids_who_like with user_ids_i_am_following]
order by intersection(user_ids_who_like).count
Is grouping and ordering by an array intersection possible?
Example data:
items
name | user_ids_who_like
'birds' | '{1,3,5,8}'
'planes' | '{2,3,4,11}'
'spaceships' | '{3,4,6}'
For a given user_ids_who_i_follow = [3,4,11]
, can I do something like:
select * from items
where <user_ids_who_like intersects with user_ids_who_i_follow>
order by <count of that intersection>
Desired result:
name | user_ids_who_like | count
'planes' | '{2,3,4,11}' | 3
'spaceships' | '{3,4,6}' | 2
'birds' | '{1,3,5,8}' | 1
One possibility seems to be something like this:
select id, user_ids_who_like, (user_ids_who_like & '{514, 515}'::int[]) as jt
from queryables
where user_ids_who_like && '{514, 515}'
order by icount(user_ids_who_like & '{514, 515}'::int[]) desc;
But I can't tell if this style (using the intarray extension rather than native array functions and operators) is outdated; any feedback from more sophisticated users here? It's not clear to me how to do the intersection of two arrays using the methods and operators.
intarray
still has its use cases, this might be one of them. The extension has a few funtions, too, which are very handy.