首页 > 解决方案 > 如何索引 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_wordsor的错误key too large to index。有没有办法用索引做到这一点?还是应该改变我的方法来解决问题(也许重新设计数据库)?

标签: pythonmongodbindexingmongodb-querypymongo

解决方案


要被索引,您需要将动态数据保存在对象的值中,而不是键中。所以我建议你修改你的模式,看起来像:

{
    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)])

推荐阅读