使用Python,C#和Java进行Neo4j连接
郝伟 2021/02/03

Python

neo4j驱动安装

在Python下安装:pip install py2neo
在Anaconda 下安装 : conda install -c anaconda neo4j-python-driver
注意:安装时需要管理员权限。

测试代码1

本方法使用neo4j官方提供的GraphDatabase实现。

#coding:utf-8
from neo4j import GraphDatabase

def create_nodes(tx, cql):
    ''' CQL语句执行函数, 其中 tx为默认执行器,CQL就是执行语句 '''
    return tx.run(cql)

print('Connecting 192.168.3.178:7687 ...')
driver=GraphDatabase.driver('bolt://192.168.3.178:7687', auth=('neo4j', '123456'))
print('Connected. \nBegin transctions...')
with driver.session() as session:
        cql = 'CREATE (n1:Person{id: "1", name: "Tom"}), (n1:Person{id: "2", name: "Jack"})' 
        session.write_transaction(create_nodes, cql)
print('Done.')

测试代码2

以下代码基于py2neo,操作也非常便利,更多用法可参考官方文档

#coding:utf-8
from py2neo import Graph,Node,Relationship
 
##连接neo4j数据库,输入地址、用户名、密码
graph = Graph("bolt://192.168.3.178:7687",username='neo4j',password='123456')
 
##创建结点
n1 = Node('皇室成员', name='皇帝')
n2 = Node('皇室成员', name='皇后')
n3 = Node('皇室成员', name='公主')
graph.create(n1)
graph.create(n2)
graph.create(n3)
 
##创建关系
#分别建立了n1指向n2和n2指向n1两条关系,关系的类型为"丈夫、妻子",两条关系都有属性count,且值为1。
husband = Relationship(n1,'丈夫',n2)
husband['count'] = 1

wife = Relationship(n2,'妻子',n1)
wife['count'] = 1

mother = Relationship(n2,'母女',n3)
 
graph.create(husband)
graph.create(wife)
graph.create(mother)

print(graph)
print(n1)
print(n2)
print(husband)
print(wife)
print(mother)

输出结果

Graph('bolt://neo4j@192.168.3.178:7687')
(_12680:皇室成员 {name: '\u7687\u5e1d'})
(_12663:皇室成员 {name: '\u7687\u540e'})
(皇帝)-[:丈夫 {count: 1}]->(皇后)
(皇后)-[:妻子 {count: 1}]->(皇帝)
(皇后)-[:母女 {}]->(公主)

其他推荐

还有一种工具叫 Pypher,能够以类似 Cypher 语法的方式进行操作,详见这里
简介:Pypher is a suite of lightweight Python objects that allow the user to express Cypher queries in pure Python.
Its main goals are to cover all of the Cypher use-cases through an interface that isn’t too far from Cypher and to be easily expandable for future updates to the query language.

Java Demo

源代码

package neo4j_demo1;

import org.neo4j.driver.AuthTokens;
import org.neo4j.driver.Driver;
import org.neo4j.driver.GraphDatabase;
import org.neo4j.driver.Result;
import org.neo4j.driver.Session;
import org.neo4j.driver.Transaction;
import org.neo4j.driver.TransactionWork;

import static org.neo4j.driver.Values.parameters;

public class HelloWorldExample implements AutoCloseable {
	private final Driver driver;

	public HelloWorldExample(String uri, String user, String password) {
		driver = GraphDatabase.driver(uri, AuthTokens.basic(user, password));
	}

	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 (HelloWorldExample greeter = new HelloWorldExample("bolt://192.168.3.178:7687", "neo4j", "123456")) {
			greeter.printGreeting("hello, world");
		}
	}
}

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.huaun.aikg</groupId>
  <artifactId>neo4j_demo1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
    <dependency>
      <groupId>org.neo4j.driver</groupId>
      <artifactId>neo4j-java-driver</artifactId>
      <version>4.0.1</version>
    </dependency>
  </dependencies>
</project>

运行结果

Feb 02, 2021 7:21:25 PM org.neo4j.driver.internal.logging.JULogger info
INFO: Direct driver instance 288994035 created for server address 192.168.3.178:7687
hello, world, from node 57
Feb 02, 2021 7:21:27 PM org.neo4j.driver.internal.logging.JULogger info
INFO: Closing driver instance 288994035
Feb 02, 2021 7:21:27 PM org.neo4j.driver.internal.logging.JULogger info
INFO: Closing connection pool towards 192.168.3.178:7687

C#Demo

源代码

连接代码

using Neo4j.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace New4j_HelloWorld
{

    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 void Main1()
        {

        }
    }
}

主程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace New4j_HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            //using (var greeter = new HelloWorldExample("bolt://192.168.3.178:7687", "neo4j", "123456"))
            //{
            //    greeter.PrintGreeting("hello, world");
            //}
		}
	}
}

显示结果

hello, world, from node 58
Press any key to continue . . .

参考资料