Skip to content

openCypher: a grouped count(*) over (a)-[:R]->(a) counts every edge of a, not its self-loops (grouped sibling of #8941) #10182

Closed

Description

@tae898

A single-hop pattern that names the same node at both ends, with a grouping key and count(*), counts every edge of the node instead of the edges that close on it. MATCH (a:N)-[:R]->(a) RETURN a.id, count(*) answers each node's out-degree, and nodes without a self-loop appear in the result. This is the grouped sibling of #8941: #8947 stopped the plain count(*) push-down from claiming a repeated variable, but the per-node shortcut COUNT EDGES RETURN (CypherExecutionPlan.tryOptimizeMatchCountReturn) still does.

Three nodes: 0 has a self-loop and an edge to 1, 1 has an edge to 2, 2 has a self-loop. The right answer is {id 0: 1, id 2: 1}. Found by a differential run against Neo4j 2026.08.1 and LadybugDB 0.21.2, which both give that answer.

Same answers on 26.10.2 (e5040d0339) and on main (8bebc13f6b), JDK 25 and JDK 21. On main, JDK 25:

query ArcadeDB
MATCH (a:N)-[:R]->(a) RETURN a.id AS id, count(*) AS n [{"id":0,"n":2}, {"id":1,"n":1}, {"id":2,"n":1}]
MATCH (a:N)<-[:R]-(a) RETURN a.id AS id, count(*) AS n [{"id":0,"n":1}, {"id":1,"n":1}, {"id":2,"n":2}]
MATCH (a:N)-[:R]->(a) RETURN a.id AS id [{"id":0}, {"id":2}]
MATCH (a:N)-[:R]->(a) RETURN count(*) AS n [{"n":2}]
MATCH (a:N)-[:R]->(a) WITH a RETURN a.id AS id, count(*) AS n [{"id":0,"n":1}, {"id":2,"n":1}]
MATCH (a:N)-[:R]->(b) WHERE a = b RETURN a.id AS id, count(*) AS n [{"id":0,"n":1}, {"id":2,"n":1}]
MATCH (a:N)-[r:R]->(a) RETURN a.id AS id, count(r) AS n [{"id":0,"n":1}, {"id":2,"n":1}]
MATCH (a:N)-[:R]->(a) RETURN a.id AS id, sum(1) AS n [{"id":0,"n":1}, {"id":2,"n":1}]

Only the first two are wrong (the reverse direction counts in-degrees). count(r), sum(1), WITH a, WHERE a = b, the ungrouped count(*) and the rows themselves are right. EXPLAIN of the first query:

+ MATCH NODE (a:N)
+ COUNT EDGES RETURN (a OUT [R] -> n)
+ FINAL PROJECTION [id, n]

The rewrite checks the WHERE clause, property filters, labels and grouping expressions, but not whether sourceVar and targetVar are the same variable; declining the rewrite in that case gives the right answer (PR to follow).

SameVarGroupedCount.java
import com.arcadedb.database.Database;
import com.arcadedb.database.DatabaseFactory;
import com.arcadedb.graph.MutableVertex;
import com.arcadedb.query.sql.executor.Result;
import com.arcadedb.query.sql.executor.ResultSet;
import java.util.*;

/** A pattern that names the same node at both ends, with a grouping key and count(*), counts every edge of the node instead of its self-loops.
 *  Three nodes: 0 has a self-loop and an edge to 1, 1 has an edge to 2, 2 has a self-loop. Expected answer (Neo4j, LadybugDB, and the
 *  same query without the shortcut): node 0 -> 1, node 2 -> 1. REMOVE WHEN: the issue is filed and fixed. */
public class SameVarGroupedCount {
  static void q(Database db, String text) {
    List<String> rows = new ArrayList<>();
    try (ResultSet rs = db.query("opencypher", text)) { while (rs.hasNext()) rows.add(rs.next().toJSON().toString()); }
    Collections.sort(rows);
    System.out.println("Q " + text + "\n  -> " + rows);
  }
  static void explain(Database db, String text) {
    try (ResultSet rs = db.query("opencypher", "EXPLAIN " + text)) {
      String plan = rs.getExecutionPlan().map(p -> p.prettyPrint(0, 2)).orElse("(no plan)");
      System.out.println("PLAN " + text + "\n" + plan.lines().map(l -> "  | " + l).reduce((x, y) -> x + "\n" + y).orElse(""));
    }
  }
  public static void main(String[] a) {
    String dir = a[0];
    DatabaseFactory f = new DatabaseFactory(dir);
    if (f.exists()) f.open().drop();
    try (Database db = f.create()) {
      db.command("sql", "CREATE VERTEX TYPE N");
      db.command("sql", "CREATE PROPERTY N.id LONG");
      db.command("sql", "CREATE EDGE TYPE R");
      db.transaction(() -> {
        MutableVertex[] v = new MutableVertex[3];
        for (int i = 0; i < 3; i++) v[i] = db.newVertex("N").set("id", (long) i).save();
        v[0].newEdge("R", v[0]); v[0].newEdge("R", v[1]); v[1].newEdge("R", v[2]); v[2].newEdge("R", v[2]);
      });
      System.out.println("engine " + com.arcadedb.Constants.getVersion() + " java " + System.getProperty("java.version"));
      String bad = "MATCH (a:N)-[:R]->(a) RETURN a.id AS id, count(*) AS n";
      q(db, bad);
      explain(db, bad);
      q(db, "MATCH (a:N)-[:R]->(a) RETURN a.id AS id, count(*) AS n ORDER BY id");
      q(db, "MATCH (a:N)<-[:R]-(a) RETURN a.id AS id, count(*) AS n");
      q(db, "MATCH (a:N)-[:R]->(a) RETURN a.id AS id");
      q(db, "MATCH (a:N)-[:R]->(a) RETURN count(*) AS n");
      q(db, "MATCH (a:N)-[:R]->(a) WITH a RETURN a.id AS id, count(*) AS n");
      q(db, "MATCH (a:N)-[:R]->(b) WHERE a = b RETURN a.id AS id, count(*) AS n");
      q(db, "MATCH (a:N)-[r:R]->(a) RETURN a.id AS id, count(r) AS n");
      q(db, "MATCH (a:N)-[:R]->(a) RETURN a.id AS id, sum(1) AS n");
    }
  }
}

Activity

  1. added
    severity:minor
    on Oct 16, 2026
  2. self-assigned this
    on Oct 16, 2026
  3. added
    in progress
    on Oct 16, 2026
  4. added this to the 26.11.1 milestone on Oct 16, 2026
  5. added a commit that references this issue on Oct 22, 2026
  6. robfrank commented on Oct 22, 2026

    @robfrank
    Collaborator

    Fixed by #10183. A grouped count such as MATCH (a)-[:R]->(a) RETURN a.id, count(*) was rewritten into a per-node edge count, so it returned every R edge of a instead of only the self-loops the pattern asks for. The rewrite now steps aside when both ends of the pattern are the same variable, so the query counts self-loops; a grouped count over two different variables, like (a)-[:R]->(b), still takes the fast path.

    Still open: nothing, the fix is complete.


    ❤️ Thanks for helping make ArcadeDB better! ArcadeDB is free and open source, sustained by its community. If it's useful to you or your company, please consider becoming a sponsor to keep development going.

  7. removed
    in progress
    on Oct 22, 2026
  8. added a commit that references this issue on Nov 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugopencypherseverity:minor

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions