溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

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

發(fā)布時間:2020-07-20 10:46:14 來源:網(wǎng)絡 閱讀:251 作者:foxyier 欄目:編程語言

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


-*- 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  # 用來統(tǒng)計刪除坐標點次數(shù)及防止棧溢出
def decoordinates(citytest2):
    '''
    名稱: decoordinates
    功能: 添加坐標索引,若發(fā)生坐標沖突,則刪除靠后的坐標,直至成功(坐標點相同問題尚未添加)
    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)
向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI