问题
MATCH (p:Product), (s:Student), (b:Boy), (a:Attribute)
RETURN count(distinct(p)), count(distinct(s)), count(distinct(b)), count(distinct(a))
I want to know how many counts of each node types in the graph using this query. However, the Neo4j Browser gives a warning saying that this query produces a cartesian product. Is there a better way to write the query?
回答1:
To get a variety of statistics for your DB, including a count of the number of nodes for every label, you can use the APOC function apoc.meta.stats.
The following query gets just the label node counts, returning a map of label names to node counts:
CALL apoc.meta.stats() YIELD labels
RETURN labels;
回答2:
Yes. You want to make sure your query uses the NodeCountFromCountStore
operator (you can view this in the query plan if you EXPLAIN the query, so you can check before you actually execute).
The tricky part of this is that the only way for this plan to be used is if you match to all nodes of a label, then get the count (no other variables in your WITH or RETURN!).
You can try this approach, which unions queries together, and keeps the NodeCountFromStore
by adding the label column after you get the count:
match (n:Product)
with count(n) as count
return 'Product' as label, count
union all
match (n:Student)
with count(n) as count
return 'Student' as label, count
union all
match (n:Boy)
with count(n) as count
return 'Boy' as label, count
union all
match (n:Attribute)
with count(n) as count
return 'Attribute' as label, count
来源:https://stackoverflow.com/questions/48726836/how-to-count-the-numbers-of-node-types-in-the-neo4j-graph