3

我使用 neo4j 数据库和 django-neomodel,我想为我的用户实现一个跟随系统并为用户编写这个模型:

class UserNode(StructuredNode):
    user_id = IntegerProperty(required=True, index=True)
    follow = RelationshipTo('UserNode','FOLLOW')

    def get_followers(self):
        results, metadata = self.cypher("START a=node({self}) MATCH a<-[:FOLLOW]-(b) RETURN b");
        return [self.__class__.inflate(row[0]) for row in results]

    def get_following(self):
        results, metadata = self.cypher("START a=node({self}) MATCH b-[:FOLLOW]->(a) RETURN b");
        return [self.__class__.inflate(row[0]) for row in results]

    def follow_person(self, user_id):
        import datetime
        from django.utils.timezone import utc

        followed_user = self.index.get(user_id=user_id)
        self.follow.connect(followed_user, {'time': str(datetime.datetime.utcnow().replace(tzinfo=utc))})
        self.save()
        followed_user.save()

您认为我的以下系统的 UserNode 模型是一个好的模型吗?

这个模型出现了问题!当我运行此代码时:

a = UserNode.index.get(user_id=200)
b = UserNode.index.get(user_id=201)
c = UserNode.index.get(user_id=202)

a.follow_person(201)
b.follow_person(200)

print a.get_followers(), a.get_following()

输出是两个空列表。为什么?

4

1 回答 1

8

嗨,这里是新模型的作者。

不需要在 follow_person 方法中保存。您使用的是哪个版本的新模型?以下代码对我有用:

class UserNode(StructuredNode):                                                                                                                                                                        
    user_id = IntegerProperty(required=True, index=True)
    follow = RelationshipTo('UserNode', 'FOLLOW')

    def get_followers(self):
        results, metadata = self.cypher("START a=node({self}) MATCH a<-[:FOLLOW]-(b) RETURN b")
        return [self.__class__.inflate(row[0]) for row in results]

    def get_following(self):
        results, metadata = self.cypher("START a=node({self}) MATCH b-[:FOLLOW]->(a) RETURN b")
        return [self.__class__.inflate(row[0]) for row in results]

    def follow_person(self, user_id):
        followed_user = self.index.get(user_id=user_id)
        self.follow.connect(followed_user, {'time': str(datetime.datetime.utcnow())})

u1 = UserNode(user_id=1).save()
u2 = UserNode(user_id=2).save()

u1.follow_person(2)
u2.follow_person(1)
print "User 1 follows {}".format(u1.get_following())
print "User 1's followers {}".format(u1.get_followers())

您可能还需要考虑为传入和传入定义两个单独的关系管理器,这意味着您不需要编写密码查询:

class UserNode(StructuredNode):
    user_id = IntegerProperty(required=True, index=True)
    following = RelationshipTo('UserNode', 'FOLLOW')
    followers = RelationshipFrom('UserNode', 'FOLLOW')

    def follow_person(self, user_id):
        followed_user = self.index.get(user_id=user_id)
        self.follow.connect(followed_user, {'time': str(datetime.datetime.utcnow())})

print "User 1 follows {}".format(u1.following.all())
print "User 1's followers {}".format(u1.followers.all())

希望这可以帮助!如果您还有任何问题,请随时给我发电子邮件。

于 2013-06-03T15:47:42.440 回答