How do I filter entries by category with GraphQL (and Gatsby)?

I am struggling with how to to filter content entries by categories.

I have a Content Type called “Products”. I’d like to assign a product a category such as “Cameras”, “Appliances”, “Computers”.

I already had Products with entries, so based on what I’ve read, I’ve created three content types: Cameras, Appliances and Computers.

I’ve added a Reference Field to Products called “Product Type” and am selecting whether a products is a camera, an appliance or a computer.

I can successfully grab all products with allContentfulProduct in GraphQL, but I can’t figure out how to filter by the Reference Field. I’m using Gatsby and am trying to figure this out in GraphiQL, but don’t see a way to do this.

This is a great thing to use GraphiQL for, the nav on the left has a “filter” tree under each query that you can expand to build out your query filter.

For your Product query, something like this should do the trick

allContentfulProducts(filter: {product_type: {elemMatch: {title: {eq: "Computers"}}}})

or multiple product types

allContentfulProducts(filter: {product_type: {elemMatch: {title: {in: ["Computers", "Appliances"]}}}})

where product_type is the name of your field on Products and title is the name/title field for Product Types.

Thanks Blake. That’s helpful!

But I don’t have “elemMatch” as an option. I have:

filter: {productType:

children
contenful_id
createdAt
id
internal
node_locale
parent
spaceId
sys
updatedAt

those are my options

Ah well that’s no good! By chance did you try making sure you had a published Product with the Product Type field referencing an entry and then restarting gatsby develop locally? Sometimes it doesn’t make those relationships until it is restarted with existing content that uses them.

Alternatively you might try updating your npm packages if they’re not fully up to date… Otherwise you might try filtering on the id :-/

ooo, i found it:

allContentfulProduct(filter: {productType: {product: {elemMatch: {productType: {title: {eq: "Computers"}}}}}})

thanks Blake!