How to convert neo4j return types to python types

2019-06-02 21:35发布

I am using py2neo and I would like to extract the information from query returns so that I can do stuff with it in python. For example, I have a DB containing three "Person" nodes:

for num in graph.cypher.execute("MATCH (p:Person) RETURN count(*)"): print num

outputs:

>> count(*)

3

Sorry for shitty formatting, it looks essentially the same as a mysql output. However, I would like to use the number 3 for computations, but it has type py2neo.cypher.core.Record. How can I convert this to a python int so that I can use it? In a more general sense, how should I go about processing cypher queries so that the data I get back can be used in Python?

2条回答
唯我独甜
2楼-- · 2019-06-02 22:18

graph.cypher.execute() returns a RecordList containing multiple Records. Each Record corresponds to a single line of the result of your Cypher query.

Your RETURN count(*) query returns only one line, so the for num in ... loop will only touch one Record in your RecordList.

To get data from the columns of a record, you can use indices or column names:

for num in ... :
    your_count = num[0] # gets the first column

This should be an int, but you can now convert it to whatever you need with float() or int().


Your query returns only one line with one column. You can shorten it to:

your_count = graph.cypher.execute("MATCH (p:Person) RETURN count(*)")[0][0]

The first [0] gets the first Record of your resulting RecordList and the second [0] gets the first column of the Record.

Have a look at: http://py2neo.org/2.0/cypher.html#records

查看更多
爷的心禁止访问
3楼-- · 2019-06-02 22:22

can you int(), float() str() on the __str__() method that looks to be outputting the value you want in your example?

查看更多
登录 后发表回答