Efficient way to get number of nodes / relations in neo4j
<p><strong>TLDR</strong></p>

<p>Query <code>MATCH (n) RETURN count(n)</code> scans all nodes, can I do it in O(1)?</p>

<p><strong>Full question</strong></p>

<p>I added million nodes to graph and run query to count them</p>

<pre><code>PROFILE 
MATCH (n) RETURN count(n)
</code></pre>

<p>Which results in all nodes scan and takes 2 seconds: </p>

<p><a href="https://i.stack.imgur.com/jJqsq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jJqsq.png" alt="enter image description here"></a></p>

<p>Adding index on label and property does not change situation</p>

<pre><code>Indexes
  ON :USER(userId)     ONLINE (for uniqueness constraint) 
Constraints
  ON (user:USER) ASSERT user.userId IS UNIQUE
</code></pre>

<p>So the next query also runs in 2 seconds </p>

<pre><code>PROFILE 
MATCH (n: USER) RETURN count(n)
</code></pre>

<p><a href="https://i.stack.imgur.com/wey50.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wey50.png" alt="enter image description here"></a></p>

<p>Counting relations with queries like </p>

<pre><code>MATCH ()-[r]-&gt;() return count(r)
MATCH ()-[r:relation_type]-&gt;() return count(r)
</code></pre>

<p>Also results in similar plan with 5 seconds execution time (3M relations)</p>

<p>Is there better syntax to query for count of nodes / relations which would result in &lt; O(n)? Or should we never count all nodes / relations? I would like to know why indexes do not cover these queries and what is blocking from making these queries fast.</p>