Introduction
Sometimes you want to find information from different categories or types in one search. This helps you get all related results quickly.
Sometimes you want to find information from different categories or types in one search. This helps you get all related results quickly.
query SearchAcrossTypes($searchTerm: String!) {
search(term: $searchTerm) {
__typename
... on TypeA {
field1
field2
}
... on TypeB {
field3
field4
}
}
}__typename to know which type each result belongs to.... on TypeName) to specify fields for each type.query {
search(term: "Alice") {
__typename
... on User {
id
name
}
... on Company {
id
companyName
}
}
}query {
search(term: "Book") {
__typename
... on Book {
title
author
}
... on Author {
name
birthYear
}
}
}This query looks for the term "John" in both Person and Organization types and shows their relevant fields.
query {
search(term: "John") {
__typename
... on Person {
id
name
email
}
... on Organization {
id
orgName
contactEmail
}
}
}Always check __typename to handle results correctly.
Fragments help keep your query organized and clear.
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.
__typename field do in a GraphQL query when searching across types?__typename__typename field returns the name of the type of each object in the query result.__typename shows object type [OK]Book and Author, in one GraphQL query using fragments?... on TypeName { fields } to specify fields for each type.Book and Author. Options B, C, and D have invalid syntax.... on Type [OK]... on Type for each type's fields [OK]query { search { __typename ... on Book { title author } ... on Author { name booksCount } } }__typename and fields specific to Book and Author types.query { search { ... on Book { title author } ... on Author { name booksCount } } }booksCount is not a valid field on Author type.booksCount is not defined on Author, the query is invalid.booksCount is not a valid field on Author. -> Option CBook, Author, and Publisher. Each type has a field name, but Book also has pages, Author has birthYear, and Publisher has location. Which query correctly fetches the name for all types and their specific fields?__typename to identify each type... on Type syntaxname and the type-specific fields.__typename. Other options have syntax errors or missing fragments.Pass the test and this pattern moves unknown