py2neo常见用法
from py2neo import Graph, Node, Relationship, cyper
graph = Graph(url, username=name, password=pwd)
# 匹配节点
len(graph.nodes.match("Person", age=33))
# 筛选出部分属性
graph.run("MATCH (a:Person) RETURN a.name, a.born LIMIT 4").data()
# 筛选出部分属性并转化为dataframe
graph.run("MATCH (a:Person) RETURN a.name, a.born LIMIT 4").to_data_frame()
# 根据属性筛选出节点
g.run("MATCH (a) WHERE a.email={x} RETURN a.name", x="bob@acme.com").evaluate()
from py2neo import Graph, NodeMatcher
graph = Graph()
matcher = NodeMatcher(graph)
# 匹配首个符合条件的节点
matcher.match("Person", name="Keanu Reeves").first()
# 匹配符合条件的节点,并排序, 并返回指定数量
list(matcher.match("Person").where("_.name =~ 'K.*'").order_by("_.name").limit(3))
# [(_224:Person {born: 1964, name: 'Keanu Reeves'}),
# (_57:Person {born: 1957, name: 'Kelly McGillis'}),
# (_83:Person {born: 1962, name: 'Kelly Preston'})]
from py2neo.cypher import cypher_escape
# 输出cypher语句
"MATCH (a:{label}) RETURN id(a)".format(label=cypher_escape("Employee of the Month"))
# 'MATCH (a:`Employee of the Month`) RETURN id(a)'
# 输出有多个筛选条件的cyper语句
cp1 = "MATCH (s:Person) where s.phone={numb} and s.other={othnum} return s".format(numb=cypher.cypher_escape(p1), othnum=cypher.cypher_repr(oth))
g.run(cp1)
# 输出全部路径中的节点
cp1 = "MATCH ((s:Person) -[*..3]- (t:Person)) where s.phone={nump1} and t.phone={nump2} return s.format(nump1=cypher.cypher_repr(p1), nump2=cypher.cypher_repr(p2))
g.run(cp1)
neo4j-cypher语法
/* 根据id查询多个节点 */
MATCH (n)
WHERE id(n) IN [0, 3, 5]
RETURN n
/* 结果:
Node[0]{name:"Charlie Sheen"}
Node[3]{name:"Oliver Stone"}
Node[5]{title:"Wall Street"}
*/
/* 查询所有的最短路径 */
MATCH (martin:Person { name: 'Martin Sheen' }),(michael:Person { name: 'Michael Douglas' }), p = allShortestPaths((martin)-[*]-(michael))
RETURN p
/*结果:
(1)-[ACTED_IN,1]->(5)<-[ACTED_IN,2]-(2)
(1)-[ACTED_IN,4]->(6)<-[ACTED_IN,5]-(2)
*/
/* 条件查询 */
MATCH (a)-[r]-(b)
WHERE id(r)= 0
RETURN a,b
/* 去重 */
MATCH (a { name: 'A' })-->(b)
RETURN DISTINCT b
/* 返回所有值 */
MATCH p =(a { name: 'A' })-[r]->(b)
RETURN *
/* 排序和限制返回数量 */
MATCH (n { name: 'Anders' })--(m)
WITH m
ORDER BY m.name DESC LIMIT 1
MATCH (m)--(o)
RETURN o.name
/* list展开为多行 */
WITH [1, 2] AS a,[3, 4] AS b
UNWIND (a + b) AS x
RETURN x
/* 解析到List */
MATCH p =(a)-->(b)-->(c)
WHERE a.name = 'Alice' AND b.name = 'Bob' AND c.name = 'Daniel'
RETURN extract(n IN nodes(p)| n.age) AS extracted
/* 统计边的数量 */
MATCH p=()-[r:renren]->() RETURN count(p)
MATCH p=()-->() RETURN count(p)
/* 统计点的数量 */
match (a:Person) return count(a)
参考文献