Knowledge map: [map database Neo4j] - Py2Neo

Introduction to Py2Neo

Py2Neo is a Python library used to interface with Neo4j

Connect to existing graph database

from py2neo import Graph

test_graph = Graph(
    "http://10.6.16.96:7474", 
    username="neo4j", 
    password="sl123456"
)

Node & relationship creation

from py2neo import Node, Relationship

a = Node('Person', name='Alice')
b = Node('Person', name='Bob')
r = Relationship(a, 'KNOWS', b)
print(a, b, r)

Attribute assignment

Method 1:

a['age'] = 20
b['age'] = 21
r['time'] = '2017/08/31'
print(a, b, r)

Method 2:

a.setdefault('location', 'Beijing')
print(a)

Method 3: batch update

data = {
    'name': 'Amy',
    'age': 21
}
a.update(data)
print(a)

Subgraph

A subgraph is a collection of nodes and relationships. The simplest way to construct a subgraph is through relational operators. Examples are as follows:

from py2neo import Node, Relationship

a = Node('Person', name='Alice')
b = Node('Person', name='Bob')
r = Relationship(a, 'KNOWS', b)
s = a | b | r
print(s)

All nodes and relationships can be obtained through the nodes () and relationships () methods

print(s.nodes())
print(s.relationships())

Walkable

Walkable is a Subgraph with traversal information added. We can build a walkable object by using the + sign, for example:

from py2neo import Node, Relationship

a = Node('Person', name='Alice')
b = Node('Person', name='Bob')
c = Node('Person', name='Mike')
ab = Relationship(a, "KNOWS", b)
ac = Relationship(a, "KNOWS", c)
w = ab + Relationship(b, "LIKES", c) + ac
print(w)

You can call the walk() method to realize traversal. The example is as follows:

from py2neo import walk
for item in walk(w):
    print(item)

You can see that it starts to traverse from node a, then to b, then to c, and finally back to a. You can also use start_node (),end_node(), nodes(), relationships() methods to obtain the starting node, terminating node, all nodes and relationships, for example:

print(w.start_node())
print(w.end_node())
print(w.nodes())
print(w.relationships())

Graph

The database module contains an API for data interaction with Neo4j. The most important is graph, which represents Neo4j's graph database. At the same time, graph also provides many methods to operate Neo4j database. Graph needs to pass in the connection URI during initialization. The initialization parameters include bolt, secure, host and http_port,https_port,bolt_port, user and password. For details, please refer to: http://py2neo.org/v3/database.html#py2neo.database.Graph . Examples of initialization are as follows:

from py2neo import Graph
graph_1 = Graph()
graph_2 = Graph(host="localhost")
graph_3 = Graph("http://localhost:7474/db/data/")

You can use the create () method to pass in the Subgraph object to add the diagram to the database. Examples are as follows:

from py2neo import Node, Relationship, Graph

a = Node('Person', name='Alice')
b = Node('Person', name='Bob')
r = Relationship(a, 'KNOWS', b)
s = a | b | r
graph = Graph(password='123456')
graph.create(s)

You can also add a single Node or Relationship separately. Examples are as follows:

from py2neo import Graph, Node, Relationship

graph = Graph(password='123456')
a = Node('Person', name='Alice')
graph.create(a)
b = Node('Person', name='Bob')
ab = Relationship(a, 'KNOWS', b)
graph.create(ab)

You can also use the data () method to obtain query results:

from py2neo import Graph

graph = Graph(password='123456')
data = graph.data('MATCH (p:Person) return p')
print(data)

You can use find_one () or find () methods can be used to find nodes. Match () or match () can be used_ The one () method looks up the Relationship:

from py2neo import Graph

graph = Graph(password='123456')
node = graph.find_one(label='Person')
print(node)
relationship = graph.match_one(rel_type='KNOWS')
print(relationship)

You can use the push () method to update an attribute of a Node, for example:

from py2neo import Graph, Node

graph = Graph(password='123456')
a = Node('Person', name='Alice')
node = graph.find_one(label='Person')
node['age'] = 21
graph.push(node)
print(graph.find_one(label='Person'))

