Search code examples
tinkerpoptinkerpop3gremlin-server

Graph traversal name to graph name mapping


Is there any API using which I can get graphTraversalName to graphName mapping defined in the script?

I am using the below messy code but it's error-prone if both graphs are using the same underlying storage.

    Map<String, String>  graphTraversalToNameMap = new ConcurrentHashMap<String, String>();
    while(traversalSourceIterator.hasNext()){
      String traversalSource = traversalSourceIterator.next();
      String currentGraphString = ( (GraphTraversalSource) graphManager.getAsBindings().get(traversalSource)).getGraph().toString();
      graphNameTraversalMap.put(currentGraphString, traversalSource);
    }

    Iterator<String> graphNamesIterator =  graphManager.getGraphNames().iterator();
    while(graphNamesIterator.hasNext()){
      String graphName = graphNamesIterator.next();
      String currentGraphString = graphManager.getGraph(graphName).toString();
      String traversalSource = graphNameTraversalMap.get(currentGraphString);
      graphTraversalToNameMap.put(traversalSource, graphName);
    }

Does gremlinExecutor.getScriptEngineManager().getBindings().entrySet() provide order guarantee? I can iterate over this and populate my map


Solution

  • Underlying storage details can be obtained from the configuration object and can be used for the mapping, sample code:

    public class GraphTraversalMappingUtil {
      public static void populateGraphTraversalToNameMapping(GraphManager graphManager){
    
        if(graphTraversalToNameMap.size() != 0){
          return;
        }
    
        Iterator<String> traversalSourceIterator = graphManager.getTraversalSourceNames().iterator();
    
        Map<StorageBackendKey, String> storageKeyToTraversalMap = new HashMap<StorageBackendKey, String>();
        while(traversalSourceIterator.hasNext()){
          String traversalSource = traversalSourceIterator.next();
          StorageBackendKey key = new StorageBackendKey(
                  graphManager.getTraversalSource(traversalSource).getGraph().configuration());
          storageKeyToTraversalMap.put(key, traversalSource);
        }
    
        Iterator<String> graphNamesIterator =  graphManager.getGraphNames().iterator();
        while(graphNamesIterator.hasNext()) {
          String graphName = graphNamesIterator.next();
          StorageBackendKey key = new StorageBackendKey(
                  graphManager.getGraph(graphName).configuration());
          graphTraversalToNameMap.put(storageKeyToTraversalMap.get(key), graphName);
        }
      }
    }
    

    For full code, refer: https://pastebin.com/7m8hi53p