日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

gremlin_python使用及增删查改方法封装

發布時間:2024/1/1 python 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 gremlin_python使用及增删查改方法封装 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

    • 一、安裝Janusgraph
    • 二、連接gremlin
    • 三、增刪查改方法封裝
    • 四、其他方法封裝
    • 五、致謝

一、安裝Janusgraph

1、下載安裝包

前往janusgraph的官方發布頁下載離線安裝包,如下圖所示,目前最新的版本是0.4.0,點擊janusgraph-0.4.0-hadoop2.zip下載即可。請注意,該安裝包只能在linux系統下安裝!!!


2、解壓運行

打開終端,使用unzip命令解壓下載好的zip安裝包,然后進入到janusgraph-0.4.0目錄下,執行 bin/janusgraph.sh start ,會得到如下的運行結果,說明janusgraph運行成功。

$ bin/janusgraph.sh startForking Cassandra...Running `nodetool statusthrift`.. OK (returned exit status 0 and printed string "running").Forking Elasticsearch...Connecting to Elasticsearch (127.0.0.1:9300)... OK (connected to 127.0.0.1:9300).Forking Gremlin-Server...Connecting to Gremlin-Server (127.0.0.1:8182)... OK (connected to 127.0.0.1:8182).Run gremlin.sh to connect.

3、其他操作

janusgraph-0.4.0目錄下,執行 bin/janusgraph.sh status ,可以查看janusgraph的運行狀態及進程ID,而執行 bin/janusgraph.sh stop ,則關閉janusgraph及其相關的所有進程。

$ ./bin/janusgraph.sh statusGremlin-Server (org.apache.tinkerpop.gremlin.server.GremlinServer) is running with pid 31841Elasticsearch (org.elasticsearch.bootstrap.Elasticsearch) is running with pid 31668Cassandra (org.apache.cassandra.service.CassandraDaemon) is running with pid 31336$ bin/janusgraph.sh stopKilling Gremlin-Server (pid 31841)...Killing Elasticsearch (pid 31668)...Killing Cassandra (pid 31336)...

二、連接gremlin

1、使用gremlin控制臺連接

janusgraph-0.4.0目錄下,執行 bin/gremlin.sh 則可啟動gremlin控制臺,如下所示。然后可以進行gremlin的相關操作,如:remote命令告訴控制臺使用conf/remote.yaml配置文件與gremlin服務進行遠程連接,:>是“提交”命令,比如 :> graph.addVertex("name", "test")是添加了一個name為test的節點,然后 :> g.V().values('name')則是查詢該圖中所有節點中含有name屬性的值。

$ bin/gremlin.sh\,,,/(o o)-----oOOo-(3)-oOOo-----plugin activated: tinkerpop.serverplugin activated: tinkerpop.hadoopplugin activated: tinkerpop.utilitiesplugin activated: janusgraph.importsplugin activated: tinkerpop.tinkergraphgremlin> :remote connect tinkerpop.server conf/remote.yaml==>Connected - localhost/127.0.0.1:8182gremlin> :> graph.addVertex("name", "test")==>v[4726]gremlin> :> g.V().values('name')==>test

2、使用gremlin_python連接

首先需要安裝gremlin_python這個依賴包,使用pip命令安裝 pip install gremlinpython==3.4.1 ,這里要注意的是 janusgraph0.4.0支持的gremlin最高版本為3.4.1,所以安裝的時候需指定版本號。
安裝完成后,便可在python程序中進行連接了,注意此時需要保證janusgraph處于運行狀態。

from gremlin_python.driver.driver_remote_connection import DriverRemoteConnectionfrom gremlin_python.process.anonymous_traversal import traversalconnection = DriverRemoteConnection('ws://127.0.0.1:8182/gremlin', 'g')graph = traversal().withRemote(connection)graph.addV('person').property('name', 'test').next() # 添加節點print(graph.V().values('name').toList()) # 輸出為 ['test']

三、增刪查改方法封裝

1、新增節點

只需傳入新增節點的 label 以及 properties(dict,可選),返回 Vertex(id, label)類型。

def add_vertex(graph, label, properties=None):"""add vertex:param graph: graph, type: GraphTraversalSource:param label: label, type: str:param properties: property dict, like {'p1': 'value1', 'p2': 'value2'}:return: vertex, Vertex(id, label)"""vert = graph.addV(label)if properties:for key in properties.keys():vert.property(key, properties.get(key))return vert.next()

2、新增邊

傳入新增邊的 label 和 properties(dict,可選),以及需要添加邊的兩節點(或其ID)v_from和v_to。

def add_edge(graph, label, v_from, v_to, properties=None):"""add edge:param graph: graph, type: GraphTraversalSource:param label: label, type: str:param v_from: long vertex id or Vertex(id, label) of from:param v_to: long vertex id or Vertex(id, label) of to:param properties: property dict, like {'p1': 'value1', 'p2': 'value2'}:return: None"""if isinstance(v_from, int):v_from = graph.V().hasId(v_from).next()if isinstance(v_to, int):v_to = graph.V().hasId(v_to).next()edge = graph.V(v_from).addE(label).to(v_to)if properties:for key in properties.keys():edge.property(key, properties.get(key))edge.next()

3、刪除節點

可以根據要求來刪除特定節點,如根據節點(或其ID)、label、properties。如果不傳入其他參數,則默認刪除所有節點。

def drop_vertex(graph, v_id=None, label=None, properties=None):"""drop all vertex or specific vertex:param graph: graph, type: GraphTraversalSource:param v_id: long vertex id or Vertex(id, label):param label: label, type: str:param properties: property list, like ['p1', 'p2', {'p3': 'value'}]:return: None"""if isinstance(v_id, int):v_id = graph.V().hasId(v_id).next()travel = graph.V(v_id) if v_id else graph.V()if label:travel = travel.hasLabel(label)if properties:for p in properties:if isinstance(p, dict):key = list(p.keys())[0]travel = travel.has(key, p.get(key))else:travel = travel.has(p)travel.drop().iterate()

4、刪除邊

可以根據要求來刪除特定邊,如根據邊ID、label、properties。如果不傳入其他參數,則默認刪除所有邊

def drop_edge(graph, e_id=None, label=None, properties=None):"""drop all edges or specific edge:param graph: graph, type: GraphTraversalSource:param e_id: edge id, type str:param label: label, type: str:param properties: property list, like ['p1', 'p2', {'p3': 'value'}]:return: None"""travel = graph.E(e_id) if e_id else graph.E()if label:travel = travel.hasLabel(label)if properties:for p in properties:if isinstance(p, dict):key = list(p.keys())[0]travel = travel.has(key, p.get(key))else:travel = travel.has(p)travel.drop().iterate()

5、查詢節點

首先,可以根據節點(或其ID)查詢該節點的所有屬性值,此時需使用return travel.valueMap().toList()。
其次,可以通過 label 或 properties 來查詢符合條件的所有節點,此時使用return travel.toList()。

def query_vertex(graph, v_id=None, label=None, properties=None):"""query graph vertex (value) list:param graph: graph, type: GraphTraversalSource:param v_id: long vertex id or Vertex(id, label):param label: label, type: str:param properties: property list, like ['p1', 'p2', {'p3': 'value'}]:return: vertex list or vertex value list"""if isinstance(v_id, int):v_id = graph.V().hasId(v_id).next()travel = graph.V(v_id) if v_id else graph.V()if label:travel = travel.hasLabel(label)if properties:for p in properties:if isinstance(p, dict):key = list(p.keys())[0]travel = travel.has(key, p.get(key))else:travel = travel.has(p)# return travel.valueMap().toList()return travel.toList()

6、查詢邊

根據邊的ID、label 或 properties 來查詢符合條件的邊的所有屬性值。

