Getting a total count of the edge connections

Hi, Ive put together a simple graph of Computer models and owners. I’m trying to write a query, where I can get the total number of computers owned, but can’t seem to figure it out.

Here is the data

{
  set {

    # Computers
    _:computer1 <name> "Macbook Pro" .
    _:computer1 <year> "2012" .
    _:computer1 <manufacture> "apple" .

    _:computer2 <name> "Macbook Pro" .
    _:computer2 <year> "2014" .
    _:computer2 <manufacture> "apple" .

    _:computer3 <name> "Macbook Pro" .
    _:computer3 <year> "2016" .
    _:computer3 <manufacture> "apple" .

    _:computer4 <name> "Macbook Pro" .
    _:computer4 <year> "2018" .
    _:computer4 <manufacture> "apple" .

    _:computer5 <name> "Macbook Air" .
    _:computer5 <year> "2012" .
    _:computer5 <manufacture> "apple" .

    _:computer6 <name> "Macbook Air" .
    _:computer6 <year> "2013" .
    _:computer6 <manufacture> "apple" .


    # Users
    _:user1 <name> "Bob" .
    _:user1 <owns> _:computer1 .

    _:user2 <name> "John" .
    _:user2 <owns> _:computer2 .

    _:user3 <name> "Ringo" .
    _:user3 <owns> _:computer3 .
    _:user3 <owns> _:computer6 .

    _:user4 <name> "Steve" .
    _:user4 <owns> _:computer1 .

  }
}

When I run this query

{    
  all_computers(func: has(~owns)) @cascade {
		count(uid)
		name
    year
    manufacture
    count : count(~owns)
  }
}

I get the following output

{
  "data": {
    "all_computers": [
      {
        "count": 4
      },
      {
        "name": "Macbook Air",
        "year": "2013",
        "manufacture": "apple",
        "count": 1
      },
      {
        "name": "Macbook Pro",
        "year": "2016",
        "manufacture": "apple",
        "count": 1
      },
      {
        "name": "Macbook Pro",
        "year": "2012",
        "manufacture": "apple",
        "count": 2
      },
      {
        "name": "Macbook Pro",
        "year": "2014",
        "manufacture": "apple",
        "count": 1
      }
    ]
  },
}

The first count shows number of computer nodes that have edges (4). But if you look at the count for each model, the 2012 has 2 owners. So there are 5 computers in existence. What is the right way to calculate this ?

try sum function
https://docs.dgraph.io/query-language/#sum-and-avg

{    
  var(func: has(owns)) {
    c as	count(owns)
  }
	  computer() {
   total:  sum(val(c))
  }
}

2 Likes

Thanks - that works perfectly!

you’re welcome
:sunglasses:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.