python - 如何索引 PyMongo 中已知字段的未知字段?
问题描述
我试图在数百万条推文中找到独特的单词,并且我想保留每个单词出现的位置。除此之外,我还按它们的首字母对单词进行分组。这是一个示例代码:
from pymongo import UpdateOne
# connect to db stuff
for word in words: # this is actually not the real loop I've used but it fits for this example
# assume tweet_id's and position is calculated here
initial = word[0]
ret = {"tweet_id": tweet_id, "pos": (beg, end)} # additional information about word
command = UpdateOne({"initial": initial}, {"$inc": {"count": 1}, "$push": {"words.%s" % word: ret}}, upsert=True)
commands.append(command)
if len(commands) % 1000 == 0:
db.tweet_words.bulk_write(commands, ordered=False)
commands = []
但是,分析所有这些推文的速度很慢。我猜我的问题是因为我没有在words
字段上使用索引。
以下是文档的示例输出:
{
initial: "t"
count: 3,
words: {
"the": [{"tweet_id": <some-tweet-id>, "pos": (2, 5)},
{"tweet_id": <some-other-tweet-id>, "pos": (9, 12)}]
"turkish": [{"tweet_id": <some-tweet-id>, "pos": (5, 11)}]
}
}
我尝试使用以下代码创建索引(不成功):
db.tweet_words.create_index([("words.$**", pymongo.TEXT)])
或者
db.tweet_words.create_index([("words", pymongo.HASHED)])
我有类似add index fails, too many indexes for twitter.tweet_words
or的错误key too large to index
。有没有办法用索引做到这一点?还是应该改变我的方法来解决问题(也许重新设计数据库)?
解决方案
要被索引,您需要将动态数据保存在对象的值中,而不是键中。所以我建议你修改你的模式,看起来像:
{
initial: "t"
count: 3,
words: [
{value: "the", tweets: [{"tweet_id": <some-tweet-id>, "pos": (2, 5)},
{"tweet_id": <some-other-tweet-id>, "pos": (9, 12)}]},
{value: "turkish", tweets: [{"tweet_id": <some-tweet-id>, "pos": (5, 11)}]}
]
}
然后您可以将其索引为:
db.tweet_words.create_index([("words.value", pymongo.TEXT)])
推荐阅读
- python - 无法使用 StackingCVClassifier 拟合元分类器
- windows - 如何使用 CA 根密钥签署 .csr 请求
- angular - ng update @angular/cli 返回错误:getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:80
- c# - 如何提取对象数组的名称和值?
- r - 查找聚集方法的准确性?
- django - Django runserver 在启动期间抛出错误
- git - Jenkins 错误 - ssh:连接到主机端口 22:连接被拒绝
- perl - 如何使用 Perl(系统)使用包含元字符的参数执行外部程序“
- jwt - 为什么将 JWT 拆分为三个以点分隔的部分?
- excel - 如何在 Excel 中使用 VBA 向表中添加一行,其中第一列具有递增索引