Query all documents matching a specific filter for a specific Slice

Hello,

I have been trying for a few days now to query all the documents 1) of a specific custom type 2) with a specific value at data.mainTag.

Scenario:
I want to create a slice called "SimilarMainTag" that will display all the pages with the same MainTag value as the one currently displayed.

So in my custom type [uid].js (custom type=pillar_page), in my getStaticProps function, I am retrieving the page.data.maintag to compare it with all data.maintag of documents of type "pillar_page":


export async function getStaticProps({ params, previewData }) {
  const client = createClient({ previewData })
  const page = await client.getByUID('pillar_page', params.uid)

  // Filtering all pillar pages with the same MainTag

  // Current page's mainTag - OK
  const currentMainTag = page.data.maintag

  // All pillar pages - OK
  const pillarPages = await client.getAllByType('pillar_page')

  // **All pillar pages with the same mainTag:
  //Attempt 1
  // const filteredPillarPages = await client.query(
  //   prismic.predicate.at('my.pillar_page.maintag', currentMainTag)
  // )

  //Attempt 2
  // const filteredDocuments = await client.get({
  //   predicates: prismic.predicate.at('my.pillar_page.main_tag', page.id)
  // })
  // console.log('filtered docs :', filteredDocuments)

  // From Prismic's documentation:https://prismic.io/docs/content-relationship#query-by-content-relationship
  // const filteredDocuments = await client.get({
  //   predicates: prismic.predicate.at(
  //     'my.example_custom_type.example_content_relationship',
  //     'YesUgRIAACEA-UZD'
  //   )
  // })

  return {
    props: {
      metaTitle: page.data.meta_title,
      metaDescription: page.data.meta_description,
      ogImage: page.data.og_image.url,
      page: page,
      title: page.data.title,
      upperTitle: page.data.uppertitle
    }
  }
}

export async function getStaticPaths() {
  const client = createClient()

  const pages = await client.getAllByType('pillar_page')

  return {
    paths: pages.map((page) => prismicH.asLink(page)),
    fallback: false
  }
}

Attempt 1 & 2 fall.
I am not sure neither how to import "prismic". Am I supposed to use prismic.H or import Prismic from 'prismic-javascript'? none of them worked so far.

Would you be as kind as telling me what am I doing wrong?

I think this kind of filtering should interest a lot of people for SEO purposes.

Best,

1 Like

Hello @Marving

prismic-javascript has moved to @prismicio/client. Please upgrade to @prismicio/client.

Once you upgrade, you can import prismic like this:

import * as prismic from '@prismicio/client'

Then you'll be able to use all query methods, like client.getAllByTag(tag)

Hello @Pau,

Thank you for your reply.

Correct me if I am wrong, but the allbyTag is filtering the back office tags cf screenshot:
Screenshot 2023-03-15 at 8.45.14 AM
But not the tags done through Content Relationship, such as:
Screenshot 2023-03-15 at 8.45.57 AM

So far with

  const allByTags = client.getAllByTag('Data Analyst')
  console.log(allByTags)

In my getStaticProps, I get : "allbyTags: Promise { }"

So I have tried prismic.predicate.at which goes as follows:

  // Attempt 2
  const filteredDocuments = await client.get({
    predicates: prismic.predicate.at(
      'my.pillar_page.main_tag',
      currentMainTag.id
    )
  })
  console.log('filtered docs :', filteredDocuments)

But now I get an empty result:

filtered docs : {
  page: 1,
  results_per_page: 20,
  results_size: 0,
  total_results_size: 0,
  total_pages: 0,
  next_page: null,
  prev_page: null,
  results: [],
  version: '0427058',
  license: 'All Rights Reserved'
}

What am I not understanding correctly?

Would love some real concrete example in the documentation :heart:!

1 Like

That's correct. Since you're using a custom tagging system instead of the default one, the queries will be different.

In this case, you'll need to use fetchLinks or GraphQuery to get the data from the linked documents. You can find an example of this in our official Next docs, in the fetch data document:

Same it does not work for me as well. I have a similar setup but called the Tags Categories.

In this Document it's described like this but it doesn't work:

@Marving Did you found a solution?

This is my code:

categoryList.forEach((category) => {
    filters.push(prismic.filter.at("my.category.uid", 'projekte'));
  });

await client.get({
    filters,
    fetchLinks: ["category.name"], //Fetch the Linked Fields 
    pageSize: 2, // Angenommen, dass 2 ein geeigneter Standardwert für die Seitengröße ist
    page: parseInt(page, 10),
  });

Hi Carlo,

I might be misreading your code, but when I look at this line:

categoryList.forEach((category) => {
    filters.push(prismic.filter.at("my.category.uid", 'projekte'));
  });

It looks like this will just create an array of the length of categoryList.length in which every item is prismic.filter.at("my.category.uid", 'projekte'). I'm not sure what affect that will have on your query.

Sam

Oh Hi Sam,
yeah this is just a example code normaly i have different strings in there. Just to make it easier to read...

this is my actual code...

let filters = [prismic.filter.any('document.type', ['neuigkeiten_post'])];


  // Kategorienfilter hinzufügen, falls vorhanden
  categoryList.forEach((category) => {
    filters.push(prismic.filter.at("my.category.uid", category));
  });

const posts = await client.get({
    filters,
    fetchLinks: ["category.name", "category.uid"],
    pageSize: 2, // Angenommen, dass 10 ein geeigneter Standardwert für die Seitengröße ist
    page: parseInt(page, 2),
  });

Hey @carlo2,

If you're trying to filter by category, you need to reference the linking property on the document and use the category's ID. It would be something like this:

categoryList.forEach((category) => {
  filters.push(prismic.filter.at("my.neuigkeiten_post.categories.category", category.id));
});

Sam