Neo4j使用简单例子(转)

Neo4j Versions

Most of the examples on this page are written with Neo4j 2.0 in mind, so they skip the START clause, and use clauses like MERGE. The focus of this page is about Cypher-to-C# syntax though, and should be equally useful in helping you translate a Neo4j 1.9 query to C#.

At the end of the day, you always need to start with a working Cypher query, then work out the equivalent C#.

Need more help?

If you have a working Cypher query, but can‘t translate it to C#, just post it on http://stackoverflow.com/questions/tagged/neo4jclient and we‘ll help you out pretty quickly.

Then, once we have the answer, we can add it to this page too so it helps other people.

User class

Most of the examples below assume you have the following class, to represent the structure of a user node:

public class User
{
    public long Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Email { get; set; }
}

Get all users by label

This Cypher:

MATCH (user:User)
RETURN user

Is this C#:

graphClient.Cypher
    .Match("(user:User)")
    .Return(user => user.As<User>())
    .Results

Get specific user

This Cypher:

MATCH (user:User)
WHERE user.Id = 1234
RETURN user

Is this C#:

graphClient.Cypher
    .Match("(user:User)")
    .Where((User user) => user.Id == 1234)
    .Return(user => user.As<User>())
    .Results

Get a user, and the count of their friends

This Cypher:

OPTIONAL MATCH (user:User)-[FRIENDS_WITH]-(friend:User)
WHERE user.Id = 1234
RETURN user, count(friend) AS NumberOfFriends

Is this C#:

graphClient.Cypher
    .OptionalMatch("(user:User)-[FRIENDS_WITH]-(friend:User)")
    .Where((User user) => user.Id == 1234)
    .Return((user, friend) => new {
        User = user.As<User>(),
        NumberOfFriends = friend.Count()
    })
    .Results

Get a user, and all their friends

This Cypher:

OPTIONAL MATCH (user:User)-[FRIENDS_WITH]-(friend:User)
WHERE user.Id = 1234
RETURN user, collect(friend) AS NumberOfFriends

Is this C#:

graphClient.Cypher
    .OptionalMatch("(user:User)-[FRIENDS_WITH]-(friend:User)")
    .Where((User user) => user.Id == 1234)
    .Return((user, friend) => new {
        User = user.As<User>(),
        Friends = friend.CollectAs<User>()
    })
    .Results

Create a user

This Cypher:

CREATE (user:User { Id: 456, Name: ‘Jim‘ })

Should use parameters:

CREATE (user:User {newUser})

And is this C#:

var newUser = new User { Id = 456, Name = "Jim" };
graphClient.Cypher
    .Create("(user:User {newUser})")
    .WithParam("newUser", newUser)
    .ExecuteWithoutResults();

Note that we‘re using an explicitly named parameter (newUser) and the query, and the WithParam method to supply it. This keeps our encoding safe, protects against Cypher-injection attacks, and improves performance by allowing query plans to be cached.

Create a user, only if they don‘t already exist

This Cypher:

MERGE (user:User { Id: 456 })
ON CREATE user
SET user.Name = ‘Jim‘

Should use parameters:

CREATE (user:User { Id: {id} })
ON CREATE user
SET user = {newUser}

And is this C#:

var newUser = new User { Id = 456, Name = "Jim" };
graphClient.Cypher
    .Merge("(user:User { Id: {id} })")
    .OnCreate()
    .Set("user = {newUser}")
    .WithParams(new {
        id = newUser.Id,
        newUser
    })
    .ExecuteWithoutResults();

Create a user and relate them to an existing one

This Cypher:

MATCH (invitee:User)
WHERE invitee.Id = 123
CREATE invitee-[:INVITED]->(invited:User {newUser})

Is this C#:

var newUser = new User { Id = 456, Name = "Jim" };
graphClient.Cypher
    .Match("(invitee:User)")
    .Where((User invitee) => invitee.Id == 123)
    .Create("invitee-[:INVITED]->(invited:User {newUser})")
    .WithParam("newUser", newUser)
    .ExecuteWithoutResults();

Relate two existing users

This Cypher:

