Exporting a graph from neo4j and importing it into gephi

‹ Run neo4j-shell inside docker | Composable asset and vulnerability expected value model for security ›

Some code to calculate the <key> elements needed to get Gephi to import the labels for nodes and edges exported by neo4j

#!/usr/bin/env python
# coding=utf-8
# Copyright (C) 2017 Wesley Tanaka
"""
"""
# Per https://docs.python.org/3/howto/pyporting.html
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import sys
import xml.etree.ElementTree as ET

def makekeys(node, node_or_edge=None):
  tag = node.tag.replace('{http://graphml.graphdrawing.org/xmlns}', '')

  if node_or_edge is not None and tag == 'data':
    yield ET.Element('key', {
        'id': node.attrib.get('key'),
        'for': node_or_edge,
        'attr.name': node.attrib.get('key'),
        'attr.type': 'string'
    })

  if tag in ('node', 'edge'):
    node_or_edge = tag

  for child in node:
    for key in makekeys(child, node_or_edge):
      yield key

if __name__ == "__main__":
  tree = ET.parse(sys.stdin)
  keys = set()
  for elem in makekeys(tree.getroot()):
    keys.add(ET.tostring(elem))
  for key in keys:
    print(key)

 

Subscribe to All Posts - Wesley Tanaka