subgraphs > Developing > Creating > The Graph QL Schema

The Graph QL Schema

Reading time: 9 min

Descripción

Enlace a esta sección

The schema for your subgraph is in the file schema.graphql. GraphQL schemas are defined using the GraphQL interface definition language.

Note: If you've never written a GraphQL schema, it is recommended that you check out this primer on the GraphQL type system. Reference documentation for GraphQL schemas can be found in the GraphQL API section.

Defining Entities

Enlace a esta sección

Before defining entities, it is important to take a step back and think about how your data is structured and linked.

  • All queries will be made against the data model defined in the subgraph schema. As a result, the design of the subgraph schema should be informed by the queries that your application will need to perform.
  • It may be useful to imagine entities as "objects containing data", rather than as events or functions.
  • You define entity types in schema.graphql, and Graph Node will generate top-level fields for querying single instances and collections of that entity type.
  • Each type that should be an entity is required to be annotated with an @entity directive.
  • By default, entities are mutable, meaning that mappings can load existing entities, modify them and store a new version of that entity.
    • Mutability comes at a price, so for entity types that will never be modified, such as those containing data extracted verbatim from the chain, it is recommended to mark them as immutable with @entity(immutable: true).
    • If changes happen in the same block in which the entity was created, then mappings can make changes to immutable entities. Immutable entities are much faster to write and to query so they should be used whenever possible.

Un buen ejemplo

Enlace a esta sección

The following Gravatar entity is structured around a Gravatar object and is a good example of how an entity could be defined.

type Gravatar @entity(immutable: true) {
id: Bytes!
owner: Bytes
displayName: String
imageUrl: String
accepted: Boolean
}

Un mal ejemplo

Enlace a esta sección

The following example GravatarAccepted and GravatarDeclined entities are based around events. It is not recommended to map events or function calls to entities 1:1.

type GravatarAccepted @entity {
id: Bytes!
owner: Bytes
displayName: String
imageUrl: String
}
type GravatarDeclined @entity {
id: Bytes!
owner: Bytes
displayName: String
imageUrl: String
}

Campos opcionales y obligatorios

Enlace a esta sección

Entity fields can be defined as required or optional. Required fields are indicated by the ! in the schema. If the field is a scalar field, you get an error when you try to store the entity. If the field references another entity then you get this error:

Null value resolved for non-null field 'name'

Each entity must have an id field, which must be of type Bytes! or String!. It is generally recommended to use Bytes!, unless the id contains human-readable text, since entities with Bytes! id's will be faster to write and query as those with a String! id. The id field serves as the primary key, and needs to be unique among all entities of the same type. For historical reasons, the type ID! is also accepted and is a synonym for String!.

For some entity types the id for Bytes! is constructed from the id's of two other entities; that is possible using concat, e.g., let id = left.id.concat(right.id) to form the id from the id's of left and right. Similarly, to construct an id from the id of an existing entity and a counter count, let id = left.id.concatI32(count) can be used. The concatenation is guaranteed to produce unique id's as long as the length of left is the same for all such entities, for example, because left.id is an Address.

Tipos de Scalars incorporados

Enlace a esta sección

GraphQL admite Scalars

Enlace a esta sección

The following scalars are supported in the GraphQL API:

TipoDescripción
BytesByte array, representado como un string hexadecimal. Comúnmente utilizado para los hashes y direcciones de Ethereum.
StringScalar for string values. Null characters are not supported and are automatically removed.
BooleanScalar for boolean values.
IntThe GraphQL spec defines Int to be a signed 32-bit integer.
Int8An 8-byte signed integer, also known as a 64-bit signed integer, can store values in the range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Prefer using this to represent i64 from ethereum.
BigIntLarge integers. Used for Ethereum's uint32, int64, uint64, ..., uint256 types. Note: Everything below uint32, such as int32, uint24 or int8 is represented as i32.
BigDecimalBigDecimal High precision decimals represented as a significand and an exponent. The exponent range is from −6143 to +6144. Rounded to 34 significant digits.
TimestampIt is an i64 value in microseconds. Commonly used for timestamp fields for timeseries and aggregations.

