ITPub博客

首页 > 数据库 > > py2neo基本操作(v4版本,亲测有效)

py2neo基本操作(v4版本,亲测有效)

作者:兔子爱喝奶茶 时间:2020-05-21 13:25:26 0 删除 编辑

原文地址:zhuanlan.zhihu.com/p/83

由于官网上虽然解释详细但是例子少,网上资料又庞杂且版本旧,所以我来总结一下。

相关文章:

远行人:python操作图数据库neo4j的两种方式​zhuanlan.zhihu.com图标

--------------------------------------------------------------------------

本文是用py2neo的v4版本。

官网:

The Py2neo v4 Handbook​py2neo.org

1、连接

from py2neo import Graph,Node,Relationship

test_graph = Graph(
    "http://localhost:7474", 
    username="neo4j", 
    password="111111"
)

2、增

# 建立节点
test_node_1 = Node("人",name = "小明")
test_node_2 = Node("人",name = "小红")
test_graph.create(test_node_1)
test_graph.create(test_node_2)

# 建立关系
node_1_call_node_2 = Relationship(test_node_1,'喜欢',test_node_2)
# node_1_call_node_2['count'] = 1
node_2_call_node_1 = Relationship(test_node_2,'讨厌',test_node_1)
# node_2_call_node_1['count'] = 2
test_graph.create(node_1_call_node_2)
test_graph.create(node_2_call_node_1)

3、删

test_node_3 = Node("人",name = "小刚")
test_graph.create(test_node_3)
test_graph.delete(test_node_3)
# # 全删
# test_graph.delete_all()

4、改

test_node_2['age'] = 20
test_graph.push(test_node_2)


test_node_2['age'] = 22
test_graph.push(test_node_2)


node_1_call_node_2['程度'] = '非常'
test_graph.push(node_1_call_node_2)

5、查

5.1、用CQL进行查询,返回的结果是list

data1 = test_graph.run('MATCH (a:人) RETURN a')
print(data1, type(data1))
# "[<Record a=(_214:人 {name: '\u5c0f\u660e'})>, <Record a=(_254:人 {age: 22, name: '\u5c0f\u7ea2'})>] <class 'list'>"
print(data1[0]['a']['name'])
# "小明"

5.2、查节点

print(pd.DataFrame(test_graph.nodes.match('人')))
#     age name
# 0   NaN   小明
# 1  22.0   小红
print(pd.DataFrame(test_graph.nodes.match('人', name='小红')))
#     age name
# 0  22.0   小红


5.3、查关系

print(list(test_graph.match(r_type="喜欢")))
# [(小明)-[:喜欢 {程度: '\u975e\u5e38'}]->(小红)]

print(list(test_graph.match(r_type="讨厌")))
# [(小红)-[:讨厌 {}]->(小明)]
 


暂时还没能找到怎么在python里生成知识图谱的图的形式,像上面的图片那样。上述图片是在neo4j desktop中截的屏。


谢谢观看,觉得有用请点赞!

——————————————————————————

2020-03-31 更新

(根据评论区的提问和回答,增加这部分。)

neo4j是否能直接读取文件,如 csv ?

答案是可以的。Cypher语言可以;而py2neo模块只能通过执行Cypher语言读取,而没有python函数或方法读取(至少我没找着)。

官网例子如下:

LOAD CSV WITH HEADERS FROM 'https://neo4j.com/docs/cypher-manual/4.0/csv/artists-with-headers.csv' AS line
CREATE (:Artist { name: line.Name, year: toInteger(line.Year)})
3.20. LOAD CSV - Chapter 3. Clauses​neo4j.com

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69918097/viewspace-3168578/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-26

  • 博文量
    1470
  • 访问量
    11217