Querying nodes with has many relationship

I’m a noob at dgraph and I’m having trouble with this query.

I have two predicates: user and city, where a user can have multiple cities (all the cities they lived in).

I’m trying to write a query where, given a user id, I can find all the users that also have lived in a city that the user with the user id has lived in. In SQL I would join users by their cities, but I’m not sure how to do it with dgraph.

Schema:

user.public_id: string @index(hash) .
user.name: string @index(term) .
user.city: uid @reverse @count .
city.public_id: string @index(hash) .
1 Like

Maybe:

{
 MyUser(func: uid(0x1) {
    uid
    user.name
    user.public_id
    email
  ~user.city {
     city.name
     city.public_id
         user.city { #In this case you should filter this level, otherwise you may receive thousands of results from that city.
                    uid    
                    user.name
                    user.public_id
                    email
           }
     }
}
}

Result visually

How I simulated your request.


{
  set{
      #One City Registration
    _:cityYork <city.public_id> "1dd-48" .
    _:cityYork <name> "New York" .
  
      #User Registration 1
    _:jonah <user.name> "jonah" .
    _:jonah <user.public_id> "9a3f141e" .
    _:jonah <email> "jonah@jonah.com" . 
    _:cityYork <user.city> _:jonah . #connected in reverse with NY

      #User Registration 2
    _:Brolin <user.name> "Josh Brolin" .
    _:Brolin <user.public_id> "7a3b541v" .
    _:Brolin <email> "Josh@Brolin.com" . 
    _:cityYork <user.city> _:Brolin .  #connected in reverse

      #User Registration 3
    _:zoe <user.name> "Zoë Saldaña" .
    _:zoe <user.public_id> "1a4b991g" .
    _:zoe <email> "zoe@Saldana.com" . 
    _:cityYork <user.city> _:zoe .  #connected in reverse

  }
}

Data:

{
  "data": {
    "user": [
      {
        "uid": "0x2713",
        "user.name": "jonah",
        "user.public_id": "9a3f141e",
        "email": "jonah@jonah.com",
        "~user.city": [
          {
            "name": "New York",
            "city.public_id": "1dd-48",
            "user.city": [
              {
                "uid": "0x2711",
                "user.name": "Zoë Saldaña",
                "user.public_id": "1a4b991g",
                "email": "zoe@Saldana.com"
              },
              {
                "uid": "0x2713",
                "user.name": "jonah",
                "user.public_id": "9a3f141e",
                "email": "jonah@jonah.com"
              },
              {
                "uid": "0x2714",
                "user.name": "Josh Brolin",
                "user.public_id": "7a3b541v",
                "email": "Josh@Brolin.com"
              }
            ]
          }
        ]
      }
    ]
  }
1 Like

You should also think of predicates of the type

“Actual city”
“Hometown”
“Extra address”
“Moved from”