Search code examples
graphorientdbgremlin

How can I get the latest 10 posts those are written by people in my network (2 level) with gremlin query?


I have friends, my friends have friends also. How can I get the latest 10 posts those are written by people in my network (2 level) with gremlin query?


Solution

  • Given you want to obtain the last 10 posts of friends and friends of friends of user u1:

    u1.out('friend').copySplit(_().out('friend').except([u1]).out('post'), _().out('post')).exhaustMerge.dedup.order{it.b.ts <=> it.a.ts}[0..<10].map
    

    gives you:

    ==>{msg=f, ts=2015-03-08 12:09:11.567}
    ==>{msg=e, ts=2015-03-08 12:09:01.459}
    ==>{msg=d, ts=2015-03-08 12:08:56.339}
    ==>{msg=c, ts=2015-03-08 12:08:41.209}
    ==>{msg=b, ts=2015-03-08 12:08:21.086}
    

    with the following sample graph:

    import java.sql.Timestamp
    
    g = new TinkerGraph()
    u1 = g.addVertex('user1')
    u2 = g.addVertex('user2')
    u3 = g.addVertex('user3')
    u4 = g.addVertex('user4')
    u5 = g.addVertex('user5')
    
    g.addEdge(u1,u2,'friend')
    g.addEdge(u2,u1,'friend')
    g.addEdge(u2,u3,'friend')
    g.addEdge(u3,u2,'friend')
    g.addEdge(u1,u3,'friend')
    g.addEdge(u3,u1,'friend')
    g.addEdge(u2,u4,'friend')
    g.addEdge(u4,u2,'friend')
    g.addEdge(u4,u5,'friend')
    g.addEdge(u5,u4,'friend')
    
    p1 = g.addVertex('post1',['ts': new Timestamp(System.currentTimeMillis() - 100000), 'msg':'a'])
    p2 = g.addVertex('post2',['ts': new Timestamp(System.currentTimeMillis() - 80000), 'msg':'b'])
    p3 = g.addVertex('post3',['ts': new Timestamp(System.currentTimeMillis() - 60000), 'msg':'c'])
    p4 = g.addVertex('post4',['ts': new Timestamp(System.currentTimeMillis() - 45000), 'msg':'d'])
    p5 = g.addVertex('post5',['ts': new Timestamp(System.currentTimeMillis() - 40000), 'msg':'e'])
    p6 = g.addVertex('post6',['ts': new Timestamp(System.currentTimeMillis() - 30000), 'msg':'f'])
    p7 = g.addVertex('post7',['ts': new Timestamp(System.currentTimeMillis() - 20000), 'msg':'g'])
    p8 = g.addVertex('post8',['ts': new Timestamp(System.currentTimeMillis() - 10000), 'msg':'h'])
    p9 = g.addVertex('post9',['ts': new Timestamp(System.currentTimeMillis()), 'msg':'i'])
    
    g.addEdge(u1,p1,'post')
    g.addEdge(u1,p9,'post')
    g.addEdge(u2,p3,'post')
    g.addEdge(u3,p6,'post')
    g.addEdge(u4,p5,'post')
    g.addEdge(u4,p2,'post')
    g.addEdge(u4,p4,'post')
    g.addEdge(u5,p7,'post')
    g.addEdge(u5,p8,'post')