数据库映射
这是 GraphQL 库版本 6 的文档。对于长期支持 (LTS) 版本 5,请参阅 GraphQL 库版本 5 LTS。 |
此页面描述了如何使用指令进行数据库映射。GraphQL 类型定义中的每个类型都可以映射到 Neo4j 数据库中的实体,例如节点、关系和关系属性。
@node
将 @node
指令添加到 GraphQL 类型表示它代表一个 Neo4j 节点。例如,要表示一个 Neo4j 节点,其标签为“Movie”且具有一个名为“title”的字符串类型属性
type Movie @node {
title: String
}
在版本 6.x 中,不需要使用 |
如果未另行指定,则 GraphQL 类型名称将用作表示的 Neo4j 节点的标签。可以使用参数 labels
显式定义 Neo4j 节点标签。
labels
此参数定义在 Neo4j 中使用的标签列表,而不是 GraphQL 类型名称。
type Dog @node(labels: ["K9"]) {
name: String!
}
这样,以下查询
{
dogs {
name
}
}
生成 Cypher 查询
MATCH (this: K9)
RETURN this { .name } as name
如果 GraphQL 类型名称仍应用作标签,则也需要指定它。
type Dog @node(labels: ["Dog", "K9"]) {
name: String!
}
这样,以下查询
{
dogs {
name
}
}
生成 Cypher 查询
MATCH (this:Dog:K9)
RETURN this { .name } as this
定义 |
以下示例导致为标签 K9
和属性 name
断言唯一约束
type Dog @node(labels: ["K9", "Dog"]) {
name: String! @unique
}
使用 $jwt
和 $context
在某些情况下,您可能希望根据请求的用户生成动态标签。为此,您可以使用变量 $jwt
在 JWT 中定义自定义标签。
type User @node(labels: ["$jwt.username"]) {
name: String!
}
以下查询会根据用户 JWT 生成不同的 Cypher 查询
{
users {
name
}
}
假设 JWT 中有一个用户,其值为 "username": "arthur"
,则 Cypher 查询如下所示
MATCH (this:arthur)
RETURN this { .name } as this
类似地,可以直接传递上下文值
type User @node(label: ["$context.appId"]) {
name: String!
}
使用 Apollo 运行服务器时
const server = new ApolloServer({
schema: await neoSchema.getSchema(),
});
await startStandaloneServer(server, {
context: async ({ req }) => ({ req, appId: "myApp" }),
});
@relationship
关系通过使用指令(在本例中为 @relationship
)标记特定字段来表示。它定义了数据库中的关系类型及其方向。
以下类型定义添加了第二个节点类型 Actor
,并通过 ACTED_IN
关系连接了 Movie
和 Actor
type Movie @node {
title: String
actors: [Actor!]! @relationship(type: "ACTED_IN", direction: IN)
}
type Actor @node {
name: String
movies: [Movie!]! @relationship(type: "ACTED_IN", direction: OUT)
}
请注意,在这种情况下,关系的每个“端”上都有一个指令,但这不是必需的。
@relationshipProperties
定义
"""Required to differentiate between interfaces for relationship properties, and otherwise."""
directive @relationshipProperties on OBJECT
@relationshipProperties
只能用于接口。
用法
为了向关系添加属性,请向类型定义中添加一个新的类型,并使用 @relationshipProperties
指令进行装饰。
例如,对于“ACTED_IN”关系,添加一个属性“roles”
type Movie @node {
title: String
actors: [Actor!]! @relationship(type: "ACTED_IN", direction: IN, properties: "ActedIn")
}
type Actor @node {
name: String
movies: [Movie!]! @relationship(type: "ACTED_IN", direction: OUT, properties: "ActedIn")
}
type ActedIn @relationshipProperties {
roles: [String]
}
请注意,除了此类型之外,在现有的 @relationship
指令中还添加了一个键 properties
。有关更多信息,请参阅 类型定义 → 关系。
@alias
此指令将 GraphQL 字段映射到节点或关系上的 Neo4j 属性。它可以用于任何不是 @cypher
或 @relationship
字段的字段。
例如
type User @node {
id: ID! @id @alias(property: "dbId")
username: String!
}
type User @node {
id: ID! @id
username: String! @alias(property: "dbUserName")
livesIn: [City!]! @relationship(direction: OUT, type: "LIVES_IN", properties: "UserLivesInProperties")
}
type City @node {
name: String
}
type UserLivesInProperties @relationshipProperties {
since: DateTime @alias(property: "moveInDate")
}
别名中的属性会自动转义(用反引号 `` 括起来),因此无需在周围添加转义字符。 |