python實現mongo自動添加地圖索引, 自動修正遇到的問題
阿新 • • 發佈:2018-11-09
elif 兩個 刪除 fin create creat con int cati mongo添加地圖索引時常會遇到兩個問題: 坐標點沖突和坐標點重合, 所以之前寫了個腳本解決一下, 主要思路就是:
當添加地圖索引報錯時, 根據error信息,判斷坐標點沖突or 坐標點重合的地方, 根據正則修正坐標點, 然後通過遞歸or循環的方式, 重新嘗試, 代碼如下:
當添加地圖索引報錯時, 根據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)
python實現mongo自動添加地圖索引, 自動修正遇到的問題