选择集

就其本身而言,选择集是 GraphQL 的一个特定术语。例如,当您执行查询时,您将拥有操作

query {
    myOperation
}

并且您还有一个选择集,例如以下内容

query {
    myOperation {
        field1
        field2
    }
}

在这种情况下,此代码段是选择集

{
    field1
    field2
}

使用 OGM 时,您默认情况下不必提供选择集。这样做会使使用 OGM 感觉更像是直接查询 GraphQL 模式,而 OGM 被设计为对其进行抽象。这是通过自动生成的简单选择集实现的。

给定以下类型定义

type Movie {
    id: ID
    name: String
    genres: [Genre!]! @relationship(type: "IN_GENRE", direction: OUT)
    customCypher: String! @cypher(statement: "RETURN someCustomData")
}

type Genre {
    name: String
}

生成的选集不包含关系字段或自定义 Cypher 字段,因为它们在计算上可能代价很高。因此,给定上述类型定义,生成的选集将为

{
    id
    name
}

这意味着,默认情况下,当查询节点时,您只会获得返回的 .id.name 属性。如果要选择更多字段,则可以在执行时或作为模型上的静态定义选择集,如下节所述。

执行时选择集

使用这种方法,您可以在每次与 OGM 交互时传入一个选择集。如果每次请求数据时选择集都不同,这是一种合适的方法。

这是一个示例

const { OGM } = require("@neo4j/graphql-ogm")
const neo4j = require("neo4j-driver");

const driver = neo4j.driver(
    "bolt://localhost:7687",
    neo4j.auth.basic("username", "password")
);

const typeDefs = `
    type Movie {
        id: ID
        name: String
        genres: [Genre!]! @relationship(type: "IN_GENRE", direction: OUT)
        customCypher: String! @cypher(statement: "RETURN someCustomData")
    }

    type Genre {
        name: String
    }
`;

const ogm = new OGM({ typeDefs, driver });
const Movie = ogm.model("Movie");

const selectionSet = `
    {
        id
        name
        genres {
            name
        }
        customCypher
    }
`;

ogm.init().then(() => {
    Movie.find({ selectionSet }).then((movies) => {
        // work with movies
    })
});

请注意,参数 selectionSet 会在每次调用 Movie.find() 函数时传递。

设置默认选择集

使用这种方法,您可以将选择集分配给特定模型,以便无论何时查询它,它始终默认返回这些字段。如果生成的选集没有提供足够的数据,但您不需要在每个请求上都动态地使用选集,这将很有用。

这是一个示例

const { OGM } = require("@neo4j/graphql-ogm")
const neo4j = require("neo4j-driver");

const driver = neo4j.driver(
    "bolt://localhost:7687",
    neo4j.auth.basic("username", "password")
);

const typeDefs = `
    type Movie {
        id: ID
        name: String
        genres: [Genre!]! @relationship(type: "IN_GENRE", direction: OUT)
        customCypher: String! @cypher(statement: "RETURN someCustomData")
    }

    type Genre {
        name: String
    }
`;

const ogm = new OGM({ typeDefs, driver });
const Movie = ogm.model("Movie");

const selectionSet = `
    {
        id
        name
        genres {
            name
        }
        customCypher
    }
`;

Movie.selectionSet = selectionSet;

ogm.init().then(() => {
    Movie.find().then((movies) => {
        // work with movies
    })
});

请注意,尽管未将此选择集传递给 Movie.find(),但请求的字段在每次请求中都会返回。