javascriptsqlreactjssanitygroq

Sanity.io GROQ - Retrive document by highest reference count in other documents


I have a tag document that looks like

{
  name: 'tag',
  title: 'Tag',
  type: 'document',
  fields: [
    {
      name: 'label',
      title: 'Label',
      type: 'string',
    }
  ]
}

And page document that looks like

{
  name: "page",
  title: "Page",
  type: "document",
  fields: [
    {
      name: "title",
      title: "Title",
      type: "string",
    },
    {
      name: "tags",
      title: "Tags",
      type: "array",
      of: [{ type: "reference", to: [{ type: "tag" }] }],
    }
  ]
}

And another article document that looks like

{
  name: "article",
  title: "Article",
  type: "document",
  fields: [
    {
      name: "title",
      title: "Title",
      type: "string",
    },
    {
      name: "description",
      title: "Description",
      type: "text",
    },
    {
      name: "tags",
      title: "Tags",
      type: "array",
      of: [{ type: "reference", to: [{ type: "tag" }] }],
    }
  ]
}

I am unable to figure out how to get the tags with the highest reference count used across pages and articles

An extension of this question would be to get the top 10 highest tags used across the site.

I've been struggling for a while now. Any help would be appreciated.

Thank you team.


Solution

  • You can likely accomplish this by constructing a query that first gets all tags, then uses the count function to further filter them. Something like the following:

    *[_type == 'tag'] {
      ...,
      'totalReferences': count(*[_type in ['page', 'article'] && references(^._id))
    } | order(totalReferences desc) [0...10]
    

    This may not be very performant in very large datasets, though.