如何在py2neo中返回节点ID(Neo4J和Python)



当前正在使用Py2neo访问我的Neo4J数据库。

我在返回节点id时遇到了问题。我已经阅读了Py2neo的文档,并阅读了多篇StackOverflow帖子,但没有一篇包含我问题的可靠答案。我认为更多的人可以使用这个解决方案。

我可以使用NodeMatcher 定位节点

from py2neo import Graph, NodeMatcher
from py2neo import Node, Relationship
graph = Graph("bolt://localhost:7687")
matcher = NodeMatcher(graph)
find_ingredient = matcher.match("Ingredient", name="Onion").first()
print(find_ingredient)
>>> (_6:Ingredient {name: 'Onion'})

如何提取节点ID(_6(?

所需输出为

print(find_ingredient)
>>> 6 

(_6也可以(


第二种方法:我添加了一个名为"ing_id"的属性

ingredient = graph.run("MATCH (n:Ingredient {name:'Ui'}) WHERE n.name='Ui' RETURN n")
data = ingredient.data()
print(data)
>>>[{'n': Node('Ingredient', ing_id=1, name='Ui')}]

所需输出为

print(ing_id)
>>> 1 

我需要添加什么代码才能实现这一点?或者,是否有一种替代方法(或更好的方法(可以轻松返回节点id?

非常感谢您的帮助

这解决了问题。我希望这对将来的某个人有所帮助。

#retreive the ingredient_id of the last added ingredient in the Neo4j db
def last_ingredient_id():
ingredient = graph.run("MATCH (a:Ingredient) RETURN a.ing_id ORDER BY a.ing_id DESC").to_series()
result = int(ingredient[0])
return result

最新更新