【问题标题】:py2neo node accessed by id returns different object than node accessed by index通过 id 访问的 py2neo 节点返回的对象与通过索引访问的节点不同
【发布时间】:2014-03-26 14:27:33
【问题描述】:

我正在使用 py2neo 1.6.4 和 neo4j 2.0.1,我发现访问索引节点时有些奇怪。特别是,通过 index 访问的索引节点不会返回与通过 id 访问的节点相同的对象。

例如:

>>> graph_db.get_or_create_indexed_node('index','key',1)
Node('http://localhost:7474/db/data/node/1')
>>> graph_db.get_indexed_node('index','key',1)
Node('http://localhost:7474/db/data/node/1')   #get works fine after create
>>> graph_db.get_indexed_node('index','key',1).exists
True                                 #the node exists in the db
>>> graph_db.get_indexed_node('index','key',1)._id
1                                    #the id for the node
>>> graph_db.node(1)
Node('http://localhost:7474/db/node/ #note that this is different than the query on the index
>>> graph_db.node(1).exists
False                                #node does not exist in db when accessed by id

所以当被 id 访问时返回的节点实际上并不存在于数据库中,即使返回的 id 正是分配给索引节点的那个。

我对 neo4j 和 py2neo 都相当陌生,并且对索引没有非常复杂的理解,所以如果有一个答案可以帮助教育我和其他人,那就太好了,如果这代表一个错误,会也很高兴知道:)

谢谢!

【问题讨论】:

    标签: py2neo neo4j


    【解决方案1】:

    我并不完全熟悉 py2neo 如何确定数据库中是否存在节点,但您可能想尝试使用 Neo4j 2.0.0 中引入的新索引。您在此处使用的索引是需要您手动保持最新的旧索引,并且围绕它们的操作有几个警告。新索引会自动保持最新,并且更多地作为查询的优化,就像索引在关系数据库中的工作方式一样。

    我不确定 py2neo 如何或是否直接公开这些索引,但您可以通过 py2neos cypher API 访问它们。在处理 neo4j 服务器时,使用 cypher 查询语言通常是一个更好的主意,因为它允许您发送更大的域工作块以在数据库中完成,而不是一次从一个 http 调用中提取数据并执行在客户端工作。

    例如:

    from py2neo import cypher
    
    session = cypher.Session("http://localhost:7474")
    tx = session.create_transaction()
    
    # Create an index
    tx.append("CREATE INDEX ON :User(name)")
    tx.commit()
    
    # Query that will use the index for lookup
    tx = session.create_transaction()
    tx.append("MATCH (n:User) WHERE n.name='Cat Stevens' RETURN n")
    results = tx.execute()
    

    【讨论】:

    • 虽然这并不能完全解决有问题的行为,但它确实提出了一个更好的替代方案,它不存在相同的问题——在我的书中听起来是正确的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 2017-03-24
    • 1970-01-01
    相关资源
    最近更新 更多