gremlin_python使用及增删查改方法封装
文章目錄
- 一、安裝Janusgraph
- 二、連接gremlin
- 三、增刪查改方法封裝
- 四、其他方法封裝
- 五、致謝
一、安裝Janusgraph
1、下載安裝包
前往janusgraph的官方發(fā)布頁(yè)下載離線安裝包,如下圖所示,目前最新的版本是0.4.0,點(diǎn)擊janusgraph-0.4.0-hadoop2.zip下載即可。請(qǐng)注意,該安裝包只能在linux系統(tǒng)下安裝!!!
2、解壓運(yùn)行
打開(kāi)終端,使用unzip命令解壓下載好的zip安裝包,然后進(jìn)入到janusgraph-0.4.0目錄下,執(zhí)行 bin/janusgraph.sh start ,會(huì)得到如下的運(yùn)行結(jié)果,說(shuō)明janusgraph運(yùn)行成功。
$ 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目錄下,執(zhí)行 bin/janusgraph.sh status ,可以查看janusgraph的運(yùn)行狀態(tài)及進(jìn)程ID,而執(zhí)行 bin/janusgraph.sh stop ,則關(guān)閉janusgraph及其相關(guān)的所有進(jìn)程。
$ ./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控制臺(tái)連接
在janusgraph-0.4.0目錄下,執(zhí)行 bin/gremlin.sh 則可啟動(dòng)gremlin控制臺(tái),如下所示。然后可以進(jìn)行g(shù)remlin的相關(guān)操作,如:remote命令告訴控制臺(tái)使用conf/remote.yaml配置文件與gremlin服務(wù)進(jìn)行遠(yuǎn)程連接,:>是“提交”命令,比如 :> graph.addVertex("name", "test")是添加了一個(gè)name為test的節(jié)點(diǎn),然后 :> g.V().values('name')則是查詢?cè)搱D中所有節(jié)點(diǎn)中含有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')==>test2、使用gremlin_python連接
首先需要安裝gremlin_python這個(gè)依賴包,使用pip命令安裝 pip install gremlinpython==3.4.1 ,這里要注意的是 janusgraph0.4.0支持的gremlin最高版本為3.4.1,所以安裝的時(shí)候需指定版本號(hào)。
安裝完成后,便可在python程序中進(jìn)行連接了,注意此時(shí)需要保證janusgraph處于運(yùn)行狀態(tài)。
三、增刪查改方法封裝
1、新增節(jié)點(diǎn)
只需傳入新增節(jié)點(diǎn)的 label 以及 properties(dict,可選),返回 Vertex(id, label)類(lèi)型。
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,可選),以及需要添加邊的兩節(jié)點(diǎn)(或其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、刪除節(jié)點(diǎn)
可以根據(jù)要求來(lái)刪除特定節(jié)點(diǎn),如根據(jù)節(jié)點(diǎn)(或其ID)、label、properties。如果不傳入其他參數(shù),則默認(rèn)刪除所有節(jié)點(diǎn)。
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、刪除邊
可以根據(jù)要求來(lái)刪除特定邊,如根據(jù)邊ID、label、properties。如果不傳入其他參數(shù),則默認(rèn)刪除所有邊。
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、查詢節(jié)點(diǎn)
首先,可以根據(jù)節(jié)點(diǎn)(或其ID)查詢?cè)摴?jié)點(diǎn)的所有屬性值,此時(shí)需使用return travel.valueMap().toList()。
其次,可以通過(guò) label 或 properties 來(lái)查詢符合條件的所有節(jié)點(diǎn),此時(shí)使用return travel.toList()。
6、查詢邊
根據(jù)邊的ID、label 或 properties 來(lái)查詢符合條件的邊的所有屬性值。
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、查詢所有與節(jié)點(diǎn)相連的邊
根據(jù)節(jié)點(diǎn)(或其ID)查詢與該節(jié)點(diǎn)相連的所有邊。
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 result8、查詢所有與節(jié)點(diǎn)相連的節(jié)點(diǎn)
根據(jù)節(jié)點(diǎn)(或其ID)查詢與該節(jié)點(diǎn)相連的所有節(jié)點(diǎn)。
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、節(jié)點(diǎn)屬性轉(zhuǎn)字典
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、邊屬性轉(zhuǎn)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、判斷節(jié)點(diǎn)是否在圖中
對(duì)于已知節(jié)點(diǎn)的 label 和 properties 值,判斷該節(jié)點(diǎn)是否在圖中;如果在,返回該節(jié)點(diǎn),否則返回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 None5、獲取子圖
根據(jù)特定的節(jié)點(diǎn)信息或者邊信息來(lái)獲取子圖。
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)五、致謝
以上所有代碼都供參考學(xué)習(xí),非常感謝大家的閱讀。如果有任何問(wèn)題,都可在下方留言交流,希望大家一起學(xué)習(xí),共同進(jìn)步。
總結(jié)
以上是生活随笔為你收集整理的gremlin_python使用及增删查改方法封装的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 华为ME909 4G LTE模块在树莓派
- 下一篇: 开发日志 2015-03-29