[英]Exporting data from neo4j to csv instead of json
我正在使用neo4jdb-python
包來查詢Neo4j數據庫。 例如,考慮以下代碼
import neo4j
connection = neo4j.connect("http://localhost:7474")
cursor = connection.cursor()
for i in cursor.execute("MATCH a RETURN a LIMIT 1"):
print i
但輸出是元組的形式。 即
({u'text': u'Stoyanov, S., Hoogveld, B., Kirschner, P.A., (2010). Mapping Major Changes to Education and Training in 2025, in JRC Technical Note JRC59079., Publications Office of the European Union: Luxembourg.', u'identifier': u'reference/lak/226'},)
如何以csv格式獲得輸出。這可以通過neo4j的Web視圖實現。 輸出就像,
"{""text"":""Stoyanov, S., Hoogveld, B., Kirschner, P.A., (2010). Mapping Major Changes to Education and Training in 2025, in JRC Technical Note JRC59079., Publications Office of the European Union: Luxembourg."",""identifier"":""reference/lak/226""}"
但是我想通過客戶端程序來實現它,因為我需要將它嵌入到另一個程序中。 如果使用neo4jdb-python
是不可能的,那么還有哪些其他選項可用。
Neo4j服務器只返回JSON,正如Mark Needham在他的回答中提到的那樣。
因此,任何將其轉換為CSV的代碼都必須在客戶端。 這可以使用csv模塊完成。 請注意, neo4jdb-python
包僅與Python2.7兼容。
獲取數據的最小代碼是
import neo4j
connection = neo4j.connect("http://localhost:7474")
cursor = connection.cursor()
data = list(cursor.execute("MATCH a RETURN a LIMIT 1")
請注意,如問題中所述,返回值采用元組的形式。 創建csv文件的最小代碼是
with open("test.csv","w") as csvfile:
writer = csv.writer(csvfile,delimiter = ',',quotechar = '"',quoting = csv.QUOTE_ALL)
writer.writerow(t[0].keys())
for i in t:
writer.writerow(['{"%s":"%s"}'%(k,v) for k,v in i.iteritems()])
代碼的解釋很簡單,打開一個文件。 使用csv.writer
創建一個writer
對象。 首先使用writerow
寫入標題。 最后循環遍歷字典並寫入行。
獲得的輸出是
"{""text"":""Stoyanov, S., Hoogveld, B., Kirschner, P.A., (2010). Mapping Major Changes to Education and Training in 2025, in JRC Technical Note JRC59079., Publications Office of the European Union: Luxembourg.""}","{""identifier"":""reference/lak/226""}"
這與使用exportable.coffee
腳本獲得的類似。
該CSV實際上並非來自特定的API - 它在客戶端被翻譯成CSV格式。
如果你想看一下,適當的代碼在exportable.coffee中 :
$scope.exportCSV = (data) ->
return unless data
csv = new CSV.Serializer()
csv.columns(data.columns())
for row in data.rows()
csv.append(row)
這指的是CSV.coffee 。 我想你應該可以在Python中做類似的事情,或許像這樣使用json.dumps :
> import json
> t = ({u'text': u'Stoyanov, S., Hoogveld, B., Kirschner, P.A., (2010). Mapping Major Changes to Education and Training in 2025, in JRC Technical Note JRC59079., Publications Office of the European Union: Luxembourg.', u'identifier': u'reference/lak/226'},)
> json.dumps(t)
'[{"text": "Stoyanov, S., Hoogveld, B., Kirschner, P.A., (2010). Mapping Major Changes to Education and Training in 2025, in JRC Technical Note JRC59079., Publications Office of the European Union: Luxembourg.", "identifier": "reference/lak/226"}]'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.