I have setup apostscollection, with atagsfield. The most frequently used tags are going to be displayed in a ‘tag cloud’, on a website. I need to be able to query Directus via the REST API, and get a list of all tags, ordered by the most to least frequently used.
I initially tried using a standard ‘tags’ field, but it seems the field stores the tags as a JSON list, and the aggregate[]functions cannot be applied to the individual list items.
I then tried to setup a separate tagscollection, and then setup a many-to-many tags field in the postscollection. I can now get the count of how many times each tag is being used — by querying the posts_tagscollection directly — but the result gives me the tag IDs instead of the actual tag_text, which is in the related tags collection. I’ve tried using ?fields=tags_id.tag_text, but as soon as I add an aggregate or groupBy function, it seems the fieldsparameter gets ignored, and I just get the IDs…
I feel like I’m overlooking something basic — any guidance would be greatly appreciated.
When I created the many-to-many field in the postscollection, I didn’t specify that I wanted the equivalent field added to the tagscollection. As a result, I couldn’t query the tagscollection for the number of posts connected to each tag — which is what we needed.
I recreated the relationship, now with fields on both sides. I am now able to query the API for the 20 most frequently used tags, through the tags collection, like this:`
GET /items/tags?
fields=tag_text,count(posts)
&order=-count(posts)
&limit=20
When using aggregate and groupBy in Directus, you’ll typically only get the raw IDs (like tags_id) in the result, not the full related data. Unfortunately, expanding fields like tags_id.tag_text doesn’t work as expected with aggregation. So yes, after getting the tag IDs and their counts, you’ll need to make a second request to fetch the actual tag text for each ID from the tags collection. That’s just how Directus handles relational data in aggregate queries right now.