【问题标题】:Create relationship on pre-existing node in py2neo在 py2neo 中的预先存在的节点上创建关系
【发布时间】:2015-12-09 17:43:40
【问题描述】:

我正在尝试在 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 有没有办法找到一个已经存在的节点并在其上建立关系,这样我就可以得到一个更连通的图?

【问题讨论】:

    标签: python neo4j py2neo


    【解决方案1】:

    我认为您正在寻找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 函数,该函数基于为属性指定的标签和键、值充当“获取或创建”:如果匹配的节点存在,它将返回它,否则将创建它并返回。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多