如何将Neo4j返回类型转换为python类型 [英] How to convert neo4j return types to python types
问题描述
我正在使用py2neo,我想从查询返回中提取信息,以便可以在python中进行处理.例如,我有一个包含三个"Person"节点的数据库:
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
for num in graph.cypher.execute("MATCH (p:Person) RETURN count(*)"):
print num
输出:
>> count(*)
3
很抱歉,格式很糟糕,它看起来与mysql输出基本相同.但是,我想使用数字3进行计算,但是它的类型为py2neo.cypher.core.Record
.如何将其转换为python int,以便可以使用它?从更一般的意义上讲,我应该如何处理密码查询,以便可以在Python中使用返回的数据?
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?
推荐答案
graph.cypher.execute()
返回包含多个Records
的RecordList
.每个Record
都对应于Cypher查询结果的一行.
graph.cypher.execute()
returns a RecordList
containing multiple Records
. Each Record
corresponds to a single line of the result of your Cypher query.
您的RETURN count(*)
查询仅返回一行,因此for num in ...
循环将仅触及RecordList
中的一个Record
.
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
这应该是int
,但是您现在可以使用float()
或int()
将其转换为所需的内容.
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]
第一个[0]
获取结果RecordList
的第一个Record
,第二个[0]
获取Record
的第一列.
The first [0]
gets the first Record
of your resulting RecordList
and the second [0]
gets the first column of the Record
.
看看: http://py2neo.org/2.0/cypher.html#records
这篇关于如何将Neo4j返回类型转换为python类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!