This is the data setup from documentation:
SELECT * FROM cypher('graph_name', $$
CREATE (:L {a: 1, b: 2, c: 3}),
(:L {a: 2, b: 3, c: 1}),
(:L {a: 3, b: 1, c: 2})
$$) as (a agtype);
and this is the query:
SELECT * FROM cypher('graph_name', $$
MATCH (x:L)
RETURN (x.a + x.b + x.c) + count(*) + count(*), x.a + x.b + x.c
$$) as (count agtype, key agtype);
Output:
count | key
-------+-----
12 | 6
(1 row)
I don’t understand how the count
function works exactly, where is the grouping key in this example is it the (x.a + x.b + x.c) part or is it the , x.a + x.b + x.c part, then how does count work to yield the above output?
2
Answers
In your query, since you used
count(*)
without any grouping clause, yourcount
functions will calculate the number of rows in the result set and since there are three rows, eachcount
function returns a value of 3.Since the aggregate of
x.a + x.b + x.c
is 6, and the two count functions is equal to 6,count
result is equal to 12The value of
key
result (x.a + x.b + x.c
) is 6Hope this helps
You can better understand how this query works if you change some values. For example if you create your initial dataset like this:
and then run the same query:
you will get this output:
So basically what happened here is that it uses the
(x.a + x.b + x.c)
as a grouping key.One group is the rows that the
(x.a + x.b + x.c) + count(*) + count(*)
result into 5. If you see our dataset you can see that one of our vertices has different values that(x.a + x.b + x.c) = 3
. Since it is only 1 vertex, when thecount(*)
function is being used it is only going to count 1 vertex twice (because thecount(*)
function is used twice). Therefore the count in the output is going to be 5, and the key is just the(x.a + x.b + x.c)
which is 3.The second group is the rows that the
(x.a + x.b + x.c)
equals to 6. There are 2 rows that satisfy that grouping key so thecount(*)
function equals to 2 (so the 2count(*)
functions equal to 4). Therefore if we add(x.a + x.b + x.c) + count(*) + count(*)
we get 10. And that is thecount
in our output. For the key it is the same as the first group we just addx.a + x.b + x.c
and the resulting key is 6.