### Setup the Neo4j GraphQL Library Source: https://memgraph.com/docs/client-libraries/graphql Installs the Neo4j GraphQL Library, its dependencies, and Apollo Server. ```bash npm install @neo4j/graphql@7.2.0 graphql neo4j-driver @apollo/server ``` -------------------------------- ### Example download and install command Source: https://memgraph.com/docs/getting-started/install-memgraph/wsl This is an example of the download and install command using a specific version. ```bash wget https://download.memgraph.com/memgraph/v2.17.0/ubuntu-22.04/memgraph_2.17.0-1_amd64.deb -O memgraph.deb sudo dpkg -i memgraph.deb ``` -------------------------------- ### Download mgconsole - Start mgconsole (generic) Source: https://memgraph.com/docs/getting-started/cli Start mgconsole after downloading it, specifying host and port. ```bash ./mgconsole --host HOST --port PORT ``` -------------------------------- ### TTL Setup Examples Source: https://memgraph.com/docs/querying/time-to-live Examples demonstrating how to set up TTL with different periods and times. ```cypher # Run TTL every dat at 14:30 (will run immediately once if started after 14:30) ENABLE TTL AT "14:30:00"; # Run TTL every 2nd day at 4:00 (will run immediately once if started after 4:00) ENABLE TTL EVERY "2d" AT "04:00:00"; # Run TTL every 3 hours, starting from 19:45 today (will run immediately once if started after 19:45) ENABLE TTL EVERY "3h" AT "19:45:00"; ``` -------------------------------- ### mgconsole command prompt example Source: https://memgraph.com/docs/getting-started/cli Example of the mgconsole command prompt after starting the client. ```text mgconsole X.X Connected to 'memgraph://127.0.0.1:7687' Type :help for shell usage Quit the shell by typing Ctrl-D(eof) or :quit memgraph> ``` -------------------------------- ### Troubleshooting notes for Memgraph Source: https://memgraph.com/docs/getting-started/install-memgraph/fedora Example output showing common notes and warnings when starting a Memgraph instance, particularly related to missing Python libraries. ```text You are running Memgraph v1.4.0-community NOTE: Please install networkx to be able to use graph_analyzer module. Using Python: 3.8.2 (default, Jul 16 2020, 14:00:26) [GCC 9.3.0] NOTE: Please install networkx to be able to use Memgraph NetworkX wrappers. Using Python: 3.8.2 (default, Jul 16 2020, 14:00:26) [GCC 9.3.0] NOTE: Please install networkx, numpy, scipy to be able to use proxied NetworkX algorithms. E.g., CALL nxalg.pagerank(...). Using Python: 3.8.2 (default, Jul 16 2020, 14:00:26) [GCC 9.3.0] NOTE: Please install networkx to be able to use wcc module. Using Python: 3.8.2 (default, Jul 16 2020, 14:00:26) [GCC 9.3.0] ``` -------------------------------- ### Docker installation example for older versions Source: https://memgraph.com/docs/advanced-algorithms/install-mage Example command for older MAGE versions that included both MAGE and Memgraph versions. ```bash docker run -p 7687:7687 --name memgraph memgraph/memgraph-mage:3.1.1-memgraph-3.1.1 ``` -------------------------------- ### Build from source - Start mgconsole (generic) Source: https://memgraph.com/docs/getting-started/cli Start mgconsole after building from source, specifying host and port. ```bash mgconsole --host HOST --port PORT ``` -------------------------------- ### Docker installation example Source: https://memgraph.com/docs/advanced-algorithms/install-mage Example command to run Memgraph with MAGE using a specific version. ```bash docker run -p 7687:7687 --name memgraph memgraph/memgraph-mage:3.2 ``` -------------------------------- ### Download mgconsole - Start mgconsole (local default) Source: https://memgraph.com/docs/getting-started/cli Start mgconsole when Memgraph is running locally with default configuration. ```bash ./mgconsole --host 127.0.0.1 --port 7687 ``` -------------------------------- ### Example GraphQL Query Source: https://memgraph.com/docs/client-libraries/graphql An example GraphQL query to interact with Memgraph. ```graphql query Users { users { name posts { content } } } ``` -------------------------------- ### Install text editor (vim) Source: https://memgraph.com/docs/configuration/configuration-settings For example, if you want to use `vim` run: ```bash apt-get update && apt-get install -y vim ``` -------------------------------- ### Example Database State Setup Source: https://memgraph.com/docs/advanced-algorithms/available-algorithms/do Cypher queries to set up the initial database state for the example. ```cypher MERGE (a:Node {id: 0}) MERGE (b:Node {id: 1}) CREATE (a)-[:RELATION]->(b); MERGE (a:Node {id: 1}) MERGE (b:Node {id: 2}) CREATE (a)-[:RELATION]->(b); MERGE (a:Node {id: 0}) MERGE (b:Node {id: 2}) CREATE (a)-[:RELATION]->(b); MERGE (a:Node {id: 3}) MERGE (b:Node {id: 4}) CREATE (a)-[:RELATION]->(b); MERGE (a:Node {id: 3}) MERGE (b:Node {id: 5}) CREATE (a)-[:RELATION]->(b); MERGE (a:Node {id: 4}) MERGE (b:Node {id: 5}) CREATE (a)-[:RELATION]->(b); ``` -------------------------------- ### Build from source - Start mgconsole (local default) Source: https://memgraph.com/docs/getting-started/cli Start mgconsole after building from source when Memgraph is running locally with default configuration. ```bash mgconsole --host 127.0.0.1 --port 7687 ``` -------------------------------- ### Explicit Transaction Example Source: https://memgraph.com/docs/client-libraries/javascript An example showing how to initiate an explicit transaction with a specified default access mode. ```javascript let session = driver.session({ database: 'neo4j', defaultAccessMode: 'READ' }) let transaction = await session.beginTransaction() // await transaction.run('') // await transaction.run('') // ... await transaction.close() await session.close() ``` -------------------------------- ### Start Ubuntu Source: https://memgraph.com/docs/getting-started/install-memgraph/wsl Run the command below from PowerShell to launch Ubuntu. ```bash ubuntu ``` -------------------------------- ### Memgraph Docker Setup Source: https://memgraph.com/docs/ai-ecosystem/integrations Quickly start Memgraph using Docker. ```bash docker run -p 7687:7687 memgraph/memgraph:latest ``` -------------------------------- ### Minimal Working Example Source: https://memgraph.com/docs/client-libraries/rust This example demonstrates connecting to Memgraph, creating nodes and relationships, and fetching graph data using the Rust client library. ```rust use rsmgclient::{ConnectParams, Connection, Value, SSLMode, ConnectionStatus}; fn main() { // Connect to Memgraph let connect_params = ConnectParams { host: Some(String::from("localhost")), port: 7687, sslmode: SSLMode::Disable, ..Default::default() }; let mut connection = Connection::connect(&connect_params).unwrap(); // Check if connection is established. let status = connection.status(); if status != ConnectionStatus::Ready { println!("Connection failed with status: {:?}", status); return; } else { println!("Connection established with status: {:?}", status); } // Clear the graph. connection.execute_without_results("MATCH (n) DETACH DELETE n;").unwrap(); if let Err(e) = connection.commit() { println!("Error: {}", e); } let indexes = vec![ "CREATE INDEX ON :Developer(id);", "CREATE INDEX ON :Technology(id);", "CREATE INDEX ON :Developer(name);", "CREATE INDEX ON :Technology(name);", ]; let developer_nodes = vec![ "CREATE (n:Developer {id: 1, name:'Andy'});", "CREATE (n:Developer {id: 2, name:'John'});", "CREATE (n:Developer {id: 3, name:'Michael'});", ]; let technology_nodes = vec![ "CREATE (n:Technology {id: 1, name:'Memgraph', description: 'Fastest graph DB in the world!', createdAt: Date()})", "CREATE (n:Technology {id: 2, name:'Rust', description: 'Rust programming language ', createdAt: Date()})", "CREATE (n:Technology {id: 3, name:'Docker', description: 'Docker containerization engine', createdAt: Date()})", "CREATE (n:Technology {id: 4, name:'Kubernetes', description: 'Kubernetes container orchestration engine', createdAt: Date()})", "CREATE (n:Technology {id: 5, name:'Python', description: 'Python programming language', createdAt: Date()})", ]; let relationships = vec![ "MATCH (a:Developer {id: 1}),(b:Technology {id: 1}) CREATE (a)-[r:LOVES]->(b);", "MATCH (a:Developer {id: 2}),(b:Technology {id: 3}) CREATE (a)-[r:LOVES]->(b);", "MATCH (a:Developer {id: 3}),(b:Technology {id: 1}) CREATE (a)-[r:LOVES]->(b);", "MATCH (a:Developer {id: 1}),(b:Technology {id: 5}) CREATE (a)-[r:LOVES]->(b);", "MATCH (a:Developer {id: 2}),(b:Technology {id: 2}) CREATE (a)-[r:LOVES]->(b);", "MATCH (a:Developer {id: 3}),(b:Technology {id: 4}) CREATE (a)-[r:LOVES]->(b);", ]; for index in indexes { connection.execute_without_results(index).unwrap(); } if let Err(e) = connection.commit() { println!("Error: {}", e); } for developer_node in developer_nodes { connection.execute_without_results(developer_node).unwrap(); } if let Err(e) = connection.commit() { println!("Error: {}", e); } for technology_node in technology_nodes { connection.execute_without_results(technology_node).unwrap(); } if let Err(e) = connection.commit() { println!("Error: {}", e); } for relationship in relationships { connection.execute_without_results(relationship).unwrap(); } if let Err(e) = connection.commit() { println!("Error: {}", e); } // Fetch the graph. let columns = connection.execute("MATCH (n)-[r]->(m) RETURN n, r, m;", None); println!("Columns: {}", columns.unwrap().join(", ")); while let Ok(result) = connection.fetchall() { for record in result { for value in record.values { match value { Value::Node(node) => println!("Node: {}", node), Value::Relationship(edge) => println!("Edge: {}", edge), value => println!("Value: {}", value), } } } println!(); } // Close the connection. connection.close(); } ``` -------------------------------- ### Example Dockerfile for Memgraph Lab with custom SSL Source: https://memgraph.com/docs/data-visualization/user-manual/custom-base-path Dockerfile example for running Memgraph Lab with custom SSL certificates enabled and paths configured. ```dockerfile FROM memgraph/lab:latest # Environment variables ENV SSL_IS_ENABLED=true ENV SSL_CERT_PATH=./myssl/cert.pem ENV SSL_KEY_PATH=./myssl/key.pem ``` -------------------------------- ### Set up your script Source: https://memgraph.com/docs/client-libraries/nodejs Initialize your project and create a `package.json` file with the command: ```bash npm init ``` -------------------------------- ### Add start script to composer.json Source: https://memgraph.com/docs/client-libraries/php Example of how to add a start script to the composer.json file to run the application. ```json { "require": { "stefanak-michal/bolt": "^7" }, "scripts": { "start": "php -S localhost:4000" }, "config": { "allow-plugins": { "php-http/discovery": true } } } ``` -------------------------------- ### Set up your script Source: https://memgraph.com/docs/client-libraries/nodejs To make the actual program, create an `example.js` file and add the following code: ```javascript const express = require("express"); const app = express(); const port = 3000; var db = require("neo4j-driver"); app.get("/", async (req, res) => { const driver = db.driver("bolt://localhost:7687"); const session = driver.session(); try { const result = await session.executeWrite((tx) => tx.run( 'CREATE (a:Greeting) SET a.message = $message RETURN "Node " + id(a) + ": " + a.message', { message: "Hello, World!", } ) ); const singleRecord = result.records[0]; const greeting = singleRecord.get(0); console.log(greeting); res.send("Welcome to Node.js quick start guide!") } finally { await session.close(); } // On application exit: await driver.close(); }); app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`); }); ``` -------------------------------- ### Set up your script Source: https://memgraph.com/docs/client-libraries/javascript Create a new directory for your application and position yourself in it. ```bash mkdir myApp cd myApp ``` -------------------------------- ### Verbose execution info example Source: https://memgraph.com/docs/getting-started/cli Example output showing a breakdown of query execution time when the -verbose_execution_info flag is true. ```text Query COST estimate: 3066 Query PARSING time: 0.000175982 sec Query PLAN EXECUTION time: 0.0154524 sec Query PLANNING time: 8.054e-05 sec ``` -------------------------------- ### First Cypher query example Source: https://memgraph.com/docs/getting-started A basic Cypher query to return all nodes and relationships in the database. ```cypher MATCH (n)-[r]-(m) RETURN n, r, m; ``` -------------------------------- ### Set up your script Source: https://memgraph.com/docs/client-libraries/nodejs Create a new directory for your application and position yourself in it. ```bash mkdir MyApp cd MyApp ``` -------------------------------- ### Set up your script Source: https://memgraph.com/docs/client-libraries/nodejs Install _Express.js_ and the _Bolt driver_ in the `/MyApp` directory while adding them to the dependencies list: ```bash npm install express --save npm install neo4j-driver --save ``` -------------------------------- ### Registering a Read Procedure Source: https://memgraph.com/docs/custom-query-modules/cpp/cpp-example Example of registering a read procedure named 'get' using the AddProcedure function. This procedure takes a start node and length, and returns a Path. ```cpp extern "C" int mgp_init_module(struct mgp_module *module, struct mgp_memory *memory) { try { mgp::MemoryDispatcherGuard guard(memory); AddProcedure(RandomWalk, "get", mgp::ProcedureType::Read, {mgp::Parameter("start", mgp::Type::Node), mgp::Parameter("length", mgp::Type::Int)}, {mgp::Return("random_walk", mgp::Type::Path)}, module, memory); } catch (const std::exception &e) { return 1; } return 0; } ``` -------------------------------- ### Example JavaScript code Source: https://memgraph.com/docs/client-libraries/javascript Create an `example.js` file and add the following code: ```javascript (async () => { var db = require('neo4j-driver'); const URI = 'bolt://localhost:7687'; const USER = ''; const PASSWORD = ''; let driver; try { driver = db.driver(URI, db.auth.basic(USER, PASSWORD)); const serverInfo = await driver.getServerInfo(); console.log('Connection established'); console.log(serverInfo); const session = driver.session(); try { // Clear the database await session.run("MATCH (n) DETACH DELETE n;"); console.log("Database cleared."); // Create a user in the database await session.run("CREATE (:Person {name: 'Alice', age: 22});"); console.log("Record created."); // Get all of the nodes const result = await session.run("MATCH (n) RETURN n;"); console.log("Record matched."); const mark = result.records[0].get("n"); const label = mark.labels[0]; const name = mark.properties["name"]; const age = mark.properties["age"]; if (label != "Person" || name != "Alice" || age != 22) { console.error("Data doesn't match."); } console.log("Label: " + label); console.log("Name: " + name); console.log("Age: " + age); } catch (error) { console.error(error); } finally { session.close(); } driver.close(); } catch (err) { console.log(`Connection error\n${err}\nCause: ${err.cause}`); await driver.close(); return; } await driver.close(); })(); ``` -------------------------------- ### DFS Pre-order Nodes Usage Source: https://memgraph.com/docs/advanced-algorithms/available-algorithms/nxalg Example Cypher query to get nodes in a depth-first-search pre-ordering starting from a source node with a specified depth limit. ```cypher MATCH (source:Label) CALL nxalg.dfs_preorder_nodes(source, 10) YIELD nodes RETURN source, nodes AS preoder_nodes; ``` -------------------------------- ### Create index.js file Source: https://memgraph.com/docs/client-libraries/graphql Sets up the Neo4j GraphQL Library and connects to the Memgraph instance. ```bash touch index.js ``` ```javascript import { Neo4jGraphQL } from "@neo4j/graphql"; import { ApolloServer } from '@apollo/server' import { startStandaloneServer } from '@apollo/server/standalone'; import neo4j from 'neo4j-driver' const typeDefs = ` type Post @node { id: ID! @id content: String! creator: [User!]! @relationship(type: "HAS_POST", direction: IN) } type User @node { id: ID! @id name: String posts: [Post!]! @relationship(type: "HAS_POST", direction: OUT) } `; const driver = neo4j.driver( "bolt://localhost:7687", neo4j.auth.basic("", "") ); const neoSchema = new Neo4jGraphQL({ typeDefs, driver }); const server = new ApolloServer({ schema: await neoSchema.getSchema(), }); const { url } = await startStandaloneServer(server, { context: async ({ req }) => ({ req, sessionConfig: { database: "memgraph" }, cypherQueryOptions: { addVersionPrefix: false } }), listen: { port: 4000 }, }); console.log(`🚀 Server ready at ${url}`); ``` -------------------------------- ### Minimal Working Example Source: https://memgraph.com/docs/client-libraries/java This example demonstrates how to set up a connection, create indexes, add nodes and relationships, and query data using the Memgraph Java client library. ```java package org.example; import org.neo4j.driver.*; import org.neo4j.driver.Record; import org.neo4j.driver.types.Node; import java.util.Arrays; import java.util.List; public class HelloMemgraph implements AutoCloseable { // Driiver instance used across the application private final Driver driver; // Create a driver instance, and pass the uri, username and password if required public HelloMemgraph(String uri, String user, String password){ driver = GraphDatabase.driver(uri, AuthTokens.basic(user, password)); } // Creating indexes public void createIndexes() { List indexes = Arrays.asList( "CREATE INDEX ON :Developer(id);", "CREATE INDEX ON :Technology(id);", "CREATE INDEX ON :Developer(name);", "CREATE INDEX ON :Technology(name);" ); try (Session session = driver.session()) { for (String index : indexes) { session.run(index); } } } //Create nodes and relationships public void createNodesAndRealationships() { List developerNodes = Arrays.asList( "CREATE (n:Developer {id: 1, name:'Andy'});", "CREATE (n:Developer {id: 2, name:'John'});", "CREATE (n:Developer {id: 3, name:'Michael'});" ); List technologyNodes = Arrays.asList( "CREATE (n:Technology {id: 1, name:'Memgraph', description: 'Fastest graph DB in the world!', createdAt: timestamp()}", "CREATE (n:Technology {id: 2, name:'Java', description: 'Java programming language ', createdAt: timestamp()})", "CREATE (n:Technology {id: 3, name:'Docker', description: 'Docker containerization engine', createdAt: timestamp()})", "CREATE (n:Technology {id: 4, name:'Kubernetes', description: 'Kubernetes container orchestration engine', createdAt: timestamp()})", "CREATE (n:Technology {id: 5, name:'Python', description: 'Python programming language', createdAt: timestamp()})" ); List relationships = Arrays.asList( "MATCH (a:Developer {id: 1}),(b:Technology {id: 1}) CREATE (a)-[r:LOVES]->(b);", "MATCH (a:Developer {id: 2}),(b:Technology {id: 3}) CREATE (a)-[r:LOVES]->(b);", "MATCH (a:Developer {id: 3}),(b:Technology {id: 1}) CREATE (a)-[r:LOVES]->(b);", "MATCH (a:Developer {id: 1}),(b:Technology {id: 5}) CREATE (a)-[r:LOVES]->(b);", "MATCH (a:Developer {id: 2}),(b:Technology {id: 2}) CREATE (a)-[r:LOVES]->(b);", "MATCH (a:Developer {id: 3}),(b:Technology {id: 4}) CREATE (a)-[r:LOVES]->(b);" ); try (Session session = driver.session()) { for (String node : developerNodes) { session.run(node); } for (String node : technologyNodes) { session.run(node); } for (String relationship : relationships) { session.run(relationship); } } } // Read nodes and return as Record list public List readNodes() { String query = "MATCH (n:Technology{name: 'Memgraph'}) RETURN n;"; try (Session session = driver.session()) { Result result = session.run(query); return result.list(); } } public static void main(String[] args) { try (var helloMemgraph = new HelloMemgraph("bolt://localhost:7687", "", "")){ // Create indexes helloMemgraph.createIndexes(); // Create nodes and relationships helloMemgraph.createNodesAndRealationships(); // Read nodes var result = helloMemgraph.readNodes(); // Process results for (Record node : result) { Node n = node.get("n").asNode(); System.out.println(n); // Node type System.out.println(n.asMap()); // Node properties System.out.println(n.id()); // Node internal ID System.out.println(n.labels()); // Node labels System.out.println(n.get("id").asLong()); // Node user defined id property System.out.println(n.get("name").asString()); // Node user defined name property System.out.println(n.get("description").asString()); // Node user defined description property } } } ``` -------------------------------- ### Manage Memgraph service using systemd Source: https://memgraph.com/docs/deployment/environments/linux Once Memgraph is installed, you can use `systemd` to manage the Memgraph service. Here is an example of how to start, stop, and restart the Memgraph service: ```bash sudo systemctl start memgraph sudo systemctl stop memgraph sudo systemctl restart memgraph sudo systemctl status memgraph ``` -------------------------------- ### Install the Memgraph package (Ubuntu 24.04 example) Source: https://memgraph.com/docs/getting-started/packaging-memgraph Example command to install the Memgraph package using apt on Ubuntu 24.04. ```bash sudo apt install ./output/memgraph__.deb ``` -------------------------------- ### Run the application Source: https://memgraph.com/docs/client-libraries/graphql Command to execute the application file. ```bash node index.js ``` -------------------------------- ### Minimal Working Example Source: https://memgraph.com/docs/client-libraries/java A minimal working example demonstrating connection, index creation, node and relationship creation, and data retrieval using the Memgraph Java driver. ```java /* * Copyright (c) 2016-2023 Memgraph Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.memgraph; import org.junit.jupiter.api.Test; import org.neo4j.driver.AuthTokens; import org.neo4j.driver.Config; import org.neo4j.driver.Driver; import org.neo4j.driver.GraphDatabase; import org.neo4j.driver.Record; import org.neo4j.driver.Result; import org.neo4j.driver.Session; import org.neo4j.driver.Transaction; import org.neo4j.driver.Values; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; public class MinimalWorkingExample { @Test public void minimalWorkingExample() throws Exception { // Connect to Memgraph // The driver is a heavy object. You should instantiate it once and make it available globally. // For example, in a singleton class or passed around. final Driver driver = GraphDatabase.driver("bolt://localhost:7687", AuthTokens.basic("memgraph", "memgraph"), Config.builder().withLogging(Config.Logging.none()).build()); // Use the driver to create a session // A session is a lightweight object and can be created as needed. try (Session session = driver.session()) { // Create indexes session.writeTransaction(tx -> { tx.run("CREATE INDEX ON :User(name)"); return null; }); // Create nodes and relationships session.writeTransaction(tx -> { tx.run("CREATE (a:User {name: $name1})", Values.parameters("name1", "Alice")); tx.run("CREATE (b:User {name: $name2})", Values.parameters("name2", "Bob")); tx.run("MATCH (a:User {name: $name1}), (b:User {name: $name2}) CREATE (a)-[:FRIENDS_WITH]->(b)", Values.parameters("name1", "Alice"), Values.parameters("name2", "Bob")); return null; }); // Read the data back Result result = session.run("MATCH (a:User)-[:FRIENDS_WITH]->(b:User) RETURN a.name AS a, b.name AS b"); Record record = result.single(); // Assertions assertEquals("Alice", record.get("a").asString()); assertEquals("Bob", record.get("b").asString()); // Close the driver driver.closeAsync(); driver.closeAsync().toCompletableFuture().get(10, TimeUnit.SECONDS); } } } ``` -------------------------------- ### Docker start command syntax Source: https://memgraph.com/docs/getting-started/first-steps-with-docker The general syntax for starting an existing Docker container. ```bash docker start ``` -------------------------------- ### Vertices __len__ Example Source: https://memgraph.com/docs/custom-query-modules/python/python-api Example of getting the number of vertices. ```python len(graph.vertices) ``` -------------------------------- ### Start a container Source: https://memgraph.com/docs/getting-started/first-steps-with-docker Start the container by ID or name. ```bash docker start # or docker start ``` -------------------------------- ### Run Memgraph Source: https://memgraph.com/docs/client-libraries/graphql Command to install and run Memgraph Platform on Windows. ```powershell iwr https://windows.memgraph.com | iex ``` -------------------------------- ### Running the application output Source: https://memgraph.com/docs/client-libraries/java Example output when the application is run successfully. ```text node<76> {name=Memgraph, createdAt=1693389566657284, description=Fastest graph DB in the world!, id=1} 76 [Technology] 1 Memgraph Fastest graph DB in the world! ``` -------------------------------- ### Example Relationship Output Source: https://memgraph.com/docs/client-libraries/javascript An example of the output when extracting specific relationship details. ```javascript Relationship type: USES Start node ID: End node ID: ``` -------------------------------- ### Memgraph C# Client Example Source: https://memgraph.com/docs/client-libraries/c-sharp An example demonstrating how to connect to Memgraph, create a node, set a property, and retrieve it using the C# client library. ```csharp using Neo4j.Driver; namespace MemgraphApp { public class Program : IDisposable { private readonly IDriver _driver; public Program(string uri, string user, string password) { _driver = GraphDatabase.Driver(uri, AuthTokens.Basic(user, password)); } public void PrintGreeting(string message) { using (var session = _driver.Session()) { var greeting = session.ExecuteWrite(tx => { var result = tx.Run("CREATE (n:FirstNode) " + "SET n.message = $message " + "RETURN 'Node ' + id(n) + ': ' + n.message", new { message }); return result.Single()[0].As(); }); Console.WriteLine(greeting); } } public void Dispose() { _driver?.Dispose(); } public static void Main() { using (var greeter = new Program("bolt://localhost:7687", "", "")) { greeter.PrintGreeting("Hello, World!"); } } } } ``` -------------------------------- ### init-file and init-data-file configuration flags Source: https://memgraph.com/docs/release-notes Example of configuring init-file and init-data-file for query execution on server startup. ```bash memgraph --init-file init.cypher --init-data-file init_data.cypher start ``` -------------------------------- ### Install Python client library Source: https://memgraph.com/docs/client-libraries/python Install the Python client library which requires Python >= 3.7, and can be installed with `pip`. ```bash pip install neo4j ``` -------------------------------- ### End-to-end Kerberos/LDAP Example Source: https://memgraph.com/docs/configuration/auth-module Example of starting Memgraph with Kerberos and LDAP authentication enabled. ```shell # Memgraph startup docker run -it -p 7687:7687 -p 7444:7444 \ -e MEMGRAPH_SSO_KERBEROS_KEYTAB=/etc/memgraph/memgraph.keytab \ -e MEMGRAPH_SSO_KERBEROS_SERVICE_PRINCIPAL=memgraph/dbhost.example.com@EXAMPLE.COM \ -e MEMGRAPH_SSO_KERBEROS_REALM=EXAMPLE.COM \ -e MEMGRAPH_SSO_KERBEROS_USERNAME_FIELD=name \ -e MEMGRAPH_SSO_KERBEROS_ROLE_MAPPING_MODE=ldap \ -e MEMGRAPH_SSO_KERBEROS_LDAP_URI=ldap://dc.example.com:389 \ -e MEMGRAPH_SSO_KERBEROS_LDAP_BASE_DN="DC=example,DC=com" \ -e MEMGRAPH_SSO_KERBEROS_ROLE_MAPPING="Memgraph Admins:memadmin; Memgraph Users:memuser" \ -v /etc/memgraph/memgraph.keytab:/etc/memgraph/memgraph.keytab:ro \ memgraph/memgraph \ --auth-module-mappings=kerberos ``` -------------------------------- ### Pinot as a single backend Source: https://memgraph.com/docs/memgraph-zero/memgql/quick-start Example of running Pinot as a single backend with a specified connection type and URL, using Cargo to build and run the bolt server. ```bash CONNECTION_TYPE=pinot PINOT_URL=http://localhost:8099 cargo run --bin bolt_server ``` -------------------------------- ### Create a work directory Source: https://memgraph.com/docs/client-libraries/graphql Creates a directory for the project and navigates into it. ```bash mkdir graphql-example cd graphql-example ``` -------------------------------- ### Get Vehicle Route Example Source: https://memgraph.com/docs/advanced-algorithms/available-algorithms/vrp Cypher query to get and visualize the vehicle route. ```Cypher MATCH (d:Depot) CALL vrp.route(d) YIELD from_vertex, to_vertex, vehicle_id CREATE (from_vertex)-[r:Route]->(to_vertex); MATCH (n)-[r:Route]->(m) RETURN n, r, m; ``` -------------------------------- ### Enable Memgraph to start on boot Source: https://memgraph.com/docs/getting-started/install-memgraph/centos Command to configure Memgraph to start automatically on system startup. ```bash systemctl enable memgraph ``` -------------------------------- ### Run Memgraph Source: https://memgraph.com/docs/client-libraries/graphql Command to install and run Memgraph Platform on Linux and macOS. ```bash curl https://install.memgraph.com | sh ``` -------------------------------- ### String operator example Source: https://memgraph.com/docs/querying/expressions Example of using the STARTS WITH string operator to filter nodes by name. ```cypher MATCH (p:Person) WHERE p.name STARTS WITH 'Joh' RETURN p.name; ``` -------------------------------- ### Explicit Transaction Example Source: https://memgraph.com/docs/client-libraries/nodejs An example of setting up an explicit transaction with a specified database. ```javascript let session = driver.session({ database: 'neo4j' }) let transaction = await session.beginTransaction() // await transaction.run('') // await transaction.run('') // ... await transaction.close() await session.close() ``` -------------------------------- ### Initialize the Node.js project Source: https://memgraph.com/docs/client-libraries/graphql Initializes a new Node.js project with ES6 modules. ```bash npm init es6 --yes ``` -------------------------------- ### Example GraphQL Query Result Source: https://memgraph.com/docs/client-libraries/graphql The expected result from the example GraphQL query. ```json { "data": { "users": [ { "name": "Alice", "posts": [ { "content": "Alice's first post!" }, { "content": "Another thought from Alice." } ] }, { "name": "Bob", "posts": [ { "content": "Bob's great idea." } ] } ] } } ``` -------------------------------- ### from() Usage Example Source: https://memgraph.com/docs/advanced-algorithms/available-algorithms/refactor This example demonstrates how to use the `from()` procedure to change the start node of a relationship. ```cypher MATCH (:Person {name: "Ivan"})-[rel:Friends]->(:Person {name: "Matija"}) MATCH (idora: Person {name:"Idora"}) CALL refactor.from(rel, idora) YIELD relationship RETURN relationship; ``` -------------------------------- ### Example: Copy configuration file from container Source: https://memgraph.com/docs/getting-started/first-steps-with-docker Example of copying the Memgraph configuration file from a container to the local directory. ```bash docker cp bb3de2634afe:/etc/memgraph/memgraph.conf memgraph.conf ``` -------------------------------- ### Minimal Working Example Source: https://memgraph.com/docs/client-libraries/go This Go code snippet demonstrates how to connect to Memgraph, create indexes, nodes, and relationships, and then read a node. ```go package main import ( "context" "fmt" "github.com/neo4j/neo4j-go-driver/v5/neo4j" ) func main() { dbUser := "" dbPassword := "" dbUri := "bolt://localhost:7687" // scheme://host(:port) (default port is 7687) driver, err := neo4j.NewDriverWithContext(dbUri, neo4j.BasicAuth(dbUser, dbPassword, "")) ctx := context.Background() defer driver.Close(ctx) err = driver.VerifyConnectivity(ctx) if err != nil { panic(err) } else { fmt.Println("Viola! Connected to Memgraph!") } //Create indexes on developer and technology nodes indexes := []string{ "CREATE INDEX ON :Developer(id);", "CREATE INDEX ON :Technology(id);", "CREATE INDEX ON :Developer(name);", "CREATE INDEX ON :Technology(name);", } //Create developer nodes developer_nodes := []string{ "CREATE (n:Developer {id: 1, name:'Andy'});", "CREATE (n:Developer {id: 2, name:'John'});", "CREATE (n:Developer {id: 3, name:'Michael'});", } //Create technology nodes technology_nodes := []string{ "CREATE (n:Technology {id: 1, name:'Memgraph', description: 'Fastest graph DB in the world!', createdAt: Date()})", "CREATE (n:Technology {id: 2, name:'Go', description: 'Go programming language ', createdAt: Date()})", "CREATE (n:Technology {id: 3, name:'Docker', description: 'Docker containerization engine', createdAt: Date()})", "CREATE (n:Technology {id: 4, name:'Kubernetes', description: 'Kubernetes container orchestration engine', createdAt: Date()})", "CREATE (n:Technology {id: 5, name:'Python', description: 'Python programming language', createdAt: Date()})", } //Create relationships between developers and technologies relationships := []string{ "MATCH (a:Developer {id: 1}),(b:Technology {id: 1}) CREATE (a)-[r:LOVES]->(b);", "MATCH (a:Developer {id: 2}),(b:Technology {id: 3}) CREATE (a)-[r:LOVES]->(b);", "MATCH (a:Developer {id: 3}),(b:Technology {id: 1}) CREATE (a)-[r:LOVES]->(b);", "MATCH (a:Developer {id: 1}),(b:Technology {id: 5}) CREATE (a)-[r:LOVES]->(b);", "MATCH (a:Developer {id: 2}),(b:Technology {id: 2}) CREATE (a)-[r:LOVES]->(b);", "MATCH (a:Developer {id: 3}),(b:Technology {id: 4}) CREATE (a)-[r:LOVES]->(b);", } //Create a simple session session := driver.NewSession(ctx, neo4j.SessionConfig{DatabaseName: ""}) defer session.Close(ctx) // Run index queries via implicit auto-commit transaction for _, index := range indexes { _, err = session.Run(ctx, index, nil) if err != nil { panic(err) } } fmt.Println("****** Indexes created *******") // Run developer node queries for _, node := range developer_nodes { _, err = neo4j.ExecuteQuery(ctx, driver, node, nil, neo4j.EagerResultTransformer, neo4j.ExecuteQueryWithDatabase("")) if err != nil { panic(err) } } fmt.Println("****** Developer nodes created *******") // Run technology node queries for _, node := range technology_nodes { _, err = neo4j.ExecuteQuery(ctx, driver, node, nil, neo4j.EagerResultTransformer, neo4j.ExecuteQueryWithDatabase("")) if err != nil { panic(err) } } fmt.Println("****** Technology nodes created *******") // Run relationship queries for _, rel := range relationships { _, err = neo4j.ExecuteQuery(ctx, driver, rel, nil, neo4j.EagerResultTransformer, neo4j.ExecuteQueryWithDatabase("")) if err != nil { panic(err) } } fmt.Println("****** Relationships created *******") // Read a node query := "MATCH (n:Technology{name: 'Memgraph'}) RETURN n;" result, err := neo4j.ExecuteQuery(ctx, driver, query, nil, neo4j.EagerResultTransformer, neo4j.ExecuteQueryWithDatabase("")) if err != nil { panic(err) } // Print the node results for _, node := range result.Records { fmt.Println(node.AsMap()["n"].(neo4j.Node)) // Node type fmt.Println(node.AsMap()["n"].(neo4j.Node).GetProperties()) fmt.Println(node.AsMap()["n"].(neo4j.Node).GetElementId()) fmt.Println(node.AsMap()["n"].(neo4j.Node).Labels) fmt.Println(node.AsMap()["n"].(neo4j.Node).Props["id"].(int64)) fmt.Println(node.AsMap()["n"].(neo4j.Node).Props["name"].(string)) fmt.Println(node.AsMap()["n"].(neo4j.Node).Props["description"].(string)) fmt.Println(node.AsMap()["n"].(neo4j.Node).Props["createdAt"].(neo4j.Date).Time()) } fmt.Println("****** End *******") ``` -------------------------------- ### Next function example Source: https://memgraph.com/docs/data-visualization/graph-style-script/built-in-elements Example demonstrating the Next function to get the next item from an iterator. ```gss Next(AsIterator(AsArray(3, 2, 1))) ``` -------------------------------- ### Run the setup script Source: https://memgraph.com/docs/advanced-algorithms/install-mage Commands to activate the toolchain and build MAGE. ```bash source /opt/toolchain-v7/activate python3 setup build ``` -------------------------------- ### Uniq function examples Source: https://memgraph.com/docs/data-visualization/graph-style-script/built-in-elements Examples demonstrating the Uniq function to get unique elements from an array. ```gss Uniq(AsArray(2,1,1,2,1,3,1)) ``` ```gss Uniq(AsArray("1", "1", 1, True, True, 1)) ``` -------------------------------- ### Start the container Source: https://memgraph.com/docs/configuration/configuration-settings Start the Docker container. ```docker docker start memgraph_container ``` -------------------------------- ### Coordinator Instance Environment Variables Source: https://memgraph.com/docs/clustering/high-availability/best-practices Example of environment variables for setting up a coordinator instance. ```bash export MEMGRAPH_COORDINATOR_PORT=10111 export MEMGRAPH_COORDINATOR_ID=1 export MEMGRAPH_BOLT_PORT=7687 export MEMGRAPH_NURAFT_LOG_FILE="" export MEMGRAPH_COORDINATOR_HOSTNAME="localhost" export MEMGRAPH_MANAGEMENT_PORT=12121 ``` -------------------------------- ### Install Dependencies Source: https://memgraph.com/docs/client-libraries/go Command to install Go dependencies using go mod tidy. ```bash go mod tidy ``` -------------------------------- ### Data Instance Environment Variables Source: https://memgraph.com/docs/clustering/high-availability/best-practices Example of environment variables for setting up a data instance. ```bash export MEMGRAPH_MANAGEMENT_PORT=13011 export MEMGRAPH_BOLT_PORT=7692 ``` -------------------------------- ### Managed Transaction Example Source: https://memgraph.com/docs/client-libraries/javascript An example demonstrating how to use `session.executeRead()` for a managed transaction to retrieve data. ```javascript try { let session, result // Create a session session = driver.session() // The `.executeRead()` method is the entry point into a transaction result = await session.executeRead(async tx => { // Use the method `Transaction.run()` to run queries return await tx.run( ` MATCH (p:Person) WHERE p.name = 'Alice' RETURN p.name as name ORDER BY name ` ) }) // Process the result records for(let record of result.records) { console.log(record.get('name')) } } finally { // Remember to close session when done session.close() } ``` -------------------------------- ### Restart the instance Source: https://memgraph.com/docs/configuration/configuration-settings Run the following command: ```bash docker restart ``` -------------------------------- ### Install JavaScript Driver Source: https://memgraph.com/docs/client-libraries/javascript Run the following _npm_ command to install the Neo4j JavaScript Driver. ```bash npm i neo4j-driver ``` -------------------------------- ### Start Memgraph explicitly Source: https://memgraph.com/docs/getting-started/install-memgraph/wsl If the Memgraph database instance is not running, you can start it explicitly using this command. ```bash sudo runuser -l memgraph -c '/usr/lib/memgraph/memgraph' ``` -------------------------------- ### Size function example Source: https://memgraph.com/docs/data-visualization/graph-style-script/built-in-elements Example of using the Size function to get the length of a node's property. ```GSS Size(Property(node, "name")) ``` -------------------------------- ### Run the script output Source: https://memgraph.com/docs/client-libraries/javascript After running your script with node `example.js`, you should receive the output in your terminal similar to this: ```bash Database cleared. Record created. Record matched. Label: Person Name: Alice Age: 22 ``` -------------------------------- ### date.format() Usage Example Source: https://memgraph.com/docs/advanced-algorithms/available-algorithms/date Example of using the date.format() procedure to get a string representation from a time value. ```cypher CALL date.format(74976, "h", "%Y/%m/%d %H:%M:%S %Z", "Mexico/BajaNorte") YIELD formatted RETURN formatted; ``` ```text +-------------------------------+ | formatted | +-------------------------------+ | "1978/07/21 17:00:00 PDT" | +-------------------------------+ ``` -------------------------------- ### Run the script Source: https://memgraph.com/docs/client-libraries/nodejs After running your script with `node example.js` and accessing the root URL `http://localhost:3000` in your web browser, you should receive the output in your terminal similar to this: ```bash Example app listening at http://localhost:3000 Node 1: Hello, World! ```