MATCH (user1:User), (user2:User)
WHERE user1.Id = 123, user2.Id = 456
CREATE user1-[:FRIENDS_WITH]->user2

Is this C#:

graphClient.Cypher
    .Match("(user1:User)", "(user2:User)")
    .Where((User user1) => user1.Id == 123)
    .AndWhere((User user2) => user2.Id == 456)
    .Create("user1-[:FRIENDS_WITH]->user2")
    .ExecuteWithoutResults();

Relate two existing users, only if they aren‘t related already

This Cypher:

MATCH (user1:User), (user2:User)
WHERE user1.Id = 123, user2.Id = 456
CREATE UNIQUE user1-[:FRIENDS_WITH]->user2

Is this C#:

graphClient.Cypher
    .Match("(user1:User)", "(user2:User)")
    .Where((User user1) => user1.Id == 123)
    .AndWhere((User user2) => user2.Id == 456)
    .CreateUnique("user1-[:FRIENDS_WITH]->user2")
    .ExecuteWithoutResults();

Update a single property on a user

This Cypher:

MATCH (user:User)
WHERE user.Id = 123
SET user.Age = 25

Is this C#:

graphClient.Cypher
    .Match("(user:User)")
    .Where((User user) => user.Id == 123)
    .Set("user.Age = {age}")
    .WithParam("age", 25)
    .ExecuteWithoutResults();

Note: we‘re using parameters again to pass in data. Never do this via string concatenation like Set("user.Age = " + age.ToString()) otherwise you will introduce encoding bugs, security risks, and significantly impact your query performance by bypassing the query plan cache in Neo4j itself.

Replace all the properties on a user

This Cypher:

MATCH (user:User)
WHERE user.Id = 123
SET user = { Id: 123, Age: 25, Email: ‘[email protected]‘ }

Is this C#:

graphClient.Cypher
    .Match("(user:User)")
    .Where((User user) => user.Id == 123)
    .Set("user = {tatham}")
    .WithParam("tatham", new User { Id = 123, Age = 25, Email = "[email protected]" })
    .ExecuteWithoutResults();

Delete a user

This Cypher:

MATCH (user:User)
WHERE user.Id = 123
DELETE user

Is this C#:

graphClient.Cypher
    .Match("(user:User)")
    .Where((User user) => user.Id == 123)
    .Delete("user")
    .ExecuteWithoutResults();

Delete a user and all inbound relationships

This Cypher:

OPTIONAL MATCH (user:User)<-[r]-()
WHERE user.Id = 123
DELETE r, user

Is this C#:

graphClient.Cypher
    .OptionalMatch("(user:User)<-[r]-()")
    .Where((User user) => user.Id == 123)
    .Delete("r, user")
    .ExecuteWithoutResults();

Get all labels for a specific user

This Cypher:

MATCH (user:User)
WHERE user.Id = 1234
RETURN labels(user)

Is this C#:

graphClient.Cypher
    .Match("(user:User)")
    .Where((User user) => user.Id == 1234)
    .Return(user => user.Labels())
    .Results

Get all labels for a specific user, and still the user too

This Cypher:

MATCH (user:User)
WHERE user.Id = 1234
RETURN user, labels(user)

Is this C#:

graphClient.Cypher
    .Match("(user:User)")
    .Where((User user) => user.Id == 1234)
    .Return(user => new {
        User = user.As<User>(),
        Labels = user.Labels()
    })
    .Results

Get a user, count their friends then add this number to the user and return.

Note: This is an example of using Neo4j 3.0 Stored Procedures. There are other ways of adding a property to an object, this is just an example of CALL and YIELD, using apoc Neo4j Stored Procedures

This Cypher:

MATCH (user:User)
WHERE user.Id = 1234
WITH user, size((user)-[:IS_FRIENDS_WITH]->(:Friend)) as numberOfFriends
CALL apoc.map.setKey(user, ‘numberOfFriends‘, numberOfFriends) YIELD value AS userWithFriends
RETURN userWithFriends

Is this C#:

