GDB支持OpenCypher查詢語言,并兼容bolt協議,可以通過Neo4j driver進行訪問。以下為各種常用driver訪問GDB的示例。
Java
環境準備
安裝JDK 1.8以上版本。
安裝maven。
代碼示例
創建并進入項目目錄。
mkdir cypher-java-example cd cypher-java-example
創建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>
創建源碼目錄。
mkdir -p src/main/java/com/example/gdb/
編輯文件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" ); } } }
編譯運行。
mvn compile exec:java
實例運行結果如下:
hello, from node 1000010
Python
環境準備
安裝CPython 2.7或3.4以上,建議Python3。
安裝neo4j driver。如果同時安裝了多個版本的python和pip,需要用pip2或者pip3為指定版本安裝。
pip install neo4j --user
代碼示例
編輯文件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')
編譯運行。
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
代碼示例
創建和初始化項目目錄。
mkdir cypher-go-example cd cypher-go-example go mod init cypher-go-example
編輯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)) }
編譯并運行示例,go會自動下載安裝driver并添加依賴關系到go.mod文件中。
go build ./.. && ./cypher-go-example # 或者 go run main.go
示例運行結果如下:
hello, from node 1000004
.Net
環境準備:下載安裝.net,版本2.0以上。
代碼示例
創建項目,并進入項目目錄。
dotnet new console -o cypher-dotnet-example cd cypher-dotnet-example
安裝Neo4j.Driver。
dotnet add package Neo4j.Driver.Simple
編輯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"); } } } }
編譯運行。
dotnet run
實例運行結果如下:
hello, from node 1000007
Node.js
環境準備:安裝Node.js,建議使用LTS版本(10.x、12.x)。
代碼示例
新建并進入項目目錄。
mkdir cypher-js-example cd cypher-js-example
添加Neo4j driver。
npm install neo4j-driver
編輯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(); });
編譯運行。
node demo.js
實例運行結果如下:
hello, from node 1000008