0

I have a knowledge base graph (built in networkx).

Here is made up example.

G = nx.DiGraph()
G.add_edge('user1', 'New York', relation = 'works at')
G.add_edge('user1', 'Boston', relation = 'from')
G.add_edge('user1', '27', relation = 'Age') 

graph relations

Between each pair of nodes I have specific relation such as 'works at', 'from', etc

I want to check if I have desired edge for specific node. For example, do I know information about where user1 works at.

Currently, I do it in a loop:

for connected_node, attributes in G['user1'].items():
    if attributes['relation'] == 'works at':
        print(True, connected_node)

Is it possible to check if a node has specific edge without loop?

And consequently get connected node by this edge?

Vadym B.
  • 681
  • 7
  • 21

1 Answers1

1

No, you'll have to iterate over the edges of the node to see if any of them matches the search criteria. The only minor improvement I can think of, is to search only among the out-edges of the node with DiGraph.out_edges:

for source, dest, d in G.out_edges('user1', data=True):
    if d.get('relation') == 'works at':
        print(f'Connected node {source} -> {dest}')
# Connected node user1 -> New York
yatu
  • 86,083
  • 12
  • 84
  • 139
  • So, is it correct that I cannot uniquely index edges for each node? Like having dictionary inside dictionary? If no, maybe there are other frameworks with such capabilities? – Vadym B. Apr 22 '20 at 12:04
  • I'm mostly have experience with nx when it comes to graph analysis, so not so sure about the second point @VadymB. And no, you have to traverse the list of edges of a given node in search for the one that has the attribute of interest. You'd have to *know* which edge has the parameter in question for that. Btw don't forget you can upvote answers too :) – yatu Apr 22 '20 at 12:54