python實現mongo自動添加地圖索引, 自動修正遇到的問題

mongo添加地圖索引時常會遇到兩個問題: 座標點衝突和座標點重合, 所以之前寫了個腳本解決一下, 主要思路就是:
當添加地圖索引報錯時, 根據error信息,判斷座標點衝突or 座標點重合的地方, 根據正則修正座標點, 然後通過遞歸or循環的方式, 重新嘗試, 代碼如下:


-*- coding: utf-8 -*-
import pymongo
import re

conn = pymongo.MongoClient(host='127.0.0.1', port=27017)
citytest2 = conn."db_name"."collection_name"  # 連接表
i = 0  # 用來統計刪除座標點次數及防止棧溢出
def decoordinates(citytest2):
    '''
    名稱: decoordinates
    功能: 添加座標索引,若發生座標衝突,則刪除靠後的座標,直至成功(座標點相同問題尚未添加)
    return: None
    '''
    try:
        global i
        citytest2.create_index([("polygons", "2dsphere")])
        print(i)
    except Exception as e:
        global i
        e = str(e)
        retest = re.compile(r'\[(.*?)\]')
        if "Duplicate vertices" in str(e):  # 座標重合問題
            retest2 = re.compile(r'and (\d+)')
            test2 = int(retest2.findall(str(e))[0])   # 獲取出錯在第幾條
print test2
        elif "locations in degrees" in str(e):  # 座標衝突問題
            retest2 = re.compile(r'(\d+?)\s+?cross')
            test2 = retest2.findall(str(e))[0]  # 獲取出錯在第幾條
        i += 1
        idtest = re.compile(r'_id:\s+(\d+)')
        idtest = idtest.findall(str(e))[0]   # 獲取出錯id
        test = ' [' + retest.findall(str(e))[int(test2)].strip() +  '],' # 獲取該條出錯的座標
        errortest = citytest2.find_one({"_id": int(idtest)})
        e = eval(str(errortest).replace(test, ''))
        citytest2.update({"_id": int(idtest)}, e)
        if i < 1000:
            decoordinates(citytest2)
if name == 'main':
    decoordinates(citytest2)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章