Delete() method can be used to delete a Node (the corresponding Relationship must be deleted before deleting a Node, otherwise the Node cannot be deleted), for example:

from py2neo import Graph

graph = Graph(password='123456')
node = graph.find_one(label='Person')
relationship = graph.match_one(rel_type='KNOWS')
graph.delete(relationship)
graph.delete(node)

NodeSelector

Graph is sometimes inconvenient to use. For example, it is impossible to query nodes according to multiple conditions. A more convenient query method here is to use NodeSelector. First, we create the following nodes and relationships. Examples are as follows:

from py2neo import Graph, Node, Relationship

graph = Graph(password='123456')
a = Node('Person', name='Alice', age=21, location='Guangzhou')
b = Node('Person', name='Bob', age=22, location='Shanghai')
c = Node('Person', name='Mike', age=21, location='Beijing')
r1 = Relationship(a, 'KNOWS', b)
r2 = Relationship(b, 'KNOWS', c)
graph.create(a)
graph.create(r1)
graph.create(r2)

Use NodeSelector to filter person nodes with age 21. Examples are as follows:

from py2neo import Graph, NodeSelector

graph = Graph(password='123456')
selector = NodeSelector(graph)
persons = selector.select('Person', age=21)
print(list(persons))

You can also use where () for more complex queries, such as finding A Person Node whose name starts with A. the examples are as follows:

from py2neo import Graph, NodeSelector

graph = Graph(password='123456')
selector = NodeSelector(graph)
persons = selector.select('Person').where('_.name =~ "A.*"')
print(list(persons))

You can also use order_ Sort by():

from py2neo import Graph, NodeSelector

graph = Graph(password='123456')
selector = NodeSelector(graph)
persons = selector.select('Person').order_by('_.age')
print(list(persons))

The previous returns are lists. If you want to query a single node, you can use the first() method. The example is as follows:

from py2neo import Graph, NodeSelector

graph = Graph(password='123456')
selector = NodeSelector(graph)
person = selector.select('Person').where('_.name =~ "A.*"').first()
print(person)

OGM

OGM is similar to ORM, meaning Object Graph Mapping, which can realize the association between an object and a Node, for example:

from py2neo.ogm import GraphObject, Property, RelatedTo, RelatedFrom

class Movie(GraphObject):
    __primarykey__ = 'title'

    title = Property()
    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')

You can use it to combine Graph queries, for example:

from py2neo import Graph
from py2neo.ogm import GraphObject, Property

graph = Graph(password='123456')

class Person(GraphObject):
    __primarykey__ = 'name'

    name = Property()
    age = Property()
    location = Property()

person = Person.select(graph).where(age=21).first()
print(person)
print(person.name)
print(person.age)

It can be used to dynamically change the attributes of a Node, such as modifying the age attribute of a Node. Examples are as follows:

person = Person.select(graph).where(age=21).first()
print(person.__ogm__.node)
person.age = 22
print(person.__ogm__.node)
graph.push(person)

You can also adjust the Relationship through the mapping Relationship. For example, add an associated Node through the Relationship. The example is as follows:

from py2neo import Graph
from py2neo.ogm import GraphObject, Property, RelatedTo

graph = Graph(password='123456')

class Person(GraphObject):
    __primarykey__ = 'name'

    name = Property()
    age = Property()
    location = Property()
    knows = RelatedTo('Person', 'KNOWS')

person = Person.select(graph).where(age=21).first()
print(list(person.knows))
new_person = Person()
new_person.name = 'Durant'
new_person.age = 28
person.knows.add(new_person)
graph.push(person)
print(list(person.knows))

Remove an associated Node through the remove() method. The example is as follows:

person = Person.select(graph).where(name='Alice').first()
target = Person.select(graph).where(name='Durant').first()
person.knows.remove(target)
graph.push(person)
graph.delete(target)

Reference link

Official documents: https://py2neo.org/2021.1/#quick-example
Bowen 1: https://cuiqingcai.com/4778.html
Blog post 2: https://cloud.tencent.com/developer/article/1434904
GitHub: https://github.com/technige/py2neo

Tags: Python Database AI NLP

Posted on Sat, 23 Oct 2021 23:40:48 -0400 by rpanning