uo_atlas_import.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. import os
  2. import random
  3. import time
  4. from datetime import datetime
  5. import pymongo
  6. from pymongo.errors import PyMongoError, ServerSelectionTimeoutError, BulkWriteError
  7. # import pandas as pd
  8. from config import atlas_config, mongo_config, atlas_table, mongo_table_uo, uo_city_pairs_old, uo_city_pairs_new
  9. def import_flight_range_status(atlas_db, mongo_db, city_pair, create_at_begin_stamp, create_at_end_stamp,
  10. limit=0, max_retries=3, base_sleep=1.0, out_table=None):
  11. """
  12. 从atlas查询指定城市对、时间范围的航班状态数据,写入mongo集合。
  13. :param atlas_db: atlas数据库连接
  14. :param mongo_db: mongo数据库连接
  15. :param city_pair: 城市对(例如:"BJSBKK")
  16. :param create_at_begin_stamp: 查询开始时间戳(秒级)
  17. :param create_at_end_stamp: 查询结束时间戳(秒级)
  18. :param limit: 限制返回结果数量(0表示不限制)
  19. :param max_retries: 最大重试次数
  20. :param base_sleep: 基础重试间隔(秒)
  21. :param out_table: 目标mongo集合名称(默认:mongo_table_uo)
  22. """
  23. for attempt in range(1, max_retries + 1):
  24. try:
  25. print(f"🔁 第 {attempt}/{max_retries} 次尝试查询")
  26. src_collection = atlas_db[atlas_table] # 源集合(atlas)
  27. out_collection = mongo_db[mongo_table_uo] # 目标集合(mongo)
  28. # 聚合查询管道
  29. pipeline = [
  30. {
  31. "$match": {
  32. "citypair": city_pair,
  33. "from_date": {"$ne": None},
  34. "flight_weight": {"$regex": r"^UO.*(0;0|1;20)$"}, # 使用$regex进行正则匹配
  35. "create_at": {"$gte": create_at_begin_stamp, "$lte": create_at_end_stamp}
  36. }
  37. },
  38. {
  39. "$addFields": {
  40. "create_at_readable": {
  41. "$toDate": {"$multiply": ["$create_at", 1000]}
  42. }
  43. }
  44. },
  45. {
  46. "$sort": {"from_date": 1, "create_at": 1}
  47. }
  48. ]
  49. if limit > 0:
  50. pipeline.append({"$limit": limit})
  51. # 执行查询
  52. t1 = time.time()
  53. results = list(src_collection.aggregate(pipeline))
  54. t2 = time.time()
  55. rt = round(t2 - t1, 3)
  56. print(f"查询用时: {rt} 秒")
  57. # 写入结果(不落原表 _id/source_id,用业务字段做去重)
  58. upserted = 0
  59. matched = 0
  60. write_failed = 0
  61. batch_size = 500
  62. ops = []
  63. def flush_ops(ops_to_flush):
  64. nonlocal upserted, matched, write_failed
  65. if not ops_to_flush:
  66. return
  67. try:
  68. bulk_res = out_collection.bulk_write(ops_to_flush, ordered=False)
  69. upserted += bulk_res.upserted_count
  70. matched += bulk_res.matched_count
  71. except BulkWriteError as e:
  72. details = e.details or {}
  73. write_failed += len(details.get("writeErrors", []))
  74. upserted += details.get("nUpserted", 0)
  75. matched += details.get("nMatched", 0)
  76. except (ServerSelectionTimeoutError, PyMongoError) as e:
  77. write_failed += len(ops_to_flush)
  78. print(f"⚠️ Mongo 批量写入失败 {city_pair}: {e}")
  79. if isinstance(e, ServerSelectionTimeoutError):
  80. raise
  81. for i, doc in enumerate(results, start=1):
  82. citypair = doc.get('citypair')
  83. citypair_new = citypair[:3] + '-' + citypair[3:]
  84. from_date = doc.get('from_date')
  85. from_date_new = datetime.strptime(from_date, '%Y%m%d').strftime('%Y-%m-%d')
  86. flight_weight = doc.get('flight_weight')
  87. flight_weight_split = flight_weight.split(';')
  88. flight_numbers_raw = flight_weight_split[0]
  89. flight_numbers_parts = [x.strip() for x in flight_numbers_raw.split(',') if x.strip()]
  90. flight_numbers = ','.join(flight_numbers_parts)
  91. baggage_weight = int(flight_weight_split[-1])
  92. deptime = doc.get('depTime', '')
  93. if deptime:
  94. from_time = datetime.strptime(deptime, '%Y%m%d%H%M').strftime('%Y-%m-%d %H:%M:%S')
  95. else:
  96. from_time = '' # 3月16之前抓的数据没有起飞时间
  97. trip_type = doc.get('trip_type')
  98. cabin_raw = doc.get('cabin', '')
  99. cabin_parts = [x.strip() for x in cabin_raw.split(',') if x.strip()]
  100. cabins = ','.join(cabin_parts)
  101. ticket_amount = doc.get('ticket_amount')
  102. currency = doc.get('vendorCurrency', '')
  103. price_base = doc.get('price')
  104. price_tax = doc.get('tax')
  105. price_total = doc.get('total')
  106. create_at = doc.get('create_at')
  107. create_at_readable = doc.get('create_at_readable')
  108. create_time = create_at_readable.strftime('%Y-%m-%d %H:%M:%S')
  109. new_doc = {
  110. "citypair": citypair_new,
  111. "from_date": from_date_new,
  112. "flight_numbers": flight_numbers,
  113. "from_time": from_time,
  114. "trip_type": trip_type,
  115. "cabins": cabins,
  116. "baggage_weight": baggage_weight,
  117. "ticket_amount": ticket_amount,
  118. "currency": currency,
  119. "price_base": price_base,
  120. "price_tax": price_tax,
  121. "price_total": price_total,
  122. "create_at": create_at,
  123. "create_time": create_time,
  124. }
  125. dedup_filter = {
  126. "citypair": citypair_new,
  127. "from_date": from_date_new,
  128. "create_at": create_at,
  129. "flight_numbers": flight_numbers,
  130. "baggage_weight": baggage_weight,
  131. }
  132. # try:
  133. # res = out_collection.update_one(dedup_filter, {"$set": new_doc}, upsert=True)
  134. # except (ServerSelectionTimeoutError, PyMongoError) as e:
  135. # write_failed += 1
  136. # print(f"⚠️ Mongo 写入失败 {city_pair} [{i}/{len(results)}]: {e}")
  137. # if isinstance(e, ServerSelectionTimeoutError):
  138. # raise
  139. # continue
  140. # if res.upserted_id is not None:
  141. # upserted += 1
  142. # else:
  143. # matched += res.matched_count
  144. ops.append(pymongo.UpdateOne(dedup_filter, {"$set": new_doc}, upsert=True))
  145. if len(ops) >= batch_size:
  146. flush_ops(ops)
  147. ops = []
  148. if i % 500 == 0:
  149. print(f"写入进度 {city_pair} [{i}/{len(results)}]: upserted={upserted}, matched={matched}, failed={write_failed}")
  150. flush_ops(ops)
  151. print(f"写入集合: {mongo_table_uo}, upserted={upserted}, matched={matched}, failed={write_failed}, total={len(results)}")
  152. return
  153. except (ServerSelectionTimeoutError, PyMongoError) as e:
  154. print(f"⚠️ Mongo 处理失败(查询/写入): {e}")
  155. if attempt == max_retries:
  156. print("❌ 达到最大重试次数,放弃")
  157. return
  158. # 指数退避 + 随机抖动
  159. sleep_time = base_sleep * (2 ** (attempt - 1)) + random.random()
  160. print(f"⏳ {sleep_time:.2f}s 后重试...")
  161. time.sleep(sleep_time)
  162. def mongo_con_parse(config=None):
  163. # if config is None:
  164. # config = mongo_atlas_config.copy()
  165. try:
  166. if config.get("URI", ""):
  167. motor_uri = config["URI"]
  168. client = pymongo.MongoClient(motor_uri, maxPoolSize=100)
  169. db = client[config['db']]
  170. print("motor_uri: ", motor_uri)
  171. else:
  172. client = pymongo.MongoClient(
  173. config['host'],
  174. config['port'],
  175. serverSelectionTimeoutMS=30000, # 30秒
  176. connectTimeoutMS=30000, # 30秒
  177. socketTimeoutMS=30000, # 30秒,
  178. retryReads=True, # 开启重试
  179. maxPoolSize=50
  180. )
  181. db = client[config['db']]
  182. if config.get('user'):
  183. db.authenticate(config['user'], config['pwd'])
  184. print(f"✅ MongoDB 连接对象创建成功")
  185. except Exception as e:
  186. print(f"❌ 创建 MongoDB 连接对象时发生错误: {e}")
  187. raise
  188. return client, db
  189. def main_import_process(create_at_begin, create_at_end):
  190. create_at_begin_stamp = int(datetime.strptime(create_at_begin, "%Y-%m-%d %H:%M:%S").timestamp())
  191. create_at_end_stamp = int(datetime.strptime(create_at_end, "%Y-%m-%d %H:%M:%S").timestamp())
  192. print(f"create_at_begin: {create_at_begin}, timestamp: {create_at_begin_stamp}")
  193. print(f"create_at_end: {create_at_end}, timestamp: {create_at_end_stamp}")
  194. uo_city_pairs = uo_city_pairs_new.copy()
  195. for idx, city_pair in enumerate(uo_city_pairs):
  196. atlas_client, atlas_db = mongo_con_parse(atlas_config)
  197. mongo_client, mongo_db = mongo_con_parse(mongo_config)
  198. print(f"开始处理航线 {idx+1}/{len(uo_city_pairs)}: {city_pair}")
  199. import_flight_range_status(atlas_db, mongo_db, city_pair, create_at_begin_stamp, create_at_end_stamp)
  200. print(f"结束处理航线 {idx+1}/{len(uo_city_pairs)}: {city_pair}")
  201. atlas_client.close()
  202. mongo_client.close()
  203. pass
  204. print("整体结束")
  205. print()
  206. if __name__ == "__main__":
  207. create_at_begin = "2026-03-27 10:00:00"
  208. create_at_end = "2026-03-27 15:59:59"
  209. main_import_process(create_at_begin, create_at_end)
  210. # try:
  211. # client, db = mongo_con_parse(mongo_atlas_config)
  212. # print(f"✅ 数据库连接创建成功")
  213. # except Exception as e:
  214. # print(f"❌ 数据库连接创建失败: {e}")
  215. # db = None