Created
February 13, 2017 22:15
-
-
Save peeyushsrj/b342e169f753b7905f87c7b7d443a602 to your computer and use it in GitHub Desktop.
Efficient Data Structure for Graph Social Network using golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Efficient Design
int
, so thatPerson.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
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).