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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章