graphClient.Cypher
    .Match("(user:User)")
    .Where((User user) => user.Id == 1234)
    .With("user, size((user)-[:IS_FRIENDS_WITH]->(:Friend)) as numberOfFriends")
    .Call("apoc.map.setKey(user, ‘numberOfFriends‘, numberOfFriends)").Yield("value AS userWithFriends")
    .Return(userWithFriends => new {
        User = userWithFriends.As<User>()
    })
    .Results
时间: 2024-07-30 01:22:05

Neo4j使用简单例子(转)的相关文章

从一个简单例子来理解js引用类型指针的工作方式

? 1 2 3 4 5 6 7 <script> var a = {n:1};  var b = a;   a.x = a = {n:2};  console.log(a.x);// --> undefined  console.log(b.x);// --> [object Object]  </script> 上面的例子看似简单,但结果并不好了解,很容易把人们给想绕了--"a.x不是指向对象a了么?为啥log(a.x)是undefined?".&

Hadoop RPC简单例子

jdk中已经提供了一个RPC框架-RMI,但是该PRC框架过于重量级并且可控之处比较少,所以Hadoop RPC实现了自定义的PRC框架. 同其他RPC框架一样,Hadoop RPC分为四个部分: (1)序列化层:Clent与Server端通信传递的信息采用了Hadoop里提供的序列化类或自定义的Writable类型: (2)函数调用层:Hadoop RPC通过动态代理以及java反射实现函数调用: (3)网络传输层:Hadoop RPC采用了基于TCP/IP的socket机制: (4)服务器端

extern外部方法使用C#简单例子

外部方法使用C#简单例子 1.增加引用using System.Runtime.InteropServices; 2.声明和实现的连接[DllImport("kernel32", SetLastError = true)] 3.声明外部方法public static extern int GetCurrentDirectory(int a, StringBuilder b); 4.对外部方法操作  GetCurrentDirectory(300, pathstring); using

事件简单例子

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Runtime.InteropServices; 6 7 namespace EventTest 8 { 9 /// <summary> 10 /// 事件订阅者类 11 /// </summary> 12 class Program 13 { 14 static v

spring mvc(注解)上传文件的简单例子

spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype=”multipart/form-data” 这个是上传文件必须的2.applicationContext.xml中 <bean id=”multipartResolver” class=”org.springframework.web.multipart.commons.CommonsMultipartResolver”/> 关于文件上传的配置不能少 大家可以看具体代码如下: web.xml &

自定义隐式转换和显式转换c#简单例子

自定义隐式转换和显式转换c#简单例子 (出自朱朱家园http://blog.csdn.net/zhgl7688) 例子:对用户user中,用户名first name和last name进行转换成合成一个限定长度为10个字符新name. 自定义隐式转换: namespace transduction { public partial class transductionForm : Form { public transductionForm() { InitializeComponent();

使用fastjson转换json的简单例子

pom添加依赖: <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> 代码: package JsonTest.JsonTest; import java.util.ArrayList; import java.util.Hash

最简单例子图解JVM内存分配和回收

一.简介 JVM采用分代垃圾回收.在JVM的内存空间中把堆空间分为年老代和年轻代.将大量(据说是90%以上)创建了没多久就会消亡的对象存储在年轻代,而年老代中存放生命周期长久的实例对象.年轻代中又被分为Eden区(圣经中的伊甸园).和两个Survivor区.新的对象分配是首先放在Eden区,Survivor区作为Eden区和Old区的缓冲,在Survivor区的对象经历若干次收集仍然存活的,就会被转移到年老区. 简单讲,就是生命期短的对象放在一起,将少数生命期长的对象放在一起,分别采用不同的回收

BIP_Case_以RDF为数据源以RTF为模板的简单例子

一. 汇总    1. 建立rdf报表    2. 开发rtf模板    3. 建立可执行程式    4. 建立并发程式    5. 注册data defination    6. 注册template    7. 运行程式    8. 开发程式中间,需将输出模式修改为xml,产生xml文件,以做rtf开发准备原始数据 二.分步解析1. 建立rdf报表2. 开发rtf模板3. 建立可执行程式4. 建立并发程式5. 注册data defination6. 注册template7. 运行程式8. 开