neo4j 通过连接mysql 动态取数据图形展示 python
程序分二个部分:
1.创建节点,会先判断节点是否存在,存在则打印“already exists 1” 或 “already exists 2”,不存在则创建。
如:
nginx访问后端tomcat ,数据库填写如下信息:
192.168.1.1 nginx access 192.168.1.2 tomcat
2.创建关系,会按行扫描mysql
node_1 = Relationship(node1, ‘node’, node2)
3.python 运行时会先删除所有数据重新来过
4.做crontab 后,可以修改数据库后自动图形展示
# coding:utf-8
from py2neo import Graph, Node, Relationship,NodeMatcher
import MySQLdb
def createnode():
sql = "select * from `neo4j` ;"
cursor.execute(sql)
results = cursor.fetchall()
#py2neo 4.3.0 version
#graph = Graph('http://192.168.6.245:7474', username='neo4j', password='passwd')
#py2neo 2021.1 version
graph = Graph('http://192.168.1.245:7474', auth=('neo4j', 'passwd'))
graph.delete_all()
for row in results:
id,monitor,ip,product,relationship,ip1,product1 = row[0],row[1],row[2],row[3],row[4],row[5],row[6]
if monitor == 1 :
print id,monitor,ip,product,relationship,ip1,product1
node1 = Node('product', name=product+ip)
node2 = Node('product', name=product1+ip1)
matcher = NodeMatcher(graph)
ifnode1 = matcher.match('product', name=product+ip).first()
if ifnode1 == None:
graph.create(node1)
else:
cc = ifnode1['name']
if product+ip == cc:
print "already exists 1"
else:
graph.create(node1)
ifnode2 = matcher.match('product', name=product1+ip1).first()
if ifnode2 == None:
graph.create(node2)
else:
dd = ifnode2['name']
if product1+ip1 == dd:
print "already exists 2"
else:
graph.create(node2)
print "create node ok"
def neo4jrelationship():
sql = "select * from `neo4j` ;"
cursor.execute(sql)
results = cursor.fetchall()
graph = Graph('http://192.168.1.245:7474', auth=('neo4j', 'passwd'))
for row in results:
id,monitor,ip,product,relationship,ip1,product1 = row[0],row[1],row[2],row[3],row[4],row[5],row[6]
if monitor == 1 :
print id,monitor,ip,product,relationship,ip1,product1
matcher = NodeMatcher(graph)
node1 = matcher.match('product',name=product+ip).first()
node2 = matcher.match('product',name=product1+ip1).first()
node_1 = Relationship(node1, 'node', node2)
graph.create(node_1)
if __name__=="__main__":
try:
conn = MySQLdb.connect("192.168.1.23", "root", "passwd", "test", charset='utf8' )
cursor = conn.cursor()
print "connect mysql "
createnode()
neo4jrelationship()
conn.close()
except:
print "Error"
mysql结构:
图形展示: