Was this page helpful?

Filter API results with relational queries

Imagine a scenario of recreating an IMDB website on Contentful. In this setup, every film entry would refer to content types describing a movie genre, cast, and critic reviews. If a user needs to know how many movie credits has Danny "Machete" Trejo earned to date, the ideal way to go about it would be to fetch all the films that feature Danny Trejo as an actor.

Previously, there was no easy way to do it because the Content Delivery API (CDA) did not allow filtering of entries by values of their reference fields.

To address this problem, Contentful has introduced a new filtering capability to the APIs, enabling the user to query for content based on the fields of referenced entries. The following query explains how to get all Danny Trejo's movie credits in a single API call:

https://cdn.contentful.com/spaces/my-space-id/entries/
    ?content_type=movies
    &fields.actors.sys.contentType.sys.id=actors
    &fields.actors.fields.name[all]=Trejo,Danny

It can be extended one step further, by using multiple values to filter only Danny Trejo movies which were also directed by Quentin Tarantino, or movies with Danny Trejo that received a rating of six stars or higher. Here is how the queries look like:

https://cdn.contentful.com/spaces/my-space-id/entries/
    ?content_type=movies
    &fields.actors.sys.contentType.sys.id=actors
    &fields.actors.fields.name[all]=Trejo,Danny
    &fields.directors.sys.contentType.sys.id=director
    &fields.directors.fields.name[all]=Tarantino, Quentin
https://cdn.contentful.com/spaces/my-space-id/entries/
    ?content_type=movies
    &fields.actors.sys.contentType.sys.id=actors
    &fields.actors.fields.name[all]=Trejo,Danny
    &fields.reviews.sys.contentType.sys.id=review
    &fields.reviews.fields.rating[gte]=6

The reference can also be combined with the select operator to streamline the type of information required in the response.

It is important to understand that search on reference fields only works with entries. It cannot search assets the same way, and the search can only be one level deep. To ensure consistent performance, the number of searchable reference fields is limited to two.

Search on reference field values is supported by all the REST APIs (Content Management, Content Delivery, and Content Preview) and all the SDKs.