def query_edge(graph, e_id=None, label=None, properties=None):"""query graph edge value list:param graph: graph, type: GraphTraversalSource:param e_id: edge id, type str:param label: label, type: str:param properties: property list, like ['p1', 'p2', {'p3': 'value'}]:return: valueMap list"""travel = graph.E(e_id) if e_id else graph.E()if label:travel = travel.hasLabel(label)if properties:for p in properties:if isinstance(p, dict):key = list(p.keys())[0]travel = travel.has(key, p.get(key))else:travel = travel.has(p)return travel.valueMap().toList()

7、查詢所有與節點相連的邊

根據節點(或其ID)查詢與該節點相連的所有邊

def query_edges_of_vertex(graph, v_id):"""query all edges of vertex:param graph: graph, type: GraphTraversalSource:param v_id: v_id: long vertex id or Vertex(id, label):return: edge list"""if isinstance(v_id, int):v_id = graph.V().hasId(v_id).next()result = []in_edges = graph.V(v_id).inE().toList()out_edges = graph.V(v_id).outE().toList()result.extend(in_edges)result.extend(out_edges)return result

8、查詢所有與節點相連的節點

根據節點(或其ID)查詢與該節點相連的所有節點。

def query_near_vertex(graph, v_id):"""query near vertices of vertex:param graph: graph, type: GraphTraversalSource:param v_id: v_id: long vertex id or Vertex(id, label):return: vertex list"""if isinstance(v_id, int):v_id = graph.V().hasId(v_id).next()result = []out_v = graph.V(v_id).out().toList()in_v = graph.V(v_id).in_().toList()result.extend(out_v)result.extend(in_v)return result

四、其他方法封裝

1、獲取邊的ID

def get_edge_id(edge):"""get edge id:param edge: Egde(id, label, outV, inV):return: edge id, type str"""return edge.id.get('@value').get('relationId')

2、節點屬性轉字典

def vertex_to_dict(graph, vertex):"""transfer Vertex's info to dict:param graph: graph, type: GraphTraversalSource:param vertex: vertex, Vertex(id, label):return: vertex info dict"""properties = graph.V(vertex).valueMap().toList()[0]for key in properties.keys():properties[key] = properties.get(key)[0]return {'id': vertex.id,'label': vertex.label,'properties': properties}

3、邊屬性轉dict

def edge_to_dict(graph, edge):"""transfer Edge's info to dict:param graph: graph, type: GraphTraversalSource:param edge: edge, Edge(id, label, outV, inV):return: edge info dict"""e_id = get_edge_id(edge)properties = graph.E(e_id).valueMap().toList()[0]return {'id': e_id,'label': edge.label,'properties': properties}

4、判斷節點是否在圖中

對于已知節點的 label 和 properties 值,判斷該節點是否在圖中;如果在,返回該節點,否則返回None。

def judge_vertex_in_graph(graph, vertex_dict):"""judge a vertex whether in graph:param graph: graph, type: GraphTraversalSource:param vertex_dict: vertex dict, like {'label': 'value1', 'properties': {'p1': 'v1', ...}}:return: None or Vertex(id,label)"""label = vertex_dict.get('label')properties = vertex_dict.get('properties')travel = graph.V()if label:travel = travel.hasLabel(label)if properties:for k in properties.keys():travel = travel.has(k, properties.get(k))if travel.hasNext():return travel.next()return None

5、獲取子圖

根據特定的節點信息或者邊信息來獲取子圖。

def get_sub_graph(graph, vertices=None, edges=None, vertex_properties=None):"""get sub graph:param graph: graph, type: GraphTraversalSource:param vertices: hasLabel('label').has('property').has('age', gt(20)):param edges: hasLabel('label').has('property'):param vertex_properties::return: sub_graph, type: GraphTraversalSource"""strategy = SubgraphStrategy(vertices=vertices, edges=edges, vertex_properties=vertex_properties)return graph.withStrategies(strategy)

五、致謝

以上所有代碼都供參考學習,非常感謝大家的閱讀。如果有任何問題,都可在下方留言交流,希望大家一起學習,共同進步。

總結

以上是生活随笔為你收集整理的gremlin_python使用及增删查改方法封装的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。