Examples

Filter & Count

Filter nodes using lambda functions and count results.

Learn how to filter graph results and count nodes.

Setting Up the Graph

from cog.torque import Graph

g = Graph("ages")
g.put_batch([
    ("alice", "age", "25"),
    ("bob", "age", "30"),
    ("charlie", "age", "35"),
])

Filtering with Lambda Functions

Use filter() with a lambda to filter based on conditions:

# People over 28
g.v().out("age").filter(lambda x: int(x) > 28).all()
# {'result': [{'id': '30'}, {'id': '35'}]}

To get the people (not ages), traverse back with inc():

g.v().out("age").filter(lambda x: int(x) > 28).inc("age").all()
# {'result': [{'id': 'bob'}, {'id': 'charlie'}]}

Counting Nodes

Use count() to get the number of matching nodes:

# Count all vertices
g.v().count()  # 3

# Count with filter
g.v().out("age").filter(lambda x: int(x) > 28).count()  # 2

More Filter Examples

# Filter by name prefix
g.v().filter(lambda x: x.startswith("a")).all()
# {'result': [{'id': 'alice'}]}

# Filter by exact value
g.v().out("age").filter(lambda x: x == "30").inc("age").all()
# {'result': [{'id': 'bob'}]}

On this page