También puedes crear enums dentro de un esquema. Los enums tienen la siguiente sintaxis:

enum TokenStatus {
OriginalOwner
SecondOwner
ThirdOwner
}

Once the enum is defined in the schema, you can use the string representation of the enum value to set an enum field on an entity. For example, you can set the tokenStatus to SecondOwner by first defining your entity and subsequently setting the field with entity.tokenStatus = "SecondOwner". The example below demonstrates what the Token entity would look like with an enum field:

More detail on writing enums can be found in the GraphQL documentation.

Relaciones entre Entidades

Enlace a esta sección

Una entidad puede tener una relación con otra u otras entidades de su esquema. Estas relaciones pueden ser recorridas en sus consultas. Las relaciones en The Graph son unidireccionales. Es posible simular relaciones bidireccionales definiendo una relación unidireccional en cada "extremo" de la relación.

Las relaciones se definen en las entidades como cualquier otro campo, salvo que el tipo especificado es el de otra entidad.

Relaciones Uno a Uno

Enlace a esta sección

Define a Transaction entity type with an optional one-to-one relationship with a TransactionReceipt entity type:

type Transaction @entity(immutable: true) {
id: Bytes!
transactionReceipt: TransactionReceipt
}
type TransactionReceipt @entity(immutable: true) {
id: Bytes!
transaction: Transaction
}

Relaciones one-to-many

Enlace a esta sección

Define a TokenBalance entity type with a required one-to-many relationship with a Token entity type:

type Token @entity(immutable: true) {
id: Bytes!
}
type TokenBalance @entity {
id: Bytes!
amount: Int!
token: Token!
}

Búsquedas Inversas

Enlace a esta sección

Reverse lookups can be defined on an entity through the @derivedFrom field. This creates a virtual field on the entity that may be queried but cannot be set manually through the mappings API. Rather, it is derived from the relationship defined on the other entity. For such relationships, it rarely makes sense to store both sides of the relationship, and both indexing and query performance will be better when only one side is stored and the other is derived.

En el caso de las relaciones one-to-many, la relación debe almacenarse siempre en el lado "one", y el lado "many" debe derivarse siempre. Almacenar la relación de esta manera, en lugar de almacenar una array de entidades en el lado "many", resultará en un rendimiento dramáticamente mejor tanto para la indexación como para la consulta del subgrafo. En general, debe evitarse, en la medida de lo posible, el almacenamiento de arrays de entidades.

We can make the balances for a token accessible from the token by deriving a tokenBalances field:

type Token @entity(immutable: true) {
id: Bytes!
tokenBalances: [TokenBalance!]! @derivedFrom(field: "token")
}
type TokenBalance @entity {
id: Bytes!
amount: Int!
token: Token!
}

Relaciones de many-to-many

Enlace a esta sección

Para las relaciones de many-to-many, como los usuarios pueden pertenecer a cualquier número de organizaciones, la forma más directa, pero generalmente no la más eficaz, de modelar la relación es en un array en cada una de las dos entidades implicadas. Si la relación es simétrica, sólo es necesario almacenar un lado de la relación y el otro puede derivarse.

Define a reverse lookup from a User entity type to an Organization entity type. In the example below, this is achieved by looking up the members attribute from within the Organization entity. In queries, the organizations field on User will be resolved by finding all Organization entities that include the user's ID.

type Organization @entity {
id: Bytes!
name: String!
members: [User!]!
}
type User @entity {
id: Bytes!
name: String!
organizations: [Organization!]! @derivedFrom(field: "members")
}

A more performant way to store this relationship is through a mapping table that has one entry for each User / Organization pair with a schema like

