在 py2neo 中的预先存在的节点上创建关系

Create relationship on pre-existing node in py2neo

我正在尝试在 Neo4j 中创建一个简单的图形。我想做的是创建一个节点,如果它不存在,如果它已经存在,我想将一个新节点连接到它而不是创建一个类似的节点。

一个节点是用户节点,其他节点是餐厅名称、菜系和位置。如果一家餐厅提供已经作为节点存在的美食,我想将该餐厅连接到预先存在的美食节点。

def add_restaurant(self, name, cuisine, location):
    user=self.find()
    restaurant = Node("Restaurant", id=str(uuid.uuid4()),name=name)
    #graph.create(restaurant)
    graph.create_unique(rel(user,"LIKES", restaurant))

    rest_type = Node("Cuisine", cuisine=cuisine)
    #graph.create(rest_type)
    graph.create_unique(rel(restaurant,"SERVES", rest_type))

    loc = Node("Location", location=location)
    #graph.create(loc)
    graph.create_unique(rel(restaurant, "IN", loc))

此代码有效,但每次添加美食或位置时都会创建一个新节点。在 py2neo 中有没有办法找到一个已经存在的节点并在其上建立关系,这样我就可以获得一个连接性更强的图?

我认为您正在寻找 graph.merge_one() 函数:

rest_type = graph.merge_one("Cuisine", "cuisine", cuisine)
graph.create_unique(rel(restaurant,"SERVES", rest_type))
loc = graph.merge_one("Location", "location", location)
graph.create_unique(rel(restaurant, "IN", loc))

这使用 MERGE 函数,它根据为 属性 指定的标签和键、值充当 "get or create":如果存在匹配的节点,它将 return 它,如果没有,那么它将被创建并 returned.