CSV / TSVデータをCouchDBにインポートする方法は?
7724 次
5 に答える
7
pythonを使えばかなり簡単です。
#!/usr/bin/env python
from couchdbkit import Server, Database
from couchdbkit.loaders import FileSystemDocsLoader
from csv import DictReader
import sys, subprocess, math, os
def parseDoc(doc):
for k,v in doc.items():
if (isinstance(v,str)):
#print k, v, v.isdigit()
# #see if this string is really an int or a float
if v.isdigit()==True: #int
doc[k] = int(v)
else: #try a float
try:
if math.isnan(float(v))==False:
doc[k] = float(v)
except:
pass
return doc
def upload(db, docs):
db.bulk_save(docs)
del docs
return list()
def uploadFile(fname, uri, dbname):
print 'Upload contents of %s to %s/%s' % (fname, uri, dbname)
# #connect to the db
theServer = Server(uri)
db = theServer.get_or_create_db(dbname)
#loop on file for upload
reader = DictReader(open(fname, 'rU'), dialect = 'excel') #see the python csv module
#for other options, such as using the tab delimeter. The first line in your csv
#file should contain all of the "key" and all subsequent lines hold the values
#for those keys.
#used for bulk uploading
docs = list()
checkpoint = 100
for doc in reader:
newdoc = parseDoc(doc) #this just converts strings that are really numbers into ints and floats
#Here I check to see if the doc is already on the database. If it is, then I assign
#the _rev key so that it updates the doc on the db.
if db.doc_exist(newdoc.get('_id')):
newdoc['_rev'] = db.get_rev(newdoc.get('_id'))
docs.append(newdoc)
if len(docs)%checkpoint==0:
docs = upload(db,docs)
#don't forget the last batch
docs = upload(db,docs)
if __name__=='__main__':
filename = sys.argv[1]
uri = sys.argv[2]
dbname = sys.argv[3]
uploadFile(filename, uri, dbname)
于 2011-03-09T09:33:21.853 に答える
4
Apache CouchDB は JSON ドキュメントのみを保存します。したがって、CSV をインポートするには、個々の JSON ドキュメントに変換してから、通常どおり POST する必要があります。
おそらく、各行をループするプログラムを作成する必要があります。CSV 行 (値のシーケンス) を JSON ドキュメント (キーと値のペアのシーケンス) に変換します。次に、HTTP を使用して CouchDB に送信します。
于 2011-03-09T04:37:19.183 に答える
3
ここでこれを使用します: https://github/glynnbird/couchimport。CSV がかなり単純な場合は、DB 名を設定し、CSV を couchimport にパイプするだけです。
于 2016-04-07T15:22:23.700 に答える
1
Ruby でスクリプトを作成しました: csv2couchdb
于 2011-09-26T20:30:36.387 に答える