Unlock seamless workflows and faster delivery with our latest releases โ€“ get the details

Query for related content using tags in Sanity returns no results

5 replies
Last updated: Dec 21, 2024
Looking for any help as I am attempting to query for "related content" based on the tags of a resource. Details in ๐Ÿงต
Dec 15, 2024, 5:51 PM
When I view a resource I also want to use that resource's Tags to search other resources that have tags in common. Currently trying this query
    related_papers = await client.fetch(
      `*[_type in [
          "whitePaper",
          "researchPaper",
          "dataSheet",
          "eBooks",
          "presentations"
        ] && count(Tags[@in ${searchQuery}]) > 0] {
        _id,
        title,
        abstract,
        _type,
        slug,
        date,
        Tags,
        _score
      } | order(_score desc)[0...3]`,
      {
        searchQuery // Pass the array of tags directly
      }
    );
Where
searchQuery
would be the current tag array. I cannot seem to get this dialed in so that it returns any result (current return count is 0). And yes, the tags resource is uppercase, not
tags
but
Tags
, it just is cant change it.
I am currently just hard coding the
searchQuery
to match a tag array that I know should have matching results, but cannot get anything returned, keep logging out a .count of 0.
If anyone can tell me where I am off it would be much appreciated
Dec 15, 2024, 5:55 PM
Hi there๐Ÿ‘‹
I made some changes, would you mind trying this?

const related_papers = await client.fetch(`
  *[_type in [
    "whitePaper",
    "researchPaper",
    "dataSheet",
    "eBooks",
    "presentations"
  ] && count(Tags[@ in $tags]) > 0] {
    _id,
    title,
    abstract,
    _type,
    slug,
    date,
    Tags,
    _score
  } | order(_score desc)[0...3]`,
  {
    tags: searchQuery
  }
)
Dec 16, 2024, 3:25 PM
Thanks for the try, but still 0 results
Dec 21, 2024, 2:43 PM
Think it needed to be adjusted, I was not understanding how Tags was structured I believe, this appears to have dialed it in, thanks again for the help
] && count(Tags[defined(@) && @.value in $tags]) > 0] {
Dec 21, 2024, 3:01 PM
maybe some refining can help this too but just got the results I was expecting so wanted to post for anyone who comes here and looks
Dec 21, 2024, 3:02 PM

Sanityโ€“ build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?