網路式資料庫應用 (neo4j)

應用場景

(1) 建立一個新網路式資料庫
(2) 建立節點及其屬性
(3) 建立節點間關係及其屬性
(4) 搜尋相關節點資料
(5) 刪除節點及其關係
(6) 關閉資料庫

程式碼

# -*- coding: utf-8 -*-

from neo4j import GraphDatabase
 
# Create a database
db = GraphDatabase("/home/richclee/Neo4J")
 
# All write operations happen in a transaction
with db.transaction:
    rootNode = db.node(name='Alice', age=38)
    node2 = db.node(name='Bob', age=56)
    node3 = db.node(name='Jack', age=45)
 
    # Create a relationship with type 'knows'
    nodeR2 = rootNode.relationships.create('Knows', node2, name='R2', strong=20)
    nodeR3 = rootNode.relationships.create('Knows', node3, name='R3', strong=14)
 
traverser = db.traversal() \
    .relationships('Knows') \
    .traverse(rootNode)
 
for relationship in traverser.relationships:
    startNode = relationship.getStartNode()
    endNode = relationship.getEndNode()
    
    message = "%s:%d %s:%d %s:%d" % ( \
                        startNode['name'], startNode['age'], \
                        relationship['name'],  relationship['strong'], \
                        endNode['name'], endNode['age'])
    print message
    pass

# Delete the data
with db.transaction:
    nodeR2.delete()
    nodeR3.delete()
    
    rootNode.delete()
    node2.delete()
    node3.delete()
 
# Always shut down your database when your application exits
db.shutdown()

結果輸出

Alice:38 Knows:20 Bob:56
Alice:38 Knows:14 Jack:45
ċ
neo4j-app.py
(1k)
李智,
2013年12月23日 下午6:55