如何将 CSV/TSV 数据导入 Couch DB?
问问题
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 文档,然后正常发布它们。
您可能必须编写一个程序来循环遍历每一行。将 CSV 行(值序列)转换为 JSON 文档(键:值对序列)。然后只需使用 HTTP 将其发送到 CouchDB。
于 2011-03-09T04:37:19.183 回答
3
我在这里使用它:https://github/glynnbird/couchimport。如果您的 CSV 相当简单,则可以归结为设置数据库名称并将 CSV 传送到 couchimport。
于 2016-04-07T15:22:23.700 回答
1
刚刚用 Ruby 写了一个脚本:csv2couchdb
于 2011-09-26T20:30:36.387 回答
0
你好,我创建了这个简单的片段,他非常快速和强大。
import csv
import couchdb #install this library with pip
couch = couchdb.Server('http://user:password@localhost:port') #change user, password and localhost with yours
dbname = #insert a name of the db
db = couch.create(dbname) #create the database
db = couch[dbname]
with open(r'INSERT FILE PATH') as csv_file: #in the '' insert your file path
csv_reader = csv.reader(csv_file, delimiter=',')
keys = next(csv_reader)
line_count = 0
for values in csv_reader:
db.save(dict(zip(keys,values)))
于 2022-02-18T14:59:53.460 回答