java连接neo4j测试
作者:互联网
java连接neo4j测试
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-neo4j</artifactId>
</dependency>
代码
public static void main(String[] args) {
Driver driver = GraphDatabase.driver("bolt://localhost:7687");
Session session = driver.session();
//这里注意 ,之前的版本字段注入是使用的{},现在新版本的使用的$
//创建一个person 节点 name=tom,address=北京
session.run("CREATE (n:person {name:$name,address: $address})",
parameters("name", "tom", "address", "北京"));
//创建一个person 节点 name=night,address=四川
session.run("CREATE (n:person {name:$name,address: $address})",
parameters("name", "night", "address", "四川"));
//查询person节点的name字段为night的节点
Result result = session.run( "MATCH (a:person) WHERE a.name = $name " +
"RETURN a.name AS name, a.address AS address",
parameters( "name", "night"));
while (result.hasNext()) {
Record record = result.next();
System.out.println( record.get( "address" ).asString() + "" + record.get( "name" ).asString() );
}
//为night到tom节点建立一个属性relation=邻居的关系
session.run(" match (n:person{name:$name1}),(q:person{name:$name}) create (n) -[l:link{relation:$relation}] ->(q)",
parameters("name1", "night", "name", "tom", "relation", "邻居"));
session.close();
driver.close();
}
注意点
这里有个注意点:两个person节点都通过name属性节点来关联的,使用占位符的时候注意使用不同名称的占位符,否则相同的情况下,前一个name的值会被后来的name值覆盖
底层源码的解析方式:将parameters入参拆分为一对key-value,前面是key,后面是value,相同的key的值会被覆盖
public static Value parameters(Object... keysAndValues) {
if (keysAndValues.length % 2 != 0) {
throw new ClientException("Parameters function requires an even number of arguments, alternating key and value. Arguments were: " + Arrays.toString(keysAndValues) + ".");
} else {
HashMap<String, Value> map = Iterables.newHashMapWithSize(keysAndValues.length / 2);
for(int i = 0; i < keysAndValues.length; i += 2) {
Object value = keysAndValues[i + 1];
Extract.assertParameter(value);
map.put(keysAndValues[i].toString(), value(value));
}
return value((Object)map);
}
}
标签:java,name,keysAndValues,value,person,session,测试,address,neo4j 来源: https://www.cnblogs.com/tulip-night/p/16427896.html