driver = GraphDatabase.driver("neo4j://localhost:7687") # 从Neo4j数据库中读取实体及其属性 #景点实体 with driver.session() as session: result = session.run("MATCH (n:attraction) RETURN n.id as id, n.name as name, n.time_reference as time_reference, n.address as address, n.open_time as open_time, n.ticket as ticket, n.region as region, n.lon as lon,n.lat as lat").data() # 将实体转换为图形结构 G = nx.Graph() for record in result: node_id = str(uuid.uuid4()) G.add_node(node_id, name=record["name"], time_reference=record["time_reference"], address=record["address"],open_time=record["open_time"],ticket=record["ticket"],region=record["region"],lon=record["lon"],lat=record["lat"])attributes = nx.get_node_attributes(G, node_id) attributes为什么输出实体属性是空值
时间: 2024-03-05 10:51:47 浏览: 153
在你的代码中,变量node_id在每次迭代时都被重新赋值为新的uuid.uuid4(),这就导致了每个节点的id都是唯一的,但是你只能获取最后一个节点的属性,因为在最后一次迭代后,node_id被赋值为最后一个节点的id。因此,当你在使用nx.get_node_attributes()方法时,只能获取最后一个节点的属性,其他节点的属性将无法获取。要解决这个问题,你需要在添加节点时将node_id与节点属性关联起来,可以使用一个字典来存储节点id和属性的键值对,这样就可以根据节点id获取其属性了。以下是修改后的代码示例:
```python
driver = GraphDatabase.driver("neo4j://localhost:7687")
# 从Neo4j数据库中读取实体及其属性 #景点实体
with driver.session() as session:
result = session.run("MATCH (n:attraction) RETURN n.id as id, n.name as name, n.time_reference as time_reference, n.address as address, n.open_time as open_time, n.ticket as ticket, n.region as region, n.lon as lon,n.lat as lat").data()
# 将实体转换为图形结构
G = nx.Graph()
node_attr_dict = {} # 存储节点属性的字典
for record in result:
node_id = str(uuid.uuid4())
G.add_node(node_id) # 添加节点
node_attr_dict[node_id] = {'name': record["name"], 'time_reference': record["time_reference"], 'address': record["address"], 'open_time': record["open_time"], 'ticket': record["ticket"], 'region': record["region"], 'lon': record["lon"], 'lat': record["lat"]} # 存储节点属性
nx.set_node_attributes(G, node_attr_dict) # 将节点属性与图关联起来
attributes = nx.get_node_attributes(G, node_id)
```
这样,你就可以通过节点id获取其属性了。
阅读全文