Search code examples
filternodescytoscape.jsedges

How do I get edges along with the nodes I filtered in Cytoscape.js?


I would like to know how I can get the edges along with all the nodes which I filtered based on a specific query?

I have seen this example on Cytoscape.js page: https://js.cytoscape.org/#selectors

// get node j and the edges coming out from it
cy.elements('node#j, edge[source = "j"]');

Now I would like to do the same with a specific query attribute which all nodes have in common along with all edges.

I tried a query along the above idea like this:

const query = 'node[ nodeType = "Car"]';
graphElements = cy.elements(query);

This gives me all nodes with nodeType="Car" but with no edges. How can I get ALL edges along with the selected nodes query?


Solution

  • Ok, I might have found an answer to this, apparently nodes and edges are handled separately. In order to include edges, there are several options which can be found on the Cytoscape.js page under traversing such as nodes.edgesWith(), nodes.edgesTo(), nodes.connectedEdges(), etc. etc.

    So in order to for example filter by Nodes and corresponding Edges with Edge Successors as I need it in my case, it can be done the following:

    // Filter all nodes by nodeType Car
    const query = 'node[ nodeType = "Car"]';
    let filteredNodes = cy.nodes(query);
    
    // I only want to successors of all Nodes, so I add only those and combine 
       nodes and edges with union 
    const graphElements = filteredNodes.union(filteredNodes.successors());
    
    // Apply changes on graph
    cy.elements().remove();
    cy.add( graphElements );
    

    This is what I came up with, if anyone has something to optimize please let me know. I am still figuring out Cytoscape.js myself.