简体   繁体   English

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

[英]How to return the node ID in py2neo (Neo4J & Python)

Currently working with Py2neo to access my Neo4J database.目前正在使用 Py2neo 访问我的 Neo4J 数据库。

I have trouble with returning a node id.我无法返回节点 ID。 I already went through the documentation of Py2neo and read multiple StackOverflow posts but none of them contains a solid answer to my question.我已经阅读了 Py2neo 的文档并阅读了多个 StackOverflow 帖子,但没有一个包含对我的问题的可靠答案。 I think more people could use this solution.我认为更多的人可以使用这个解决方案。

I'm able to locate the node using NodeMatcher我可以使用 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'})

How can I extract the Node ID (_6)?如何提取节点 ID (_6)?

The desired output would be所需的 output 将是

print(find_ingredient)
>>> 6 

(_6 is also fine) (_6也可以)


Second approach: I've added a property called 'ing_id'第二种方法:我添加了一个名为“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')}]

The desired output would be所需的 output 将是

print(ing_id)
>>> 1 

What code do I need to add to achieve this?我需要添加什么代码来实现这一点? Or is there an alternative (or better approach) to easily return the node id?或者是否有替代(或更好的方法)可以轻松返回节点 ID?

Help is much appreciated非常感谢帮助

This solved the problem.这解决了问题。 I hope this will help someone in the future.我希望这对将来的某人有所帮助。

#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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM