python实现mongo自动添加地图索引, 自动修正遇到的问题

发布时间:2020-07-20 10:46:14 作者:foxyier
来源:网络 阅读:241

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)
推荐阅读:
  1. mongo分片丢失分片索引
  2. windows端自动化遇到的问题

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python mongo 递归

上一篇:浅谈Python中的变量

下一篇:HTML5 canvas如何实现绘制矩形

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》