【发布时间】:2014-12-07 00:26:23
【问题描述】:
我目前正在研究是否可以或多或少地直接使用structured numpy arrays 作为 mongodb 插入操作的文档。
在我找到的所有示例中
db.collection.insert(doc)
doc 始终是 Python dict,但我想知道是否没有任何提供 mapping interface 的实例可用于插入操作。
我正在考虑使用DictMixin 或MutableMapping 对np.ndarray 进行子类化,因此它确实提供了一个dict 接口。然后做这样的事情:
structured_array = np.zeros( (5,), dtype=[('i', '<i4'), ('f', '<f4')] )
structured_array['i'] = np.random.randint(42, size=5)
structured_array['f'] = np.random.rand(5)
for row in structured_array:
# row is of type: np.void
# so in order to let pymongo insert it into the DB, I create a
# view of row, which provides the dict-like interface
row_dict_like = row.view(np_array_subclass_providing_dict_interface)
db.collection.insert(row_dict_like)
现在,由于我是一个该死的初学者,并且从未将 np.ndarray 子类化,并且担心我可能会为此浪费很多时间,只是为了以后知道,整个方法不是很聪明,我的问题是: 您认为这种方法存在主要问题吗?它是 Pythonic 的吗?我的假设是,任何提供映射接口的类都可以用于 mongodb 插入操作,完全正确吗?
【问题讨论】:
-
好像可以,你需要的功能在
numpy.lib.recfunctions -
我想看看 blaze:continuum.io/blog/blaze-hmda
标签: python arrays mongodb numpy pymongo