Count Step

The count step consumes the walker and efficiently counts the number of elements that have passed through the traversal up to that point. It is a terminal step that returns a single usize value representing the total count.

Count step diagram showing elements flowing into the step and a usize count as the output

In this diagram:

  • Input Elements: The walker starts with elements A, B, C, D.
  • The .count() step processes the stream and consumes the walker.
  • Returns: usize: The step returns a single usize value, which is the total number of elements processed (4 in this case).
  • Terminates Walker: This step ends the Graph API walker chain.

Syntax

walker.count()

Parameters

This step takes no parameters.

Return Value

Returns a usize representing the number of elements in the traversal.

Examples

Basic Count

Count the number of people in the graph:

    // Basic count - how many people are in the graph?
    let person_count = graph.walk().vertices(Vertex::person()).count();

    println!("Total people in graph: {}", person_count);

Filtered Count

Count elements that match specific criteria:

    // Count with filtering - how many people are over 30?
    let older_person_count = graph
        .walk()
        .vertices(Vertex::person())
        .filter_by_person(|person, _| person.age() > 30)
        .count();

    println!("People over 30: {}", older_person_count);

Edge Count

Count relationships in the graph:

    // Count relationships - how many 'follows' relationships exist?
    let knows_count = graph
        .walk()
        .vertices(VertexSearch::scan())
        .edges(Edge::follows())
        .count();

    println!("Total 'follows' relationships: {}", knows_count);

Analytics

Use counts to calculate graph analytics:

    // Count for analytics - average number of people followed per person
    let person_count = graph.walk().vertices(Vertex::person()).count();

    if person_count > 0 {
        let knows_count = graph
            .walk()
            .vertices(Vertex::person())
            .edges(Edge::follows().incoming())
            .count();

        let avg_known = knows_count as f64 / person_count as f64;
        println!("Average people followed per person: {:.2}", avg_known);
    }

Best Practices

  • Use count directly rather than collecting results just to count them
  • Consider indexed counts for large graphs when available in your implementation
  • Combine with filter steps for specific counting queries
  • Use count to validate expectations in tests and assertions

Common Use Cases

  • Existence checking: Determining if any elements match criteria (count > 0)
  • Graph analytics: Calculating statistics like average connections per node
  • Validation: Ensuring expected numbers of elements exist in certain conditions
  • Performance metrics: Measuring graph size and density characteristics