基於neo4j的數據可視化
Neo4j是一個高性能的,NOSQL圖形數據庫,它將結構化數據存儲在網絡上而不是表中。它是一個嵌入式的、基於磁盤的、具備完全的事務特性的Java持久化引擎,但是它將結構化數據存儲在網絡(從數學角度叫做圖)上而不是表中。Neo4j也可以被看作是一個高性能的圖引擎,該引擎具有成熟數據庫的所有特性。程序員工作在一個面向對象的、靈活的網絡結構下而不是嚴格、靜態的表中——但是他們可以享受到具備完全的事務特性、企業級的數據庫的所有好處。
(1)安裝好neo4j數據庫後,進入bin目錄,控制檯輸入,啓動neo4j數據庫,瀏覽器輸入,訪問數據庫。
(2)使用python導入數據。
相關代碼如下:
1.連接數據庫
# coding:utf-8 from py2neo import Graph, Node, Relationship, NodeMatcher import numpy as np import pandas as pd person_list = pd.read_csv('testdata1.txt', sep=' ') X = person_list[["id", "child_id", "relation"]] # 取出需要的數據 list = [] nodes = [] categories = [] ##連接neo4j數據庫,輸入地址、用戶名、密碼 graph = Graph('http://localhost:7474', auth=("neo4j", "root"))
2.數據去重,並且創建結點
##創建結點 i = 0 uniqueId = [] uniqueChildId = [] for row in X.iteritems(): if i == 0: uniqueChildId = np.unique(row[1].values) nodes.append(uniqueChildId) print(uniqueChildId) i =i+1 continue if i == 1: uniqueId = np.unique(row[1].values) nodes.append(uniqueId) print(uniqueId) i=i+1 continue uniqueId = np.append(uniqueId,uniqueChildId) globalUnique = np.unique(uniqueId) print(globalUnique) #id以及子id去重後的全局唯一id j = 0 for row in globalUnique: graph.create(Node('血緣關係', name=int(row))) j+=1 print('node:'+str(j))
3.創建關係
# ##創建關係 k = 0 for row in X.itertuples(): list.append({"source":str(row.id),"target":str(row.child_id)}) relation = "" if(row.relation=='s'): relation = "兒子" elif(row.relation=='m'): relation = "母親" elif(row.relation=='f'): relation = "父親" rel = Relationship(NodeMatcher(graph).match(name=row.id).first(), relation, NodeMatcher(graph).match(name=row.child_id).first()) print(rel) k+=1 print('res:'+str(k)) graph.create(rel)
整個過程大概持續2個小時左右(10萬條數據)。
(3)通過查看可視化數據如下:
通過上圖可以看到,數據的邏輯關係已經展示出來,但是有一個問題,就是數據的邏輯關係混亂(同一個人,既是兒子,又是母親)
大數據環境下,數據無法做到百分百正確,需要根據一些特定參數進行修正,但是規則也不是隨意指定的,此處我們沒有更多的信息,暫不修正邏輯錯誤。
(4)通過查詢結點
查詢指定屬性結點:
MATCH (n)-->(b) where b.name = 1296
return b
查詢指定關係結點:
MATCH p=()-[r:`兒子`]->() RETURN p
查詢指定label結點:
MATCH (n:`血緣關係`) RETURN n
按指定度查詢結點:
MATCH (k)
WITH k, size((k)--()) as degree
WHERE degree = 1
MATCH (k)--(n)
RETURN n,k,degree
查找結點最短路徑:
MATCH (p1:`血緣關係` {name:9311}),(p2:`血緣關係`{name:365}),
p=shortestpath((p1)-[*..10]->(p2))
RETURN p
注:[*…10]表示查詢路徑長度10以內的關係