0
0
GraphQLquery~5 mins

Search across types in GraphQL

Choose your learning style9 modes available
Introduction

Sometimes you want to find information from different categories or types in one search. This helps you get all related results quickly.

Looking for a person or a company by name in a directory.
Searching for books and authors together in a library database.
Finding products and their reviews in an online store.
Checking for movies and actors in a film database.
Syntax
GraphQL
query SearchAcrossTypes($searchTerm: String!) {
  search(term: $searchTerm) {
    __typename
    ... on TypeA {
      field1
      field2
    }
    ... on TypeB {
      field3
      field4
    }
  }
}
Use __typename to know which type each result belongs to.
Use fragments (... on TypeName) to specify fields for each type.
Examples
This searches for "Alice" in both User and Company types and returns their specific fields.
GraphQL
query {
  search(term: "Alice") {
    __typename
    ... on User {
      id
      name
    }
    ... on Company {
      id
      companyName
    }
  }
}
This finds matches in Book and Author types with their details.
GraphQL
query {
  search(term: "Book") {
    __typename
    ... on Book {
      title
      author
    }
    ... on Author {
      name
      birthYear
    }
  }
}
Sample Program

This query looks for the term "John" in both Person and Organization types and shows their relevant fields.

GraphQL
query {
  search(term: "John") {
    __typename
    ... on Person {
      id
      name
      email
    }
    ... on Organization {
      id
      orgName
      contactEmail
    }
  }
}
OutputSuccess
Important Notes

Always check __typename to handle results correctly.

Fragments help keep your query organized and clear.

Summary

Search across types lets you find data from different categories in one query.

Use __typename and fragments to get the right fields for each type.