13-2-Graph-algorithm-demo.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. from neo4j import GraphDatabase, basic_auth
  2. # neo4j直接使用了沙盒 https://sandbox.neo4j.com/
  3. # pip install neo4j-driver
  4. # pip install JPype1
  5. def main():
  6. # 自行修改
  7. driver = GraphDatabase.driver(
  8. "bolt://x.x.x.x:7687",
  9. auth=basic_auth("neo4j", "transmitters-amusements-saturdays"))
  10. session = driver.session()
  11. # 插入数据
  12. # Insert data
  13. insert_query = '''
  14. UNWIND $pairs as pair
  15. MERGE (p1:Person {name:pair[0]})
  16. MERGE (p2:Person {name:pair[1]})
  17. MERGE (p1)-[:KNOWS]-(p2);
  18. '''
  19. data = [["Jim", "Mike"], ["Jim", "Billy"], ["Anna", "Jim"], ["Anna", "Mike"], ["Sally", "Anna"], ["Joe", "Sally"],
  20. ["Joe", "Bob"], ["Bob", "Sally"]]
  21. session.run(insert_query, parameters={"pairs": data})
  22. # 朋友的朋友
  23. foaf_query = '''
  24. MATCH (person:Person)-[:KNOWS]-(friend)-[:KNOWS]-(foaf)
  25. WHERE person.name = $name
  26. AND NOT (person)-[:KNOWS]-(foaf)
  27. RETURN foaf.name AS name
  28. '''
  29. results = session.run(foaf_query, parameters={"name": "Joe"})
  30. for record in results:
  31. print(record["name"])
  32. # 共同的朋友
  33. common_friends_query = """
  34. MATCH (user:Person)-[:KNOWS]-(friend)-[:KNOWS]-(foaf:Person)
  35. WHERE user.name = $user AND foaf.name = $foaf
  36. RETURN friend.name AS friend
  37. """
  38. results = session.run(common_friends_query, parameters={"user": "Joe", "foaf": "Sally"})
  39. for record in results:
  40. print(record["friend"])
  41. # 连接路径
  42. connecting_paths_query = """
  43. MATCH path = shortestPath((p1:Person)-[:KNOWS*..6]-(p2:Person))
  44. WHERE p1.name = $name1 AND p2.name = $name2
  45. RETURN path
  46. """
  47. results = session.run(connecting_paths_query, parameters={"name1": "Joe", "name2": "Billy"})
  48. for record in results:
  49. print(record["path"])
  50. session.close()
  51. if __name__ == "__main__":
  52. main()