type Organization @entity {
id: Bytes!
name: String!
members: [UserOrganization!]! @derivedFrom(field: "organization")
}
type User @entity {
id: Bytes!
name: String!
organizations: [UserOrganization!] @derivedFrom(field: "user")
}
type UserOrganization @entity {
id: Bytes! # Set to `user.id.concat(organization.id)`
user: User!
organization: Organization!
}

Este enfoque requiere que las consultas desciendan a un nivel adicional para recuperar, por ejemplo, las organizaciones para los usuarios:

query usersWithOrganizations {
users {
organizations {
# this is a UserOrganization entity
organization {
name
}
}
}
}

Esta forma más elaborada de almacenar las relaciones many-to-many se traducirá en menos datos almacenados para el subgrafo y, por tanto, en un subgrafo que suele ser mucho más rápido de indexar y consultar.

Agregar comentarios al esquema

Enlace a esta sección

As per GraphQL spec, comments can be added above schema entity attributes using the hash symbol #. This is illustrated in the example below:

type MyFirstEntity @entity {
# unique identifier and primary key of the entity
id: Bytes!
address: Bytes!
}

Definición de campos de búsqueda de texto completo

Enlace a esta sección

Las consultas de búsqueda de texto completo filtran y clasifican las entidades basándose en una entrada de búsqueda de texto. Las consultas de texto completo pueden devolver coincidencias de palabras similares procesando el texto de la consulta en stems antes de compararlo con los datos del texto indexado.

La definición de una consulta de texto completo incluye el nombre de la consulta, el diccionario lingüístico utilizado para procesar los campos de texto, el algoritmo de clasificación utilizado para ordenar los resultados y los campos incluidos en la búsqueda. Cada consulta de texto completo puede abarcar varios campos, pero todos los campos incluidos deben ser de un solo tipo de entidad.

To add a fulltext query, include a _Schema_ type with a fulltext directive in the GraphQL schema.

type _Schema_
@fulltext(
name: "bandSearch"
language: en
algorithm: rank
include: [{ entity: "Band", fields: [{ name: "name" }, { name: "description" }, { name: "bio" }] }]
)
type Band @entity {
id: Bytes!
name: String!
description: String!
bio: String
wallet: Address
labels: [Label!]!
discography: [Album!]!
members: [Musician!]!
}

The example bandSearch field can be used in queries to filter Band entities based on the text documents in the name, description, and bio fields. Jump to GraphQL API - Queries for a description of the fulltext search API and more example usage.

query {
bandSearch(text: "breaks & electro & detroit") {
id
name
description
wallet
}
}

Feature Management: From specVersion 0.0.4 and onwards, fullTextSearch must be declared under the features section in the subgraph manifest.

Idiomas admitidos

Enlace a esta sección

La elección de un idioma diferente tendrá un efecto definitivo, aunque a veces sutil, en la API de búsqueda de texto completo. Los campos cubiertos por un campo de consulta de texto completo se examinan en el contexto de la lengua elegida, por lo que los lexemas producidos por las consultas de análisis y búsqueda varían de un idioma a otro. Por ejemplo: al utilizar el diccionario turco compatible, "token" se convierte en "toke", mientras que el diccionario inglés lo convierte en "token".

Diccionarios de idiomas admitidos:

CodeDiccionario
simpleGeneral
daDanish
nlDutch
enEnglish
fiFinnish
frFrench
deGerman
huHungarian
itItalian
noNorwegian
ptPortugués
roRomanian
ruRussian
esSpanish
svSwedish
trTurkish

Algoritmos de Clasificación

Enlace a esta sección

Algoritmos admitidos para ordenar los resultados:

AlgorithmDescription
rankUsa la calidad de coincidencia (0-1) de la consulta de texto completo para ordenar los resultados.
rango de proximidadSimilar to rank but also includes the proximity of the matches.
Editar página

Anterior
Subgraph Manifest
Siguiente
Writing AssemblyScript Mappings
Editar página