python实现mongo自动添加地图索引, 自动修正遇到的问题
mongo添加地图索引时常会遇到两个问题: 坐标点冲突和坐标点重合, 所以之前写了个脚本解决一下, 主要思路就是:
当添加地图索引报错时, 根据error信息,判断坐标点冲突or 坐标点重合的地方, 根据正则修正坐标点, 然后通过递归or循环的方式, 重新尝试, 代码如下:
-*- coding: utf-8 -*-import pymongoimport reconn = 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)
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。