py2neo:具有多个键/值的Graph.find_one

Tho*_*rph 5 python neo4j py2neo

我在使用py2neo find和find_one时遇到了一些麻烦(http://py2neo.org/2.0/essentials.html)

我想要的Cypher是:

MATCH (p:Person) WHERE p.name='Alice' AND p.age=22 RETURN p
Run Code Online (Sandbox Code Playgroud)

比如,有多个键/值集(例如,如果图中有多个'Alice').

我的问题是我不知道要给graph.find_one什么,一个有效的代码是:

graph.find_one('Person', 'name', 'Alice')
Run Code Online (Sandbox Code Playgroud)

我想要的是(这不起作用!):

graph.find_one('Person', {'name': 'Alice', 'age': 22}) 
Run Code Online (Sandbox Code Playgroud)

一个可能(坏)的解决方案是创建一个graph.find,然后遍历结果属性并查找年龄,但我不喜欢这个解决方案.

额外奖励: graph.find可以做一些年龄> 25岁的事情吗?


编辑:新的"解决方案"

find_person ="MATCH(p:Person)WHERE p.name = {N} AND p.age = {A} RETURN p"

>>> tx = graph.cypher.begin()
>>> tx.append(find_person, {'N': 'Alice', 'A': 22})
>>> res = tx.process()
>>> print(res[0][0][0])
(n423:Person {age:22,name:"Lisa"})
Run Code Online (Sandbox Code Playgroud)

我不喜欢这个是我想念Note-object,(我并不完全理解RecordListList,以及如何导航它nicley)

ely*_*ase 5

如果您查看源代码,您会发现遗憾的是find并且find_one 不支持该类型的查询.您应该直接使用Cypher接口:

d = {'name': 'Alice', 'age' : 22}

# quote string values
d = {k:"'{}'".format(v) if isinstance(v, basestring) else v 
                     for k,v in d.items()}

cond = ' AND '.join("p.{}={}".format(prop, value) for prop, value in d.items())

query = "MATCH (p:Person) {condition} RETURN p"
query = query.format(condition=cond)
# "MATCH (p:Person) p.age=22 AND p.name='Alice' RETURN p"
results = graph.cypher.execute(query)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你的回答。我必须在模板查询中添加“WHERE”才能使其正常工作。(即`query = "MATCH (p:Person) WHERE {condition} RETURN p"`) (2认同)

Tho*_*rph 2

基于 @elyase 答案和原始 py2neo.Graph.find,我编写了这段代码。请随时发表评论并改进..:-)

def find_dict(graph, label, key_value=None, limit=None):
    """ Iterate through a set of labelled nodes, optionally filtering
    by property key/value dictionary
    """
    if not label:
        raise ValueError("Empty label")
    from py2neo.cypher.lang import cypher_escape
    if key_value is None:
        statement = "MATCH (n:%s) RETURN n,labels(n)" % cypher_escape(label)
    else:
        # quote string values
        d = {k: "'{}'".format(v) if isinstance(v, str) else v
             for k, v in key_value.items()}

        cond = ""
        for prop, value in d.items():
            if not isinstance(value, tuple):
                value = ('=', value)

            if cond == "":
                cond += "n.{prop}{value[0]}{value[1]}".format(
                    prop=prop,
                    value=value,
                )
            else:
                cond += " AND n.{prop}{value[0]}{value[1]}".format(
                    prop=prop,
                    value=value,
                )

        statement = "MATCH (n:%s ) WHERE %s RETURN n,labels(n)" % (
            cypher_escape(label), cond)
    if limit:
        statement += " LIMIT %s" % limit
    response = graph.cypher.post(statement)
    for record in response.content["data"]:
        dehydrated = record[0]
        dehydrated.setdefault("metadata", {})["labels"] = record[1]
        yield graph.hydrate(dehydrated)
    response.close()


def find_dict_one(graph, label, key_value=None):
    """ Find a single node by label and optional property. This method is
    intended to be used with a unique constraint and does not fail if more
    than one matching node is found.
    """
    for node in find_dict(graph, label, key_value, limit=1):
        return node
Run Code Online (Sandbox Code Playgroud)

find_dict_one 的使用:

>>> a = find_dict_one(graph, 'Person', {'name': 'Lisa', 'age': 23})
>>>     print(a)
(n1:Person {age:23,name:"Lisa"})
Run Code Online (Sandbox Code Playgroud)

将 find_dict 与元组一起使用:

>>> a = find_dict(graph, 'Person', {'age': ('>', 21)}, 2)    >>> for i in a:
>>>     print(i)
(n2:Person {age:22,name:"Bart"})
(n1:Person {age:23,name:"Lisa"})
Run Code Online (Sandbox Code Playgroud)

使用不带元组的 find_dict:

>>> a = find_dict(graph, 'Person', {'age': 22}, 2)    >>> for i in a:
>>>     print(i)
(n2:Person {age:22,name:"Bart"})
Run Code Online (Sandbox Code Playgroud)