Skip to content

Instantly share code, notes, and snippets.

@honewatson
Created February 9, 2017 21:53
Show Gist options
  • Save honewatson/f1189cd3f40b44714f5df5467cdda484 to your computer and use it in GitHub Desktop.
Save honewatson/f1189cd3f40b44714f5df5467cdda484 to your computer and use it in GitHub Desktop.
Postgres Array, DOC Tags
table doc_tags_array (
doc_id int not null references documents(doc_id),
tags text[] not null default '{}'
)
unique index doc_tags_id_doc_id on (doc_id)
index doc_tags_id_tags using gin (tags)
-- One Tag + Offset
select doc_id
from doc_tags_array
where tags @> ARRAY['math']
order by doc_id limit 25 offset 0;
-- Multiple Tags
select doc_id
from doc_tags_array
where tags @> array['math','physics']
order by doc_id limit 25;
-- Tag Cloud
select count(*) as tag_count, tag
from doc_tags_array
join tags on doc_tags_array.tags @> array[tags.tag::text]
group by tag
order by tag_count desc limit 100;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment