### Full Apollo Federation Subgraph Setup with Neo4j Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/integrations/apollo-federation.adoc This complete example demonstrates setting up an Apollo Server with a Neo4j-backed subgraph schema using the Neo4j GraphQL library and starting a standalone server. ```javascript import { ApolloServer } from "@apollo/server"; import { startStandaloneServer } from "@apollo/server/standalone"; import { Neo4jGraphQL } from "@neo4j/graphql"; const typeDefs = `#graphql type User @key(fields: "id") @node { id: ID! name: String! } `; const driver = neo4j.driver("bolt://localhost:7687", neo4j.auth.basic("username", "password")); const neo4jGraphQL = new Neo4jGraphQL({ typeDefs, driver, }) const schema = await neo4jGraphQL.getSubgraphSchema(); const server = new ApolloServer({ schema, }); const { url } = await startStandaloneServer(server); console.log(`πŸš€ Server ready at ${url}`); ``` -------------------------------- ### Install Dependencies Source: https://github.com/neo4j/docs-graphql/blob/7.x/README.adoc Run this command to install the necessary packages for the project. ```bash npm i ``` -------------------------------- ### Full Example: Self-hosted GraphQL Server Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/getting-started/graphql-self-hosted.adoc Combines all previous steps into a complete, runnable example for a self-hosted Neo4j GraphQL API. ```javascript import { ApolloServer } from '@apollo/server'; import { startStandaloneServer } from '@apollo/server/standalone'; import { Neo4jGraphQL } from "@neo4j/graphql"; import neo4j from "neo4j-driver"; const typeDefs = `#graphql type Product @node { productName: String category: [Category!]! @relationship(type: "PART_OF", direction: OUT) } type Category @node { categoryName: String ``` -------------------------------- ### Initialize Neo4j GraphQL Server Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/getting-started/graphql-self-hosted.adoc Defines the GraphQL schema, connects to the Neo4j database using the provided driver, and starts an Apollo Server. Ensure you have the necessary Neo4j driver and Apollo Server packages installed. ```javascript const neo4j = require('neo4j-driver'); const { Neo4jGraphQL } = require('@neo4j/graphql-ogm'); const { ApolloServer } = require('@apollo/server'); const { startStandaloneServer } = require('@apollo/server/standalone'); const typeDefs = ` type Product @node { productName: String! products: [Product!]! @relationship(type: "PART_OF", direction: IN) } `; const driver = neo4j.driver( "neo4j://localhost:7687", neo4j.auth.basic("username", "password") ); const neoSchema = new Neo4jGraphQL({ typeDefs, driver }); const server = new ApolloServer({ schema: await neoSchema.getSchema(), }); const { url } = await startStandaloneServer(server, { context: async ({ req }) => ({ req }), listen: { port: 4000 }, }); console.log(`πŸš€ Server ready at ${url}`); ``` -------------------------------- ### Configure package.json for JavaScript Start Script Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/integrations/apollo-federation.adoc Replaces the default 'scripts' entry in 'package.json' to define how to start the Node.js application. ```json { // ...etc. "scripts": { "start": "node index.js" } // other dependencies } ``` -------------------------------- ### Configure package.json for TypeScript Build and Start Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/integrations/apollo-federation.adoc Updates the 'scripts' in 'package.json' to include commands for compiling TypeScript and starting the application. ```json { // ...etc. "scripts": { "compile": "tsc", "start": "npm run compile && node ./dist/index.js" } // other dependencies } ``` -------------------------------- ### Query and Mutation Examples Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/directives/custom-logic.adoc Examples demonstrating how to define query and mutation fields using the @cypher directive. ```APIDOC ==== On a query type field The following example demonstrates a query to return all of the actors in the database: [source, graphql, indent=0] ---- type Actor @node { actorId: ID! name: String } type Query { allActors: [Actor] @cypher( statement: """ MATCH (a:Actor) RETURN a """, columnName: "a" ) } ---- ==== On a mutation type field The following example demonstrates a mutation using a Cypher query to insert a single actor with the specified name argument: [source, graphql, indent=0] ---- type Actor @node { actorId: ID! name: String } type Mutation { createActor(name: String!): Actor @cypher( statement: """ CREATE (a:Actor {name: $name}) RETURN a """, columnName: "a" ) } ---- ``` -------------------------------- ### Create ApolloServer Instance and Start Server Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/getting-started/graphql-self-hosted.adoc Creates an Apollo Server instance with the generated schema and starts a standalone server to listen for GraphQL requests. ```javascript const server = new ApolloServer({ schema: await neoSchema.getSchema(), }); const { url } = await startStandaloneServer(server, { listen: { port: 4000 }, }); console.log(`πŸš€ Server ready at ${url}`); ``` -------------------------------- ### Install Dependencies for Apollo Server with Subscriptions Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/subscriptions/getting-started.adoc Install necessary npm packages for setting up an Apollo Server with WebSocket support and Neo4j integration. ```bash npm i --save ws graphql-ws neo4j-driver @neo4j/graphql express @apollo/server body-parser cors ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/integrations/apollo-federation.adoc Installs the core dependencies required for running an Apollo Server with Neo4j GraphQL, including the Neo4j driver. ```bash npm install @apollo/server @neo4j/graphql graphql neo4j-driver ``` -------------------------------- ### Basic Authentication Setup Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/security/impersonation-and-user-switching.adoc Configure basic authentication using username and password from request headers. ```javascript auth: neo4j.auth.basic(req.headers.user, req.headers.password), }, }), }); console.log(`πŸš€ Server ready at: ${url}`); ``` -------------------------------- ### Install Aura CLI on Windows Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/aura-graphql/aura-cli-configuration.adoc Move the downloaded aura-cli executable to the system's system32 directory for installation on Windows systems. ```cmd move aura-cli c:\\windows\\system32 ``` -------------------------------- ### Example Query Result Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/getting-started/toolbox.adoc This is an example of a successful response from a GraphQL query to the Neo4j database, showing the 'productName' of a single product. ```json { "data": { "products": [{ "productName": "New Product" }] } } ``` -------------------------------- ### GraphQL Authentication Directive Example Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/security/operations.adoc Example of an @authentication directive with specified operations. If no operations are specified, it defaults to all operations. ```graphql type Movie @authentication(operations: [CREATE]) @node { title: String! actors: [Actor!]! @relationship(type: "ACTED_IN", direction: IN) } ``` -------------------------------- ### Verify Aura CLI Installation Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/aura-graphql/aura-cli-configuration.adoc Check the installed Aura CLI version to confirm successful installation. ```bash aura-cli -v ``` -------------------------------- ### Install Aura CLI on Mac/Linux Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/aura-graphql/aura-cli-configuration.adoc Move the downloaded aura-cli executable to the system's binary path for installation on Mac or Linux systems. ```bash sudo mv aura-cli /usr/local/bin ``` -------------------------------- ### Create Neo4j GraphQL Subgraph Project Directory Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/integrations/apollo-federation.adoc Initializes a new project directory for the Neo4j GraphQL subgraph example. ```bash mkdir neo4j-graphql-subgraph-example cd neo4j-graphql-subgraph-example ``` -------------------------------- ### Install Neo4j GraphQL Library and Dependencies Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/getting-started/graphql-self-hosted.adoc Installs the necessary npm packages for the Neo4j GraphQL Library, Neo4j driver, and Apollo Server. ```bash npm install @neo4j/graphql graphql neo4j-driver @apollo/server ``` -------------------------------- ### Start Local Development Server Source: https://github.com/neo4j/docs-graphql/blob/7.x/README.adoc Use this command to launch a local server for viewing the built site and enabling live preview of AsciiDoc file changes. ```bash npm start ``` -------------------------------- ### Install TypeScript Development Dependencies Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/integrations/apollo-federation.adoc Installs the necessary TypeScript and related type definition packages for development. ```bash npm install --save-dev typescript @types/node @tsconfig/node-lts ``` -------------------------------- ### Example Authorization Header Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/security/configuration.adoc An example of an HTTP request with a Bearer token in the Authorization header. ```http POST / HTTP/1.1 authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJyb2xlcyI6WyJ1c2VyX2FkbWluIiwicG9zdF9hZG1pbiIsImdyb3VwX2FkbWluIl19.IY0LWqgHcjEtOsOw60mqKazhuRFKroSXFQkpCtWpgQI content-type: application/json ``` -------------------------------- ### Configure Antora Playbook - Start Page Source: https://github.com/neo4j/docs-graphql/blob/7.x/README.adoc Update the `start_page` attribute in your `preview.yml` playbook to match the `name` attribute defined in your `antora.yml` file. ```yaml site: start_page: docs-template:ROOT:index.adoc ``` -------------------------------- ### GraphQL Query Example for Input Argument Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/directives/custom-logic.adoc An example GraphQL query demonstrating how to provide a value for the `name` query, which is then used within the `@cypher` directive's statement. ```graphql query { name(value: "Jane Smith") } ``` -------------------------------- ### Simple Subscription to Creation Events Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/security/operations.adoc This example demonstrates a basic subscription to movie creation events. It uses both SUBSCRIBE and READ operations to trigger rules. ```APIDOC ## Subscription movieCreated ### Description Subscribe to events when a new movie is created and read its title. ### Method SUBSCRIBE, READ ### Endpoint N/A (GraphQL Subscription) ### Parameters N/A ### Request Example ```graphql subscription { movieCreated { createdMovie { title } } } ``` ### Response #### Success Response Returns data related to the created movie, including its title. #### Response Example ```json { "data": { "movieCreated": { "createdMovie": { "title": "Example Movie Title" } } } } ``` ``` -------------------------------- ### JWT Payload Example Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/security/configuration.adoc An example of a JWT payload where the 'roles' claim is nested under 'myApplication'. ```json { "sub": "user1234", "myApplication": { "roles": ["user", "admin"] } } ``` -------------------------------- ### Setup Directed HAS_FRIEND Relationship Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/relationships/operations.adoc Setup a directed HAS_FRIEND relationship from Bob to Alice in the database. This is required for Alice to appear in Bob's friends list when querying directed relationships. ```cypher MATCH (alice:Person {name: "Alice"}) MATCH (bob:Person {name: "Bob"}) MERGE (bob)-[:HAS_FRIEND]->(alice) ``` -------------------------------- ### Query by Phrase Example Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/directives/indexes-and-constraints.adoc Example of configuring and using the `@vector` directive for phrase-based searches, leveraging Neo4j GenAI plugin for embedding generation. Includes feature configuration and a sample query. ```APIDOC const neoSchema = new Neo4jGraphQL({ typeDefs, driver, features: { vector: { OpenAI: { token: "my-open-ai-token", model: "text-embedding-3-small", }, }, }, }); type Product @node @vector(indexes: [{ indexName: "productDescriptionIndex", embeddingProperty: "descriptionVector", provider: OPEN_AI, # Assuming this is configured in the server queryName: "searchByPhrase" }]) { id: ID! name: String! description: String! } query SearchProductsByPhrase($phrase: String!) { searchByPhrase(phrase: $phrase) { edges { cursor score node { id name description } } } } ``` -------------------------------- ### Run the GraphQL Server Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/getting-started/graphql-self-hosted.adoc Executes the Node.js script to start the Apollo Server. This command assumes your server code is saved in a file named 'index.js'. ```bash node index.js ``` -------------------------------- ### Node Creation Event Payload Example Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/subscriptions/customize-cdc.adoc This is an example of the JSON payload emitted for a node creation event, including event type, typename, property changes, node ID, and mutation timestamp. ```json { "event": "create", "typename": "Movie", "properties": { "old": undefined, "new": { "title": "The Matrix" } }, "id": "4:70bade62-2121-4808-9348-3ab77859e164:510", "timestamp": 1739286926054 } ``` -------------------------------- ### Nested Create using Update Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/mutations/update.adoc This example shows how to update a `User` and simultaneously create a new `Post` associated with that user. ```APIDOC ## updateUsers with Nested Create ### Description Updates a `User` node and can also create related nodes, such as `Post` nodes, as part of the same mutation. ### Method `mutation` ### Endpoint `updateUsers` ### Parameters #### Input Parameters - **where** (`UserWhere`) - Required - Specifies the criteria to find the `User` to update. - **update** (`UserUpdateInput`) - Required - Defines the fields and their new values for the `User`. Can include nested mutations like `create` for relationships. ### Request Example ```graphql mutation { updateUsers( where: { name: { eq: "John Doe" } } update: { posts: { create: [ { node: { content: "An interesting way of adding a new Post!" } } ] } } ) { users { id name posts { content } } } } ``` ### Response #### Success Response Returns an `UpdateUsersMutationResponse` containing the updated `User` and their related `Post`. #### Response Example ```json { "updateUsers": { "users": [ { "id": "some-user-id", "name": "John Doe", "posts": [ { "content": "An interesting way of adding a new Post!" } ] } ] } } ``` ``` -------------------------------- ### GraphQL Query Complexity Calculation Example Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/security/avoid-unbounded-queries.adoc This example demonstrates how to use the `getComplexity` function from `graphql-query-complexity` to calculate the complexity of an incoming query. It includes defining a schema, the query, and the default estimators. ```javascript const complexity = getComplexity({ schema, // result of Neo4jGraphQL.getSchema() query, // the GraphQL query document sent to server for execution estimators: DefaultComplexityEstimators, // exported from the neo4j/graphql package }); // Define your maximum complexity threshold const complexityThreshold = 1000; if (complexity > complexityThreshold) { throw new Error(`Query is too complex: ${complexity}. Maximum allowed complexity is ${complexityThreshold}.`); } ``` -------------------------------- ### Return all User nodes from their ID and name Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/queries-aggregations/queries.adoc This example demonstrates how to fetch all User nodes and retrieve their 'id' and 'name' fields. ```APIDOC ## Query ### Description Fetches all User nodes and returns their id and name. ### Query ```graphql query { users { id name } } ``` ``` -------------------------------- ### Example Mutations for Movie Creation and Update Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/subscriptions/filtering.adoc Demonstrates creating and updating movies, including one that meets the update filter criteria (average rating > 8) and one that does not. ```graphql mutation { makeTheMatrix: createMovies(input: {title: "The Matrix", averageRating: 8.7}) { title averageRating }, makeResurrections: createMovies(input: {title: "The Matrix Resurrections", averageRating: 5.7}) { title averageRating }, } mutation { updateTheMatrix: updateMovie( where: { title: { eq: "The Matrix" } } update: { averageRating: { set: 7.9 }} ) { title }, updateResurrections: updateMovie( where: { title: { eq: "The Matrix Resurrections" }} update: { averageRating: { set: 8.9 }} ) { title } } ``` -------------------------------- ### Full-text Search Usage Example Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/migration/index.adoc Example of using the @fulltext directive to configure a full-text index on the 'title' field of a 'Movie' type. This enables searching movies by their titles. ```graphql type Movie @node @fulltext( indexes: [ { indexName: "movieTitleIndex" queryName: "moviesByTitle" fields: ["title"] } ] ) { title: String! } ``` -------------------------------- ### Aura CLI Version Output Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/aura-graphql/aura-cli-configuration.adoc Expected output after verifying the Aura CLI installation. ```bash aura version v1.1.0 ``` -------------------------------- ### GraphQL Create Mutation for Movies Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/security/operations.adoc Example of a create mutation for movies, evaluating CREATE rules on the object and field definitions. ```graphql mutation { createMovies(input: [ { title: "The Matrix" } ]) { movies { title } } } ``` -------------------------------- ### Connections API Query Example Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/entity-and-connections-api.adoc Illustrates a query using the connections API to fetch movie connections, including edges, nodes, and pagination information. ```graphql query ConnectionApi { moviesConnection(first: 10) { edges { node { ``` -------------------------------- ### Create Project Directory and Initialize Node.js Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/getting-started/graphql-self-hosted.adoc Sets up a new directory for the project and initializes a Node.js project with ESM modules enabled. ```bash mkdir neo4j-graphql-example cd neo4j-graphql-example ``` ```bash npm init es6 --yes ``` ```bash touch index.js ``` -------------------------------- ### Filter users by event start time Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/filtering.adoc Find users who have events starting after a specific date and time. This example demonstrates filtering on a DateTime property of connected nodes. ```graphql query EventsAggregate { users(where: { eventsConnection: { aggregate: { node: { startTime: { gt:"2022-08-14T15:00:00Z" } } } } }) { name } } ``` -------------------------------- ### JavaScript Apollo Server Setup: Disable Version Prefix Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/migration/index.adoc Example of configuring Apollo Server to disable the 'addVersionPrefix' option for Cypher queries within the context. ```javascript await startStandaloneServer(server, { context: async ({ req }) => ({ req, cypherQueryOptions: { addVersionPrefix: false, }, }), listen: { port: 4000 }, }); ``` -------------------------------- ### String Comparison Filtering in GraphQL Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/filtering.adoc Filter string data using operators like 'startsWith', 'endsWith', and 'contains'. This example finds users whose names start with 'J'. ```graphql query { users(where: { name: { startsWith: "J" } }) { id name } } ``` -------------------------------- ### Example Vector Input for Query Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/directives/indexes-and-constraints.adoc Illustrates the expected format for the vector input argument in a GraphQL query, which is a list of float values. ```json { "vector": [ 0.123456, ... 0.654321, ] } ``` -------------------------------- ### Create Source Directory and Entrypoint File (JavaScript) Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/integrations/apollo-federation.adoc Creates the 'src' directory and an empty 'index.js' file for the application's entry point when using JavaScript. ```bash mkdir src touch src/index.js ``` -------------------------------- ### Count User Nodes with Specific Name Prefix Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/queries-aggregations/aggregations.adoc This example demonstrates how to count User nodes where the 'name' property starts with a specific string, using the 'where' argument in conjunction with the 'count' aggregation. ```graphql query { usersConnection(where: { name: { startsWith: "J" } }) { aggregate { count { nodes } } } } ``` -------------------------------- ### Book Type Implementing Node Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/integrations/relay-compatibility.adoc An example of a `Book` type implementing the `Node` interface, making it refetchable by Relay clients using the `node` query field. ```graphql type Book implements Node @node { id: ID! isbn: String! } ``` -------------------------------- ### Pass Neo4j Driver in Constructor Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/driver-configuration.adoc Instantiate Neo4jGraphQL with the Neo4j driver passed directly to the constructor. This is suitable for simple setups where the driver instance is readily available. ```javascript import { ApolloServer } from "@apollo/server"; import { startStandaloneServer } from "@apollo/server/standalone"; import { Neo4jGraphQL } from "@neo4j/graphql"; import neo4j from "neo4j-driver"; const typeDefs = `#graphql type User @node { name: String } `; const driver = neo4j.driver( "bolt://localhost:7687", neo4j.auth.basic("username", "password") ); const neoSchema = new Neo4jGraphQL({ typeDefs, driver }); const server = new ApolloServer({ schema: await neoSchema.getSchema(), }); await startStandaloneServer(server, { context: async ({ req }) => ({ req }), }); ``` -------------------------------- ### Entity API Query Example Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/entity-and-connections-api.adoc Demonstrates a query using the entity API to fetch movie titles, release years, and actors, with pagination and limits applied. ```graphql query EntityApi { movies(limit: 10, offset: 5) { title released actors(limit: 2) { name } } } ``` -------------------------------- ### GraphQL Order Calculation Result Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/graphql-modeling.adoc Example JSON response for an order query, showing product names and connection properties like quantity and unit price. ```json { "data": { "orders": [ { "products": [ { "productName": "Tofu" } ], "orderID": "6a5572bb-41fb-4263-913c-69c678c04766", "productsConnection": { "edges": [ { "properties": { "quantity": 5, "unitPrice": 23.25 } } ] } } ] } } ``` -------------------------------- ### Aggregation Example Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/entity-and-connections-api.adoc Provides an example of using aggregation to find the longest title among movies. ```graphql { moviesConnection { aggregate { node { title { longest } } } } } ``` -------------------------------- ### Query User with name "Jane Smith" and their posts Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/queries-aggregations/queries.adoc This example shows how to query for a specific User by their name and also retrieve the content of their associated posts. ```APIDOC ## Query ### Description Fetches a User named "Jane Smith" and retrieves the content of their posts. ### Query ```graphql query { users(where: { name: { eq: "Jane Smith" } }) { id name posts { content } } } ``` ``` -------------------------------- ### Complex Subscription to Relationship Events Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/security/operations.adoc This example shows a more advanced subscription for relationship events. It subscribes to movie relationship creation and reads related movie and actor information. ```APIDOC ## Subscription movieRelationshipCreated ### Description Subscribe to events when a movie relationship is created. Reads the movie title and the names of actors involved in the relationship. ### Method SUBSCRIBE, READ ### Endpoint N/A (GraphQL Subscription) ### Parameters N/A ### Request Example ```graphql subscription { movieRelationshipCreated { movie { title } createdRelationship { actors { node { name } } } } } ``` ### Response #### Success Response Returns data about the created movie relationship, including the movie title and actor names. #### Response Example ```json { "data": { "movieRelationshipCreated": { "movie": { "title": "Another Movie Title" }, "createdRelationship": { "actors": [ { "node": { "name": "Actor Name" } } ] } } } } ``` ``` -------------------------------- ### Create Source Directory and Entrypoint File (TypeScript) Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/integrations/apollo-federation.adoc Creates the 'src' directory and an empty 'index.ts' file for the application's entry point when using TypeScript. ```bash mkdir src touch src/index.ts ``` -------------------------------- ### Initialize Neo4j Driver and Neo4jGraphQL Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/driver-configuration.adoc Initializes the Neo4j driver with connection details and authentication, then creates a Neo4jGraphQL instance with the defined type definitions. ```javascript import neo4j from "neo4j-driver"; const typeDefs = `#graphql type User @node { name: String } `; const driver = neo4j.driver( "bolt://localhost:7687", neo4j.auth.basic("username", "password") ); const neoSchema = new Neo4jGraphQL({ typeDefs, driver }); await neoSchema.checkNeo4jCompat(); ``` -------------------------------- ### Initialize Node.js Project and Set Module Type Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/integrations/apollo-federation.adoc Initializes a new Node.js project and configures it to use ES Modules for features like top-level await. ```bash npm init --yes npm pkg set type="module" ``` -------------------------------- ### Create GraphQL API using CLI Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/aura-graphql/api-creation.adoc Provision a new GraphQL API with the Aura CLI. Replace placeholder values with your specific details. Ensure type definitions are saved in a file. ```bash aura-cli data-api graphql create --name YOUR_FRIENDLY_NAME --instance-id YOUR_AURA_INSTANCE_ID --instance-username YOUR_AURA_INSTANCE_USER --instance-password YOUR_AURA_INSTANCE_PASSWORD --type-definitions-file FULL_PATH_TO_YOUR_TYPE_DEFS ``` -------------------------------- ### Query by Vector Index Example Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/directives/indexes-and-constraints.adoc Example of defining a type with a vector index and the corresponding GraphQL query to perform a nearest neighbor search using a provided vector. ```APIDOC type Product @node @vector(indexes: [{ indexName: "productDescriptionIndex", embeddingProperty: "descriptionVector", queryName: "searchByDescription" }]) { id: ID! name: String! description: String! } query FindSimilarProducts($vector: [Float]!) { searchByDescription(vector: $vector) { edges { cursor score node { id name description } } } } { "vector": [ 0.123456, ..., 0.654321, ] } ``` -------------------------------- ### GraphQL Mutation to Create Product and Category Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/index.adoc Demonstrates creating a new product and its associated category using a GraphQL mutation. This mutation also creates the category if it does not exist. ```graphql mutation { createProducts( input: [ { productName: "New Product" category: { create: [{ node: { categoryName: "New Category" } }] } } ] ) { products { productName category { categoryName } } } } ``` -------------------------------- ### Create Blog and Posts Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/relationships/unions.adoc This mutation demonstrates how to create a Blog node and associate multiple Post nodes with it, utilizing the union type for content. ```APIDOC ## Create Blog and Posts ### Description This mutation creates a `Blog` node and its associated `Post` nodes. It shows how to structure the input for creating nodes and their relationships, including nested creations. ### Method mutation ### Endpoint N/A (GraphQL Operation) ### Request Example ```graphql mutation { Blog { create: [ { node: { title: "Our Blog" posts: { create: [ { node: { content: "Alice's Post" } }, { node: { content: "Bob's Post" } } ] } } } ] } } ``` ### Response #### Success Response Returns the created `users` with their `name`. #### Response Example ```json { "data": { "Blog": { "create": [ { "users": { "name": "Alice" } }, { "users": { "name": "Bob" } } ] } } } ``` ``` -------------------------------- ### GraphQL Type Mapping to Neo4j Relationship Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/directives/database-mapping.adoc Example of mapping a GraphQL field to a Neo4j relationship. This example shows a 'Movie' type with a 'title' property, implying a relationship will be defined elsewhere. ```graphql type Movie @node { title: String ``` -------------------------------- ### Query People After Setup Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/relationships/operations.adoc Run the same query after setting up the directed HAS_FRIEND relationship. This shows Alice now appearing in Bob's friends list due to the established directed relationship. ```json { "data": { "people": [ { "name": "Alice", "friends": [{ "name": "Bob" }], "acquaintances": [{ "name": "Bob" }] }, { "name": "Bob", "friends": [{ "name": "Alice" }], "acquaintances": [{ "name": "Alice" }] } ] } } ``` -------------------------------- ### Create Neo4jGraphQL Instance Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/getting-started/graphql-self-hosted.adoc Initializes the Neo4jGraphQL instance with the defined type definitions and a Neo4j driver connection. ```javascript const driver = neo4j.driver( "neo4j://localhost:7687", neo4j.auth.basic("username", "password") ); const neoSchema = new Neo4jGraphQL({ typeDefs, driver }); ``` -------------------------------- ### Update Movies Mutation Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/migration/index.adoc Example of updating movies using the `updateMovies` mutation. ```graphql mutation { updateMovies( where: { title: { eq: "Matrix" } }, update: { title: { set: "The Matrix" } } ) { movies { title } } } ``` -------------------------------- ### Generate AsciiDoc Source Files Source: https://github.com/neo4j/docs-graphql/blob/7.x/README.adoc Run this command to generate skeleton AsciiDoc files from navigation definitions, saving time when creating new documentation. ```bash npm run adoc-gen ``` -------------------------------- ### Initialize Apollo Server with Neo4j GraphQL Subgraph Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/integrations/apollo-federation.adoc Sets up an Apollo Server instance with a Neo4j GraphQL subgraph. Ensure NEO4J_URI, username, and password are correctly configured. ```javascript import { ApolloServer } from "@apollo/server"; import { startStandaloneServer } from "@apollo/server/standalone"; import { Neo4jGraphQL } from "@neo4j/graphql"; import neo4j from "neo4j-driver"; const typeDefs = `#graphql type User @node { id: ID! name: String! } `; const driver = neo4j.driver(NEO4J_URI, neo4j.auth.basic("username", "password")); const neo4jGraphQL = new Neo4jGraphQL({ typeDefs, driver, }) const schema = await neo4jGraphQL.getSchema(); const server = new ApolloServer({ schema, }); const { url } = await startStandaloneServer(server); console.log(`πŸš€ Server ready at ${url}`); ``` -------------------------------- ### GraphQL Data API Command Help Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/aura-graphql/aura-cli-configuration.adoc Displays the available commands and usage information for managing GraphQL Data APIs via the Aura CLI, including subcommands for authentication providers, CORS policies, and API lifecycle management. ```bash Allows you to programmatically provision and manage your GraphQL APIs Usage: aura-cli data-api graphql [command] Available Commands: auth-provider Allows you to programmatically manage Authentication providers for a specific GraphQL Data API cors-policy Allows you to manage the Cross-Origin Resource Sharing (CORS) policy for a specific GraphQL Data API create Creates a new GraphQL Data API delete Delete a GraphQL Data API get Get details of a GraphQL Data API list Returns a list of GraphQL Data APIs pause Pause a GraphQL Data API resume Resume a GraphQL Data API update Edit a GraphQL Data API Flags: -h, --help help for graphql Global Flags: --auth-url string --base-url string --output string Use "aura-cli data-api graphql [command] --help" for more information about a command. ``` -------------------------------- ### GraphQL Schema with @groupBy Directive Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/directives/schema-configuration/field-configuration.adoc Example of applying the @groupBy directive to a field in a GraphQL schema. ```graphql type Movie @node { title: String! year: Int! @groupBy } ``` -------------------------------- ### Update a Single Post Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/mutations/update.adoc This example demonstrates how to update the `content` of a specific `Post` using its `id`. ```APIDOC ## updatePosts ### Description Updates a `Post` node based on the provided `where` clause and applies the changes specified in the `update` input. ### Method `mutation` ### Endpoint `updatePosts` ### Parameters #### Input Parameters - **where** (`PostWhere`) - Required - Specifies the criteria to find the `Post` to update. - **update** (`PostUpdateInput`) - Required - Defines the fields and their new values for the `Post`. ### Request Example ```graphql mutation { updatePosts( where: { id: { eq: "892CC104-A228-4BB3-8640-6ADC9F2C2A5F" } } update: { content: { set: "Some new content for this Post!" } } ) { posts { content } } } ``` ### Response #### Success Response Returns an `UpdatePostsMutationResponse` containing a list of updated `Post` nodes. #### Response Example ```json { "updatePosts": { "posts": [ { "content": "Some new content for this Post!" } ] } } ``` ``` -------------------------------- ### Create and Connect People Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/relationships/operations.adoc Demonstrates creating a new person ('Charlie') and connecting them to an existing person ('Bob') via a 'friends' relationship. It also shows creating another person ('Dave') and establishing an 'acquaintances' relationship with 'Charlie'. ```APIDOC ## createPeople ### Description Creates new people nodes and establishes relationships between them. This mutation is used when the nodes do not exist in the database. ### Method mutation ### Endpoint createPeople ### Parameters #### Input - **input** (PersonCreateInput!): An array of input objects, where each object defines the properties of a person to be created and their relationships. - **name** (String): The name of the person. - **friends** (PersonFriendsConnectFieldInput): Specifies connections to existing friends. - **connect** (PersonWhereInput): Defines the criteria for connecting to existing friend nodes. - **node** (PersonWhereInput): Criteria for the friend node. - **name** (String - eq): The name of the friend to connect to. - **acquaintances** (PersonAcquaintancesCreateFieldInput): Specifies the creation of new acquaintances. - **create** (PersonCreateInput): Defines the properties of the acquaintance node to be created. - **node** (PersonCreateInput): The node to create. - **name** (String): The name of the acquaintance. ### Request Example ```json mutation { createPeople(input: [{ name: "Charlie", friends: { connect: { where: { node: { name: { eq: "Bob" } } } } }, acquaintances: { create: { node: { name: "Dave" } } } }]) { people { name friends { name } acquaintances { name } } } } ``` ### Response #### Success Response (200) Returns information about the created people nodes and their relationships. - **people** (Person): The created person nodes. - **name** (String): The name of the person. - **friends** (Person): The connected friends. - **acquaintances** (Person): The connected acquaintances. #### Response Example ```json { "data": { "createPeople": { "people": [ { "name": "Charlie", "friends": [ { "name": "Bob" } ], "acquaintances": [ { "name": "Dave" } ] } ] } } } ``` ``` -------------------------------- ### Querying a Node with Explicit Labels Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/directives/database-mapping.adoc Example query against the 'Dog' node, which is mapped to Neo4j nodes with the 'K9' label. ```graphql { dogs { name } } ``` -------------------------------- ### Add Aura CLI Credentials Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/aura-graphql/aura-cli-configuration.adoc Configure the Aura CLI with your API client ID and client secret. Replace placeholders with your actual credentials and a chosen label. ```bash aura-cli credential add --name --client-id --client-secret ``` -------------------------------- ### Example of a recursive query to limit Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/security/securing-a-graphql-api.adoc This recursive query can overload the server. Limiting query depth is a recommended security practice. ```graphql query { order(id: 42) { products { order { products { order { products { order { # and so on... } } } } } } } } ``` -------------------------------- ### Set up Apollo Server with WebSocket Support Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/subscriptions/getting-started.adoc Configure an Express server with Apollo Server, integrating WebSocket support via `graphql-ws` and `ws`. This setup includes Neo4j GraphQL integration and necessary plugins for graceful shutdown. ```javascript import { ApolloServer } from "@apollo/server"; import { expressMiddleware } from "@apollo/server/express4"; import { ApolloServerPluginDrainHttpServer } from "@apollo/server/plugin/drainHttpServer"; import bodyParser from 'body-parser'; import cors from "cors"; import { createServer } from "http"; import neo4j from 'neo4j-driver'; import { Neo4jGraphQL } from '@neo4j/graphql'; import { WebSocketServer } from "ws"; import { useServer } from "graphql-ws/lib/use/ws"; import express from 'express'; const typeDefs = ` type Movie @node { title: String } type Actor @node { name: String } extend schema @subscription `; const driver = neo4j.driver("bolt://localhost:7687", neo4j.auth.basic("username", "password")); const neoSchema = new Neo4jGraphQL({ typeDefs, driver, features: { subscriptions: true }, }); async function main() { // Apollo server setup with WebSockets const app = express(); const httpServer = createServer(app); const wsServer = new WebSocketServer({ server: httpServer, path: "/graphql", }); // Neo4j schema const schema = await neoSchema.getSchema(); const serverCleanup = useServer( { schema, context: (ctx) => { return ctx; }, }, wsServer ); const server = new ApolloServer({ schema, plugins: [ ApolloServerPluginDrainHttpServer({ httpServer }), { async serverWillStart() { return Promise.resolve({ async drainServer() { await serverCleanup.dispose(); }, }); }, }, ], }); await server.start(); app.use( "/graphql", cors(), bodyParser.json(), expressMiddleware(server, { context: async ({ req }) => ({ req }), }) ); const PORT = 4000; httpServer.listen(PORT, () => { console.log(`Server is now running on http://localhost:${PORT}/graphql`); }); } main(); ``` -------------------------------- ### Using @sortable to Disable Sorting Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/directives/schema-configuration/field-configuration.adoc Example of applying the @sortable directive with byValue set to false to exclude a field from sorting. ```graphql type Movie @node { title: String! description: String! @sortable(byValue: false) } ``` -------------------------------- ### Cursor-based pagination: Fetch initial set of posts Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/queries-aggregations/pagination.adoc Use `postsConnection(first: 10)` to fetch the first 10 posts for a user. The response includes `endCursor` and `hasNextPage` for subsequent pagination. ```graphql query { users(where: { name: { eq: "John Smith" } }) { name postsConnection(first: 10) { edges { node { content } } pageInfo { endCursor hasNextPage } } } } ``` -------------------------------- ### Check GraphQL API Provisioning Status using CLI Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/aura-graphql/api-creation.adoc Monitor the provisioning status of your GraphQL API. Replace YOUR_GRAPHQL_API_ID and YOUR_AURA_INSTANCE_ID with your actual values. ```bash aura-cli data-api graphql get YOUR_GRAPHQL_API_ID --instance-id YOUR_AURA_INSTANCE_ID ``` -------------------------------- ### GraphQL Filtered Products by Supplier Result Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/graphql-modeling.adoc Example JSON response showing a list of product names filtered by supplier. ```json { "data": { "products": [ { "productName": "Boston Crab Meat" }, { "productName": "Jack's New England Clam Chowder" } ] } } ``` -------------------------------- ### Check for GraphQL Data API Commands Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/aura-graphql/aura-cli-configuration.adoc Verify that the beta commands, specifically for GraphQL Data API management, are now available after enabling the beta feature. ```bash aura-cli data-api graphql ``` -------------------------------- ### GraphQL Filtered Products by Category Result Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/graphql-modeling.adoc Example JSON response showing a list of product names filtered by category. ```json { "data": { "products": [ { "productName": "Uncle Bob's Organic Dried Pears" }, { "productName": "Tofu" }, { "productName": "RΓΆssle Sauerkraut" }, { "productName": "Manjimup Dried Apples" }, { "productName": "Longlife Tofu" } ] } } ``` -------------------------------- ### Neo4jGraphQL Feature Configuration for OpenAI Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/directives/indexes-and-constraints.adoc Demonstrates how to configure Neo4jGraphQL with provider credentials, specifically for OpenAI, to enable query by phrase functionality. ```javascript const neoSchema = new Neo4jGraphQL({ typeDefs, driver, features: { vector: { OpenAI: { token: "my-open-ai-token", model: "text-embedding-3-small", }, }, }, }); ``` -------------------------------- ### Querying a Node with Dynamic JWT Label Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/directives/database-mapping.adoc Example query against the 'User' node, which uses a dynamic label based on the JWT. ```graphql { users { name } } ``` -------------------------------- ### GraphQL Type Definition with @id Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/directives/autogeneration.adoc Example of a `User` type definition using the `@id` directive to autogenerate the `id` field. ```graphql type User @node { id: ID! @id username: String! } ``` -------------------------------- ### Get Movie by title with related Person Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/relationships/single-relationships.adoc This query retrieves a Movie by its title and includes the related Person through the DIRECTED relationship. ```APIDOC ## Get Movie by title with related Person ### Description This query retrieves a Movie by its title and includes the related Person through the DIRECTED relationship. ### Method query ### Endpoint N/A (GraphQL Operation) ### Query Parameters - **title** (String) - The title of the movie to query. ### Response #### Success Response (200) - **movies** (array) - A list of movies matching the query. - **title** (String) - The title of the movie. - **director** (object) - The director of the movie. - **name** (String) - The name of the director. ### Response Example ```json { "data": { "movies": [ { "title": "No Country for Old Men", "director": { "name": "Joel Coen" } } ] } } ``` ``` -------------------------------- ### JWT Payload with Special Characters Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/security/configuration.adoc An example JWT payload where a nested path contains special characters like '.' which require escaping. ```json { "sub": "user1234", "http://www.myapplication.com": { "roles": ["user", "admin"] } } ``` -------------------------------- ### Generate HTML Output Source: https://github.com/neo4j/docs-graphql/blob/7.x/README.adoc Execute this command to convert AsciiDoc source files into HTML format. ```bash npm run build ``` -------------------------------- ### Query with Custom Pluralization Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/directives/schema-configuration/type-configuration.adoc Example GraphQL query demonstrating the use of a custom pluralized type name generated by the @plural directive. ```graphql { techs { title } } ``` -------------------------------- ### Switch User via HTTP Headers Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/security/impersonation-and-user-switching.adoc Configure user switching by providing username and password from HTTP headers. Note: This is not recommended for production use. ```javascript import { ApolloServer } from "@apollo/server"; import { startStandaloneServer } from "@apollo/server/standalone"; import { Neo4jGraphQL } from "@neo4j/graphql"; import neo4j from "neo4j-driver"; const typeDefs = `#graphql type Movie @node { title: String! } `; const driver = neo4j.driver( "neo4j://localhost:7687", neo4j.auth.basic("username", "password") ); const neo4jGraphql = new Neo4jGraphQL({ typeDefs, driver, }); const schema = await neo4jGraphql.getSchema(); const server = new ApolloServer({ schema, }); const { url } = await startStandaloneServer(server, { // Your async context function should async and return an object context: async ({ req }) => ({ sessionConfig: { auth: neo4j.auth.basic(req.headers.user, req.headers.password), }, }), }); console.log(`πŸš€ Server ready at: ${url}`); ``` ```typescript import { ApolloServer } from "@apollo/server"; import { startStandaloneServer } from "@apollo/server/standalone"; import { Neo4jGraphQL, Neo4jGraphQLContext } from "@neo4j/graphql"; import neo4j from "neo4j-driver"; const typeDefs = `#graphql type Movie @node { title: String! } `; const driver = neo4j.driver( "neo4j://localhost:7687", neo4j.auth.basic("username", "password") ); const neo4jGraphql = new Neo4jGraphQL({ typeDefs, driver, }); const schema = await neo4jGraphql.getSchema(); const server = new ApolloServer({ schema, }); const { url } = await startStandaloneServer(server, { // Your async context function should async and return an object context: async ({ req }) => ({ sessionConfig: { auth: neo4j.auth.basic(req.headers.user, req.headers.password), }, }), }); console.log(`πŸš€ Server ready at: ${url}`); ``` -------------------------------- ### GraphQL Query with Custom Full-Text Name Source: https://github.com/neo4j/docs-graphql/blob/7.x/modules/ROOT/pages/directives/indexes-and-constraints.adoc Example GraphQL query using the custom-named full-text query 'CustomProductFulltextQuery' to search for products. ```graphql query { CustomProductFulltextQuery(phrase: "Hot sauce", sort: [{ score: ASC }]) { score product { name } } } ```