《Web安全之机器学习入门》笔记:第十三章 13.2 有向图 hello world

本文阅读 1 分钟

本小节示例neo4j的应用。

windows安装 下载地址:

​​​​​​Neo4j Download Center - Neo4j Graph Data Platform

img

 

在安装成功后,会让修改密码,我直接将密码改为了7474。

neo4j的启动方法为neo4j.bat console

img

 

注意:auth中第二个参数为在第一步安装过程中配置的密码7474

from neo4j import GraphDatabase, basic_auth

driver = GraphDatabase.driver("bolt://localhost", auth=basic_auth("neo4j", "7474"))
session = driver.session()

微博关注关系如图所示:

img

代码如下

# Insert data
insert_query = '''
UNWIND {pairs} as pair
MERGE (p1:Person {name:pair[0]})
MERGE (p2:Person {name:pair[1]})
MERGE (p1)-[:KNOWS]-(p2);
'''

data = [["Jim","Mike"],["Jim","Billy"],["Anna","Jim"],
          ["Anna","Mike"],["Sally","Anna"],["Joe","Sally"],
          ["Joe","Bob"],["Bob","Sally"]]

session.run(insert_query, parameters={"pairs": data})

(1)查询1

# Friends of a friend

foaf_query = '''
MATCH (person:Person)-[:KNOWS]-(friend)-[:KNOWS]-(foaf)
WHERE person.name = {name}
  AND NOT (person)-[:KNOWS]-(foaf)
RETURN foaf.name AS name
'''

results = session.run(foaf_query, parameters={"name": "Joe"})
for record in results:
    print(record["name"])

运行结果

Anna

(2)查询2

# Common friends

common_friends_query = """
MATCH (user:Person)-[:KNOWS]-(friend)-[:KNOWS]-(foaf:Person)
WHERE user.name = {user} AND foaf.name = {foaf}
RETURN friend.name AS friend
"""

results = session.run(common_friends_query, parameters={"user": "Joe", "foaf": "Sally"})
for record in results:
    print(record["friend"])

运行结果

Bob

(3)查询3

# Connecting paths

connecting_paths_query = """
MATCH path = shortestPath((p1:Person)-[:KNOWS*..6]-(p2:Person))
WHERE p1.name = {name1} AND p2.name = {name2}
RETURN path
"""

results = session.run(connecting_paths_query, parameters={"name1": "Joe", "name2": "Billy"})
for record in results:
    print (record["path"])

运行结果

<Path start=<Node id=3 labels={'Person'} properties={'name': 'Joe'}> end=<Node id=6 labels={'Person'} properties={'name': 'Billy'}> size=4>

Neo4j的原始数据如下所示

img

 

Neo4j关联关系图如下所示

img

 

本文为互联网自动采集或经作者授权后发布,本文观点不代表立场,若侵权下架请联系我们删帖处理!文章出自:https://blog.csdn.net/mooyuan/article/details/122772376
-- 展开阅读全文 --
Web安全—逻辑越权漏洞(BAC)
« 上一篇 03-13
Redis底层数据结构--简单动态字符串
下一篇 » 04-10

发表评论

成为第一个评论的人

热门文章

标签TAG

最近回复