Neo4J(Cypher 语句) 例子

本贴最后更新于 2247 天前,其中的信息可能已经东海扬尘

先建立节点标签,然后实现简单的查询,标签可以类比为关系数据库中的表名,可以参考 w3cschool 里。

创建节点、关系

创建节点(小明):create (n:people{name:'小明',age:'18',sex:'男'})  return  n;
创建节点(小红): create (n:people{name:'小红',age:'18',sex:'女'})  return  n;
创建关系(小明送礼物给小红):小明节点id为0,小红节点id为1
start a =node(0),b=node(1) create (a)-[n:gift]->(b)return n

属性查询

  • 查询 18 岁的人
Match (n: people) where n.age = 18 return n
  • 查询大于 18 岁的人
Match (n: people) where n.age > 18 return n
  • 查询大于等于 18 岁的人
Match (n: people) where n.age >= 18 return n
  • 查询不等于 18 岁的人
Match (n: people) where n.age <> 18 return n

关系查询

  • 正向查询
    查询小明送礼物给了哪些人,有两种写法:(以下例子类似)
1. Match (n:people)-[: gift]->(end:people) where n.name='小明'  return end
2. Match (n:people{name:'小明'})-[:gift]->(end:people) return end
  • 反向查询
    查询哪些人送了礼物给小明
Match (n:people{name:'小明'})<-[:gift]-(end:people) return end
  • 无方向查询
    查询和小明有礼物来往的人
Match (n:people{name:'小明'})-[:gift]-(end:people) return end

ID 查询

  • 在 neo4j 中,每一个节点,会自动有一个唯一 Id。
    查找 id 为 1 的节点,有两种方式:
1. Start  n = node(1)  return  n
2. Match  (n:people)  where  ID(n)=1  return  n 

级次查询(树形遍历)

  • 以根部为条件,查询第二层的节点:
Match (start:people{name:'小明'})-[:gift*2..2]->(end:people) return end
  • 以根部为条件,查询第一层和第二层的节点
Match (start:people{name:'小明'})-[:gift*1..2]->(end:people) return end
  • 以根部为条件,按级次查询出所有直接或间接获得过小明的礼物的人
Match (start:people{name:'小明'})-[:gift*]->(end:people) return end

Delete

  • 删除 2 个节点之间的关系:
Match (x:people{name:'小明'})-[r:gift]->(y:people{name:'小红'}) delete  r
  • 删除节点,会删除和该节点有关的所有关系:
Match (n:people{name:'小红'}) delete n

Count

  • (不按属性)查询标签(people)中一共有多少节点(人):
Match (n:people)  return  count(n)
  • (按属性)查询标签(people)中年龄为 18 岁的一共有多少节点(人):
    三种写法:
1. Match (n:people) where  n.age=18   return  count(n)
2. Match (n:people{age:'18'})  return  count(n)  
3. Match (n:people)  return  count(n.age=18)

Limit

  • 查询标签(people)中的 10 个节点(人):
Match (n:people)  return  n  limit  10

Distinct

  • 查询标签(people)中所有的不同的 age:
Match (n:people)   return  distinct(n.age)

Order by

  • 根据标签(people)中的 name 排序:
Match(n:people)   return  n  order by name    (默认升序)
Match(n:people)   return  n  order by name  asc   (升序)
Match(n:people)   return  n  order by name  desc  (降序)

Union all (Union)

  • 求并集,不去重(去重用 Union):
Match(n:people)  where  n.age=18  return n.name as name
Union all
Match(n:friend) where  n.age=18  return  n.name as name

In

  • 查询 id 为 0,5,8 的节点:
Match  (n)  where ID(n)  IN[0,5,8]  return  n 

Exists

  • 判断节点是否存在 name 这个属性:
Match  (n)  where  exists(n.name)  return  n 

With

  • 查询 name 以‘小’开头的节点:
Match  (n)   where  n.name  starts  with '小'  return  n 
  • 查询 name 以‘明’结尾的节点:
Match  (n)   where  n.name  ends   with '明'  return  n

Contains

  • 查询 name 中含有 ‘小’的节点:
Match  (n)  where  n.name  Contains  '小'  return  n 

清空

  • 清空所有关系节点:
match(n) optional match(n)-[r]-() delete n,r

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...