Cypher SDK用法示例

GDB支持OpenCypher查询语言,并兼容bolt协议,可以通过Neo4j driver进行访问。以下为各种常用driver访问GDB的示例。

Java

环境准备

  • 安装JDK 1.8以上版本。

  • 安装maven。

代码示例

  1. 创建并进入项目目录。

    mkdir cypher-java-example
    cd cypher-java-example
  2. 创建pom.xml文件,内容如下。

    <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. 创建源码目录。

    mkdir -p src/main/java/com/example/gdb/
  4. 编辑文件src/main/java/com/example/gdb/HelloWorld.java。其中GDB_HOST、GDB_PORT、GDB_USER、GDB_PASSWORD分别替换成对应实例的地址、端口、用户名和密码。

    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. 编译运行。

    mvn compile exec:java

    实例运行结果如下:

    hello, from node 1000010

Python

环境准备

  • 安装CPython 2.7或3.4以上,建议Python3。

  • 安装pip

  • 安装neo4j driver。如果同时安装了多个版本的python和pip,需要用pip2或者pip3为指定版本安装。

    pip install neo4j --user

代码示例

  1. 编辑文件cypher-python-example.py,内容如下。其中GDB_HOST、GDB_PORT、GDB_USER、GDB_PASSWORD分别替换成对应实例的地址、端口、用户名和密码。

    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. 编译运行。

    python cypher-python-example.py

    运行结果如下:

    hello, from node 1000003

Go

环境准备

  • 安装go 1.11以上。

  • 安装seabolt。Neo4j go driver依赖于seabolt,推荐从源码编译安装。安装方法以Mac OS为例,其他安装方法参考seabolt的Github主页

    # 安装openssl
    brew install openssl
    # 设置环境变量OPENSSL_ROOT_DIR
    export OPENSSL_ROOT_DIR=/usr/local/opt/openssl
    # 解压seabolt源码包
    tar zxvf seabolt-1.7.4.tar.gz
    cd seabolt-1.7.4
    mkdir build && cd build
    cmake ..
    make install

代码示例

  1. 创建和初始化项目目录。

    mkdir cypher-go-example
    cd cypher-go-example
    go mod init cypher-go-example
  2. 编辑main.go文件,内容如下。其中GDB_HOST、GDB_PORT、GDB_USER、GDB_PASSWORD分别替换成对应实例的地址、端口、用户名和密码。

    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. 编译并运行示例,go会自动下载安装driver并添加依赖关系到go.mod文件中。

    go build ./.. && ./cypher-go-example
    # 或者
    go run main.go

    示例运行结果如下:

    hello, from node 1000004

.Net

环境准备:下载安装.net,版本2.0以上。

代码示例

  1. 创建项目,并进入项目目录。

    dotnet new console -o cypher-dotnet-example
    cd cypher-dotnet-example
  2. 安装Neo4j.Driver。

    dotnet add package Neo4j.Driver.Simple
  3. 编辑Program.cs,内容如下。其中GDB_HOST、GDB_PORT、GDB_USER、GDB_PASSWORD分别替换成对应实例的地址、端口、用户名和密码。

    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. 编译运行。

    dotnet run

    实例运行结果如下:

    hello, from node 1000007

Node.js

环境准备:安装Node.js,建议使用LTS版本(10.x、12.x)。

代码示例

  1. 新建并进入项目目录。

    mkdir cypher-js-example
    cd cypher-js-example
  2. 添加Neo4j driver。

    npm install neo4j-driver
  3. 编辑demo.js,内容如下。其中GDB_HOST、GDB_PORT、GDB_USER、GDB_PASSWORD分别替换成对应实例的地址、端口、用户名和密码。

    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. 编译运行。

    node demo.js

    实例运行结果如下:

    hello, from node 1000008