如何使用python将国家/地区信息有效地添加到mongoDB中包含坐标的文档中?

问题描述

我收集了来自foursquare的值机数据,但是它没有有关值机所在国家/地区的信息,只有坐标。我需要知道我正在帮助开发的模型的国家/地区,因此我编写了此脚本,用于将每个文档(因为我不想弄乱原始数据)复制到具有此添加的国家/地区字段的另一个集合中。

问题是,这运行非常慢。我估计在我的个人计算机上,大约需要48天才能完成。我不会在我的个人计算机上运行它,但是我还是不想花太长时间。如果有什么不同,我打算在其上运行的计算机正在运行mongodb 3.4.7版。如有必要,我可以对其进行更新,但我也宁愿不进行更新。

有什么方法可以更有效地执行此操作,同时确保在程序中途终止时我不必从头开始?

from pymongo import MongoClient,ReplaceOne,errors
from geopy.geocoders import Nominatim

_client = MongoClient(port=27017)
_collection = cliente.large_foursquare2014.checkins.find()
documents = list()

geolocator = Nominatim(user_agent="omitting the name i actually used on purpose")


i = 0
j = 0
for document in _collection:
    i += 1
    if i == 1000:
        print(j)
        j += 1
        cliente.large_foursquare2014.teste.bulk_write(documents)        
        documents.clear()
        i = 0

    address = geolocator.reverse((documento['latitude'],documento['longitude'])).raw['address']
    
    document['country2'] = address['country_code'].upper()
    documents.append(ReplaceOne({'_id': document['_id']},document,upsert=True))

    cliente.large_foursquare2014.teste.bulk_write(documents)

解决方法

瓶颈确实是地理定位器的调用。通过更改为reverse_geocoder程序包,性能提高了大约五倍。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...