前面三篇文章分別介紹Neo4j的安裝、導入RDF數據、Cypher查詢語言,Neo4j是基於Java開發的圖資料庫,有非常友好的Java API,當然現在也已經支持python操作使用。本文主要介紹python中適配Neo4j的庫py2neo的關於節點、關係、子圖基本內容。
1. py2neo的安裝
pip install py2ne
或
pip install git+https://github.com/nigelsmall/py2neo.git#egg=py2neo
2. Node、Relationships、Properties
>>> from py2neo import Node, Relationship
>>> a = Node("Person", name="Alice")
>>> b = Node("Person", name="Bob")
>>> ab = Relationship(a, "KNOWS", b)
>>> ab
(alice)-[:KNOWS]->(bob)
新建兩個節點a、b,分別具有一個name屬性值,還新建a與b之間有向關係ab,ab的label為KNOWS。
class Node(*labels, **properties) 新建node可以指定label和屬性
hash(node) 返回node的ID的哈希值
node[key] 返回node的屬性值,沒有此屬性就返回None
node[key] = value 設定node的屬性值
del node[key] 刪除屬性值,如果不存在此屬性報KeyError
len(node) 返回node屬性的數量
dict(node) 返回node所有的屬性
walk(node) 返回一個生成器且只包含一個node
labels() 返回node的標籤的集合
has_label(label) node是否有這個標籤
add_label(label) 給node添加標籤
remove_label(label) 刪除node的標籤
clear_labels() 清楚node的所有標籤
update_labels(labels) 添加多個標籤,注labels為可迭代的
class Relationship(start_node, type, end_node, **properties)
class Relationship(start_node, end_node, **properties)
class Relationship(node, type, **properties)
class Relationship(node, **properties)
新建關係可以指定起止node,type或屬性值
>>> c = Node("Person", name="Carol")
>>> class WorksWith(Relationship): pass
>>> ac = WorksWith(a, c)
>>> ac.type()
'WORKS_WITH'
hash(relationship) 返回一個關係的hash值
relationship[key] 返回關係的屬性值
relationship[key] = value 設定關係的屬性值
del relationship[key] 刪除關係的屬性值
len(relationship) 返回關係的屬性值數目
dict(relationship) 以字典的形式返回關係的所有屬性
walk(relationship) 返回一個生成器包含起始node、關係本身、終止node
type() 返回關係type
class PropertyDict(iterable, **kwargs) 新建屬性字典類
properties[key] 返回屬性值
properties[key] = value 設定屬性值
setdefault(key, default=None) 如果這個屬性不存在,則插入新屬性並設置默認值,存在的話就返回屬性值。
update(iterable=None, **kwargs) 更新屬性值
3. Subgraphs
子圖是節點與關係的集合
>>> s = ab | ac
>>> s
{(alice:Person {name:"Alice"}),
(bob:Person {name:"Bob"}),
(carol:Person {name:"Carol"}),
(alice)-[:KNOWS]->(bob),
(alice)-[:WORKS_WITH]->(carol)}
>>> s.nodes()
frozenset({(alice:Person {name:"Alice"}),
(bob:Person {name:"Bob"}),
(carol:Person {name:"Carol"})})
>>> s.relationships()
frozenset({(alice)-[:KNOWS]->(bob),
(alice)-[:WORKS_WITH]->(carol)})
class Subgraph(nodes, relationships) 子圖是節點與關係不可變的集合
subgraph | other | ... 子圖的並
subgraph & other & ... 子圖的交
subgraph - other - ... 子圖的差
subgraph ^ other ^ ... 子圖對稱差
subgraph.keys() 返回子圖節點和關系所有屬性的集合
subgraph.labels() 返回節點label的集合
subgraph.nodes() 返回所有節點的集合
subgraph.relationships() 返回所有關係的集合
subgraph.types() 返回所有關係的type的集合
order(subgraph) 返回子圖節點的數目
size(subgraph) 返回子圖關係的數目
4. Walkable
>>> w = ab + Relationship(b, "LIKES", c) + ac
>>> w
(alice)-[:KNOWS]->(bob)-[:LIKES]->(carol)<-[:WORKS_WITH]-(alice)
class Walkable(iterable) 子圖帶著可遍歷的信息
walkable + other + ... 串聯walkable
walk(walkable) 轉為一個生成器包含節點和關係
start_node() 返回walk()的起始節點
end_node() 返回walk()的最後節點
nodes() 返回walk()所有節點的元組
relationships() 返回walk()所有關係的元組
參考:http://py2neo.org/v3/index.html