Compute.ego_network() Preview #
#Compute.ego_network(node: Producer,
hops: int = 1
) -> Expression
This method returns the induced subgraph containing all nodes within k undirected hops from a specified source node (ego-node). It identifies nearby nodes based on undirected shortest path distance, effectively capturing the local structure around the ego-node. This is useful for analyzing local connectivity patterns or extracting ego-networks. Must be called in a rule or query context.
Supported Graph Types#
Graph Type | Supported | Notes |
---|---|---|
Directed | Yes | |
Undirected | Yes | |
Weighted | Yes | Weights are ignored. |
Unweighted | Yes |
Returns#
Returns an Expression that produces the set of edges induced by the ego_network function.
Examples#
You access the .ego_network(node, hops)
method from a Graph
object’s
.compute
attribute:
#
import relationalai as rai
from relationalai.std import alias
from relationalai.std.graphs import Graph
model = rai.Model("socialNetwork")
Person = model.Type("Person")
with model.rule():
alice = Person.add(name="Alice")
bob = Person.add(name="Bob")
claire = Person.add(name="Claire")
dave = Person.add(name="Dave")
eve = Person.add(name="Eve")
frank = Person.add(name="Frank")
gina = Person.add(name="Gina")
alice.follows.add(alice)
alice.follows.add(bob)
bob.follows.add(claire)
claire.follows.add(dave)
dave.follows.add(eve)
eve.follows.add(frank)
frank.follows.add(gina)
graph = Graph(model, undirected=False)
graph.Node.extend(Person)
graph.Edge.extend(Person.follows)
with model.query() as select:
node = Person()
a,b = graph.compute.ego_network(node, 1)
ego_response = select(alias(node.name, "ego-node") , alias( Person(a).name, "u"), alias(Person(b).name, "v"))
print(ego_response.results)
# output
# ego-node u v
# 0 Alice Alice Alice
# 1 Alice Alice Bob
# 2 Bob Alice Alice
# 3 Bob Alice Bob
# 4 Bob Bob Claire
# 5 Claire Bob Claire
# 6 Claire Claire Dave
# 7 Dave Claire Dave
# 8 Dave Dave Eve
# 9 Eve Dave Eve
# 10 Eve Eve Frank
# 11 Frank Eve Frank
# 12 Frank Frank Gina
# 13 Gina Frank Gina
If you’re interested in retrieving the 2-hop ego-network of a specific node (e.g., Alice), you can apply the following modification to the code above:
#
with model.query() as select:
node = Person(name="Alice")
a,b = graph.compute.ego_network(node, hops=2)
ego_response = select(alias(node.name, "ego-node") , alias( Person(a).name, "u"), alias(Person(b).name, "v"))
# ego-node u v
# 0 Alice Alice Alice
# 1 Alice Alice Bob
# 2 Alice Bob Claire