[Neo4j系列六]Neo4j的python操作库py2neo之三

neo4j 1年前 ⋅ 1385 阅读

       有关py2neo的第一篇文章介绍了py2neo中节点、关系、子图等,第二篇文章介绍了Graph、事务、嵌入Cypher语句以及NodeSelector等内容,本文将介绍python.ogm Object-Graph Mapping即对象与图的映射。

 

图片

 

1.Graph Objects

class py2neo.ogm.GraphObject   图对象

__primarylabel__主节点标签,用作Cypher的match和merge

__primarykey__主属性键,用作Cypher的match和merge,默认是__id__

__primaryvalue__主属性键值

classmethodGraphObject.select(graph,primary_value=None)查找节点的类方法,返回的为GraphObjectSelection,可用list()获得内容

from py2neo.ogm import GraphObject,Property

from py2neo import Graph

graph = Graph()

class Person(GraphObject):

    __prinarykey__ = "name"

 

    name = Property()

 

data = Person.select(graph, "Keanu Reeves")

print(list(data))

运行结果:

[<Person name='Keanu Reeves'>]

注意:类名要与neo4j中的标签名一致,这个类才能有效

2.Properties

class py2neo.ogm.Property(key=None) 属性类

 

3.Labels

class py2neo.ogm.Label(name=None) 标签类

 

4. Related Objects

class py2neo.ogm.Related(related_class, relationship_type=None)

与对象相关的对象集合(无方向)

class py2neo.ogm.RelatedTo(related_class, relationship_type=None)

与对象相关的对象集合(指出)

class py2neo.ogm.RelatedFrom(related_class, relationship_type=None)

与对象相关的对象集合(指入)

class py2neo.ogm.RelatedObjects(node, direction, relationship_type, related_class)

与node相关的对象集合

 

有关方法:

add(obj, properties=None, **kwproperties)增加相关对象

clear()  清除所有相关对象

get(obj, key, default=None)

remove(obj)删除一个相关对象

update(obj, properties=None, **kwproperties)增加或更新相关对象

 

 

class Movie(GraphObject):

    __primarykey__ = "title"

 

    title = Property()

    tag_line = Property("tagline")

    released = Property()

 

    actors = RelatedFrom("Person", "ACTED_IN")

    directors = RelatedFrom("Person", "DIRECTED")

    producers = RelatedFrom("Person", "PRODUCED")

 

 

class Person(GraphObject):

    __primarykey__ = "name"

 

    name = Property()

    born = Property()

 

    acted_in = RelatedTo(Movie)

    directed = RelatedTo(Movie)

    produced = RelatedTo(Movie)

 

5.Object Selection

class py2neo.ogm.GraphObjectSelection(graph, labels=frozenset(), conditions=(), order_by=(), skip=None, limit=None)

first()第一条结果

data=Person.select(graph, "Keanu Reeves").first()

print(data)

运行结果:

<Person name='Keanu Reeves'>

 

__iter__()返回查找到结果的生成器

datas=Person.select(graph).where("_.name =~ 'K.*'")

for data in datas.__iter__():

    print(data)

运行结果:

<Person name='Keanu Reeves'>

<Person name='Kevin Bacon'>

<Person name='Kiefer Sutherland'>

<Person name='Kevin Pollak'>

<Person name='Kelly McGillis'>

<Person name='Kelly Preston'>

 

6.Object Operations

Graph.pull(graph_object)获取

Graph.push(graph_object)更新

Graph.create(graph_object)创建

Graph.merge(graph_object)合并

Graph.delete(graph_object)删除

 

alice = Person()

alice.name = "Alice Smith"

graph.push(alice)

print(alice.__ogm__.node)

运行结果:

(cc3030a:Person {name:"Alice Smith"})

 

参考http://py2neo.org/v3/index.html

 

更多内容请访问:IT源点

相关文章推荐

全部评论: 0

    我有话说: