You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用py2neo创建知识图谱时出现KeyError: 'location'问题求助

Py2neo连接Neo4j出现KeyError: 'location'的原因分析

问题场景

作为py2neo新手,尝试创建包含Person、animal类型节点及对应关系的知识图谱,核心代码如下:

graph = Graph('http://127.0.0.1:7474/', name="test", password="12345678")
node1 = Node('Person', name='Bob')
graph.create(node1)

完整代码:

from py2neo import Graph, Node, Relationship, NodeMatcher


graph = Graph('http://127.0.0.1:7474/', name="test", password="12345678")

node1 = Node('Person', name='Bob')
node2 = Node('Person', name='Alice')
node3 = Node('animal', name='cat')
node4 = Node('animal', name='dog')

r1 = Relationship(node2, 'know', node1)
r2 = Relationship(node1, 'know', node3)
r3 = Relationship(node2, 'has', node3)
r4 = Relationship(node2, 'has', node4)

graph.create(node1)
graph.create(node2)
graph.create(node3)
graph.create(node4)
graph.create(r1)
graph.create(r2)
graph.create(r3)
graph.create(r4)

matcher = NodeMatcher(graph)
print(list(matcher.match('animal')))

运行时出现KeyError: 'location'错误,详细报错回溯:

Traceback (most recent call last):
  File "D:\PyCharm-workspace\learn_Neo4j\test.py", line 23, in <module>
    graph.create(node4)
  File "D:\python3.8\lib\site-packages\py2neo\database.py", line 591, in create
    self.update(lambda tx: tx.create(subgraph))
  File "D:\python3.8\lib\site-packages\py2neo\database.py", line 445, in update
    self._update(cypher, timeout=timeout)
  File "D:\python3.8\lib\site-packages\py2neo\database.py", line 467, in _update
    tx = self.begin(
  File "D:\python3.8\lib\site-packages\py2neo\database.py", line 351, in begin
    return Transaction(self, autocommit=False, readonly=readonly,
  File "D:\python3.8\lib\site-packages\py2neo\database.py", line 915, in __init__
    self._ref = self._connector.begin(self.graph.name, readonly=readonly,
  File "D:\python3.8\lib\site-packages\py2neo\client\__init__.py", line 1359, in begin
    return cx.begin(graph_name, readonly=readonly,
  File "D:\python3.8\lib\site-packages\py2neo\client\http.py", line 200, in begin
    location_path = urlsplit(r.headers["Location"]).path
  File "D:\python3.8\lib\site-packages\urllib3\_collections.py", line 157, in __getitem__
    val = self._container[key.lower()]
KeyError: 'location'

错误原因

  • 版本不兼容
    这个错误最常见于py2neo 4.x及更早版本连接Neo4j 4.0+版本。Neo4j 4.0+引入了多数据库架构,其HTTP API的事务响应格式发生变化,而旧版py2neo的HTTP客户端逻辑仍期望响应头包含Location字段来获取事务路径,新版本Neo4j不再返回该字段,直接导致KeyError。

  • 数据库名称参数使用错误

    • 若使用的是Neo4j 3.x及更早版本(单数据库模式),Graph初始化时的name参数无效,旧版Neo4j不支持多数据库,该参数会干扰连接逻辑,引发异常。
    • 若使用Neo4j 4.0+版本,指定的test数据库如果未提前创建,连接时会返回错误响应,同样不会包含Location字段,触发报错。
  • 连接字符串格式错误
    py2neo不同版本对多数据库连接的格式要求不同,旧版可能不支持通过name参数指定数据库,正确的多数据库连接应将数据库名嵌入URL路径中(例如http://127.0.0.1:7474/db/test/,具体格式需匹配py2neo版本),错误的参数传递会导致连接逻辑异常。

内容的提问来源于stack exchange,提问作者lambda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 05:05:00