Cypher SDK usage examples

Updated at:

GDB supports the OpenCypher query language and is compatible with the bolt protocol. This lets you access GDB with a Neo4j driver. The following sections provide examples of how to access GDB with common drivers.

Java

Prerequisites

  • Install JDK 1.8 or later.

  • Install Maven.

Code examples

  1. Create a project folder and navigate to it.

    mkdir cypher-java-example
    cd cypher-java-example
  2. Create a pom.xml file with the following content.

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.gdb.alibaba</groupId>
      <artifactId>GdbGremlinExample</artifactId>
      <packaging>jar</packaging>
      <version>1.0-SNAPSHOT</version>
      <name>GdbGremlinExample</name>
      <url>http://maven.apache.org</url>
      <dependencies>
        <dependency>
           <groupId>org.neo4j.driver</groupId>
           <artifactId>neo4j-java-driver</artifactId>
           <version>4.0.1</version>
        </dependency>
      </dependencies>
      <build>
         <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.0.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.3</version>
                <configuration>
                    <mainClass>com.example.gdb.HelloWorld</mainClass>
                    <complianceLevel>1.8</complianceLevel>
                </configuration>
            </plugin>
        </plugins>
      </build>
    </project>
  3. Create the source folder.

    mkdir -p src/main/java/com/example/gdb/
  4. Edit the `src/main/java/com/example/gdb/HelloWorld.java` file. Replace `GDB_HOST`, `GDB_PORT`, `GDB_USER`, and `GDB_PASSWORD` with the address, port, username, and password of your instance.

    package com.example.gdb;
    import org.neo4j.driver.AuthTokens;
    import org.neo4j.driver.Driver;
    import org.neo4j.driver.GraphDatabase;
    import org.neo4j.driver.Session;
    import org.neo4j.driver.Result;
    import org.neo4j.driver.Transaction;
    import org.neo4j.driver.TransactionWork;
    import static org.neo4j.driver.Values.parameters;
    public class HelloWorld implements AutoCloseable
    {
        private final Driver driver;
        public HelloWorld( String uri, String user, String password )
        {
            driver = GraphDatabase.driver( uri, AuthTokens.basic( user, password ) );
        }
        @Override
        public void close() throws Exception
        {
            driver.close();
        }
        public void printGreeting( final String message )
        {
            try ( Session session = driver.session() )
            {
                String greeting = session.writeTransaction( new TransactionWork<String>()
                {
                    @Override
                    public String execute( Transaction tx )
                    {
                        Result result = tx.run( "CREATE (a:Greeting) " +
                                                         "SET a.message = $message " +
                                                         "RETURN a.message + ', from node ' + id(a)",
                                parameters( "message", message ) );
                        return result.single().get( 0 ).asString();
                    }
                } );
                System.out.println( greeting );
            }
        }
        public static void main( String... args ) throws Exception
        {
            try ( HelloWorld greeter = new HelloWorld( "bolt://GDB_HOST:GDB_PORT", "GDB_USER", "GDB_PASSWORD" ) )
            {
                greeter.printGreeting( "hello" );
            }
        }
    }
  5. Compile and run the code.

    mvn compile exec:java

    The following output is returned:

    hello, from node 1000010

Python

Prerequisites

  • Install CPython 2.7 or 3.4 or later. Python 3 is recommended.

  • Install pip.

  • Install the Neo4j driver. If you have multiple versions of Python and pip installed, use `pip2` or `pip3` to install the driver for a specific version.

    pip install neo4j --user

Code examples

  1. Edit the `cypher-python-example.py` file with the following content. Replace `GDB_HOST`, `GDB_PORT`, `GDB_USER`, and `GDB_PASSWORD` with the address, port, username, and password of your instance.

    from neo4j import GraphDatabase
    class HelloWorldExample(object):
        def __init__(self, uri, user, password):
            self._driver = GraphDatabase.driver(uri,
                                                auth=(user, password),
                                                encrypted=False)
        def close(self):
            self._driver.close()
        def print_greeting(self, message):
            with self._driver.session() as session:
                greeting = session.write_transaction(
                    self._create_and_return_greeting, message)
                print(greeting)
        @staticmethod
        def _create_and_return_greeting(tx, message):
            result = tx.run(
                "CREATE (a:Greeting) "
                "SET a.message = $message "
                "RETURN a.message + ', from node ' + id(a)",
                message=message)
            return result.single()[0]
    e = HelloWorldExample('bolt://GDB_HOST:GDB_PORT', 'GDB_USER', 'GDB_PASSWORD')
    r = e.print_greeting('hello')
  2. You can compile and run the code.

    python cypher-python-example.py

    The following output is returned:

    hello, from node 1000003

Go

Prerequisites

  • Install Go 1.11 or later.

  • Install seabolt. The Neo4j Go driver depends on seabolt. Compile and install seabolt from the source code. The following example shows how to install seabolt on macOS. For other installation methods, see the seabolt GitHub homepage.

    # Install OpenSSL
    brew install openssl
    # Set the OPENSSL_ROOT_DIR environment variable
    export OPENSSL_ROOT_DIR=/usr/local/opt/openssl
    # Decompress the seabolt source package
    tar zxvf seabolt-1.7.4.tar.gz
    cd seabolt-1.7.4
    mkdir build && cd build
    cmake ..
    make install

Code examples

  1. Create and initialize the project folder.

    mkdir cypher-go-example
    cd cypher-go-example
    go mod init cypher-go-example
  2. Edit the `main.go` file with the following content. Replace `GDB_HOST`, `GDB_PORT`, `GDB_USER`, and `GDB_PASSWORD` with the address, port, username, and password of your instance.

    package main
    import (
        "fmt"
        "github.com/neo4j/neo4j-go-driver/neo4j"
    )
    func helloWorld(uri, username, password string) (string, error) {
        var (
            err      error
            driver   neo4j.Driver
            session  neo4j.Session
            result   neo4j.Result
            greeting interface{}
        )
        driver, err = neo4j.NewDriver(uri, neo4j.BasicAuth(username, password, ""))
        if err != nil {
            return "", err
        }
        defer driver.Close()
        session, err = driver.Session(neo4j.AccessModeWrite)
        if err != nil {
            return "", err
        }
        defer session.Close()
        greeting, err = session.WriteTransaction(func(transaction neo4j.Transaction) (interface{}, error) {
            result, err = transaction.Run(
                "CREATE (a:Greeting) SET a.message = $message RETURN a.message + ', from node ' + id(a)",
                map[string]interface{}{"message": "hello"})
            if err != nil {
                return nil, err
            }
            if result.Next() {
                return result.Record().GetByIndex(0), nil
            }
            return nil, result.Err()
        })
        if err != nil {
            return "", err
        }
        return greeting.(string), nil
    }
    func main() {
        greeting, err := helloWorld("bolt://GDB_HOST:GDB_PORT", "GDB_USER", "GDB_PORT")
        if err != nil {
            fmt.Println(err)
        }
        fmt.Println(string(greeting))
    }
  3. Compile and run the example. Go automatically downloads and installs the driver and adds the dependency to the `go.mod` file.

    go build ./.. && ./cypher-go-example
    # Or
    go run main.go

    The following output is returned:

    hello, from node 1000004

.NET

Prerequisite: Download and install .NET 2.0 or later.

Code examples

  1. Create a project and navigate to the project folder.

    dotnet new console -o cypher-dotnet-example
    cd cypher-dotnet-example
  2. Install Neo4j.Driver.

    dotnet add package Neo4j.Driver.Simple
  3. Edit the `Program.cs` file with the following content. Replace `GDB_HOST`, `GDB_PORT`, `GDB_USER`, and `GDB_PASSWORD` with the address, port, username, and password of your instance.

    using System;
    using System.Linq;
    using Neo4j.Driver;
    namespace cypherTest
    {
        public class HelloWorldExample : IDisposable
        {
            private readonly IDriver _driver;
            public HelloWorldExample(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.WriteTransaction(tx =>
                    {
                        var result = tx.Run("CREATE (a:Greeting) " +
                                            "SET a.message = $message " +
                                            "RETURN a.message + ', from node ' + id(a)",
                            new {message});
                        return result.Single()[0].As<string>();
                    });
                    Console.WriteLine(greeting);
                }
            }
            public void Dispose()
            {
                _driver?.Dispose();
            }
            public static void Main()
            {
                using (var greeter = new HelloWorldExample("bolt://GDB_HOST:GDB_PORT", "GDB_USER", "GDB_PASSWORD"))
                {
                    greeter.PrintGreeting("hello");
                }
            }
        }
    }
  4. Compile and run the code.

    dotnet run

    The following output is returned:

    hello, from node 1000007

Node.js

Prerequisite: Install Node.js. A Long-Term Support (LTS) version, such as 10.x or 12.x, is recommended.

Code examples

  1. Create a new project folder and navigate to it.

    mkdir cypher-js-example
    cd cypher-js-example
  2. Add the Neo4j driver.

    npm install neo4j-driver
  3. Edit the `demo.js` file with the following content. Replace `GDB_HOST`, `GDB_PORT`, `GDB_USER`, and `GDB_PASSWORD` with the address, port, username, and password of your instance.

    const neo4j = require("neo4j-driver");
    const driver = neo4j.driver('bolt://GDB_HOST:GDB_PORT',
                                neo4j.auth.basic('GDB_USER', 'GDB_PASSWORD'));
    async function helloWorld() {
      const session = driver.session();
      try {
        const result = await session.writeTransaction(
            tx => tx.run(
                'CREATE (a:Greeting) SET a.message = $message RETURN a.message + ", from node " + id(a)',
                {message : 'hello'}));
        const singleRecord = result.records[0];
        const greeting = singleRecord.get(0);
        return greeting;
      } finally {
        await session.close();
      }
    }
    helloWorld().then(msg => {
      console.log(msg);
      driver.close();
    });
  4. Compile and run.

    node demo.js

    The following output is returned:

    hello, from node 1000008