Skip to content

Instantly share code, notes, and snippets.

@peeyushsrj
Created February 13, 2017 22:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peeyushsrj/b342e169f753b7905f87c7b7d443a602 to your computer and use it in GitHub Desktop.
Save peeyushsrj/b342e169f753b7905f87c7b7d443a602 to your computer and use it in GitHub Desktop.
Efficient Data Structure for Graph Social Network using golang
package main
import (
"encoding/json"
"log"
"net/http"
)
type Relationship struct {
Rid int
Type string
With int
}
type Person struct {
Pid int
Name string
Relation map[string][]int
}
//-------------------------------------------------------------
func (p *Person) AddRelation(q *Person, name string) *Person {
r := &Relationship{101, name, q.Pid}
if p.Relation == nil {
p.Relation = make(map[string][]int)
}
//Initializing map
p.Relation[name] = append(p.Relation[name], r.Rid) //to relatinship id only
return p
}
//-------------------------------------------------------------
func main() {
//api request to be match with url SOMETHING LIKE CHAT INTERFACE
http.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Add("Content-type", "application/json")
p1 := &Person{Pid: 1}
p1.Name = "P" //this id and other details may come from pages: our and other
p2 := &Person{2, "S", nil}
p1.AddRelation(p2, "WIFE")
p1.AddRelation(p2, "FRIEND")
p2.AddRelation(p1, "HUSBAND")
b, err := json.Marshal(p1)
if err != nil {
log.Fatal(err)
}
rw.Write(b)
})
log.Println("Running on http://localhost:9890")
log.Fatal(http.ListenAndServe(":9890", nil))
}
@peeyushsrj
Copy link
Author

peeyushsrj commented Feb 13, 2017

Efficient Design

  • Person is mapped to ID of Relationship. Relationship is mapped to other Person. O(1) to get from P to R to P.
  • Person.Relation is a map to array of int, so that Person.Relation[$relationName] will be fetched in O(1). And such such relations having same $relationName are Edges to given Person Node. ($relationName is variable here e.g. "FRIEND")

So this is 1-level query, now next level

  • A Function will be present to map Person.Id and Relationship.Id to respective object data. (Note: Make these ID's as primary key for database so that fetching them will be in O(1) )
  • This above function let's say idfy(Person.Id) will map to the person object. Now you can query within those person object as Person.Relation[$relationName2]. Complexity: O(E)

Level can grow like this with complexity of O(E).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment