歡迎各路大神臨幸寒舍
以下節點标簽為people,friend,使用者自己也可以設定成其他标簽,查詢時需要用到标簽。這個标簽可以類比為關系資料庫中的表名
建立節點、關系
建立節點(小明):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
級次查詢(樹形周遊)
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnL3YDN2MjM0gjMx0iM5MzN0ITMxETNwkDM5EDMy0yM4QjMxETMvwVOwkTMwIzLcNDO0ITMxEzLcd2bsJ2Lc12bj5ycn9Gbi52YugTMwIzZtl2Lc9CX6MHc0RHaiojIsJye.png)
以根部為條件,查詢第二層的節點
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
本文連結:https://blog.csdn.net/free8666/article/details/52909523