uo_atlas_import.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. import os
  2. import random
  3. import time
  4. from datetime import datetime
  5. import pymongo
  6. from pymongo.errors import PyMongoError, ServerSelectionTimeoutError
  7. # import pandas as pd
  8. from config import atlas_config, mongo_config, atlas_table, mongo_table_uo, uo_city_pairs
  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. # 执行查询
  50. t1 = time.time()
  51. results = list(src_collection.aggregate(pipeline))
  52. t2 = time.time()
  53. rt = round(t2 - t1, 3)
  54. print(f"查询用时: {rt} 秒")
  55. # 写入结果(不落原表 _id/source_id,用业务字段做去重)
  56. upserted = 0
  57. matched = 0
  58. write_failed = 0
  59. for i, doc in enumerate(results, start=1):
  60. citypair = doc.get('citypair')
  61. citypair_new = citypair[:3] + '-' + citypair[3:]
  62. from_date = doc.get('from_date')
  63. from_date_new = datetime.strptime(from_date, '%Y%m%d').strftime('%Y-%m-%d')
  64. flight_weight = doc.get('flight_weight')
  65. flight_weight_split = flight_weight.split(';')
  66. flight_numbers_raw = flight_weight_split[0]
  67. flight_numbers_parts = [x.strip() for x in flight_numbers_raw.split(',') if x.strip()]
  68. flight_numbers = ','.join(flight_numbers_parts)
  69. baggage_weight = int(flight_weight_split[-1])
  70. deptime = doc.get('depTime', '')
  71. if deptime:
  72. from_time = datetime.strptime(deptime, '%Y%m%d%H%M').strftime('%Y-%m-%d %H:%M:%S')
  73. else:
  74. from_time = '' # 3月16之前抓的数据没有起飞时间
  75. trip_type = doc.get('trip_type')
  76. cabin_raw = doc.get('cabin', '')
  77. cabin_parts = [x.strip() for x in cabin_raw.split(',') if x.strip()]
  78. cabins = ','.join(cabin_parts)
  79. ticket_amount = doc.get('ticket_amount')
  80. currency = doc.get('vendorCurrency', '')
  81. price_base = doc.get('price')
  82. price_tax = doc.get('tax')
  83. price_total = doc.get('total')
  84. create_at = doc.get('create_at')
  85. create_at_readable = doc.get('create_at_readable')
  86. create_time = create_at_readable.strftime('%Y-%m-%d %H:%M:%S')
  87. new_doc = {
  88. "citypair": citypair_new,
  89. "from_date": from_date_new,
  90. "flight_numbers": flight_numbers,
  91. "from_time": from_time,
  92. "trip_type": trip_type,
  93. "cabins": cabins,
  94. "baggage_weight": baggage_weight,
  95. "ticket_amount": ticket_amount,
  96. "currency": currency,
  97. "price_base": price_base,
  98. "price_tax": price_tax,
  99. "price_total": price_total,
  100. "create_at": create_at,
  101. "create_time": create_time,
  102. }
  103. dedup_filter = {
  104. "citypair": citypair_new,
  105. "from_date": from_date_new,
  106. "create_at": create_at,
  107. "flight_numbers": flight_numbers,
  108. "baggage_weight": baggage_weight,
  109. }
  110. try:
  111. res = out_collection.update_one(dedup_filter, {"$set": new_doc}, upsert=True)
  112. except (ServerSelectionTimeoutError, PyMongoError) as e:
  113. write_failed += 1
  114. print(f"⚠️ Mongo 写入失败 {city_pair} [{i}/{len(results)}]: {e}")
  115. if isinstance(e, ServerSelectionTimeoutError):
  116. raise
  117. continue
  118. if res.upserted_id is not None:
  119. upserted += 1
  120. else:
  121. matched += res.matched_count
  122. print(f"写入集合: {mongo_table_uo}, upserted={upserted}, matched={matched}, failed={write_failed}, total={len(results)}")
  123. return
  124. except (ServerSelectionTimeoutError, PyMongoError) as e:
  125. print(f"⚠️ Mongo 处理失败(查询/写入): {e}")
  126. if attempt == max_retries:
  127. print("❌ 达到最大重试次数,放弃")
  128. return
  129. # 指数退避 + 随机抖动
  130. sleep_time = base_sleep * (2 ** (attempt - 1)) + random.random()
  131. print(f"⏳ {sleep_time:.2f}s 后重试...")
  132. time.sleep(sleep_time)
  133. def mongo_con_parse(config=None):
  134. # if config is None:
  135. # config = mongo_atlas_config.copy()
  136. try:
  137. if config.get("URI", ""):
  138. motor_uri = config["URI"]
  139. client = pymongo.MongoClient(motor_uri, maxPoolSize=100)
  140. db = client[config['db']]
  141. print("motor_uri: ", motor_uri)
  142. else:
  143. client = pymongo.MongoClient(
  144. config['host'],
  145. config['port'],
  146. serverSelectionTimeoutMS=30000, # 30秒
  147. connectTimeoutMS=30000, # 30秒
  148. socketTimeoutMS=30000, # 30秒,
  149. retryReads=True, # 开启重试
  150. maxPoolSize=50
  151. )
  152. db = client[config['db']]
  153. if config.get('user'):
  154. db.authenticate(config['user'], config['pwd'])
  155. print(f"✅ MongoDB 连接对象创建成功")
  156. except Exception as e:
  157. print(f"❌ 创建 MongoDB 连接对象时发生错误: {e}")
  158. raise
  159. return client, db
  160. def main_import_process(create_at_begin, create_at_end):
  161. create_at_begin_stamp = int(datetime.strptime(create_at_begin, "%Y-%m-%d %H:%M:%S").timestamp())
  162. create_at_end_stamp = int(datetime.strptime(create_at_end, "%Y-%m-%d %H:%M:%S").timestamp())
  163. print(f"create_at_begin: {create_at_begin}, timestamp: {create_at_begin_stamp}")
  164. print(f"create_at_end: {create_at_end}, timestamp: {create_at_end_stamp}")
  165. atlas_client, atlas_db = mongo_con_parse(atlas_config)
  166. mongo_client, mongo_db = mongo_con_parse(mongo_config)
  167. for idx, city_pair in enumerate(uo_city_pairs):
  168. print(f"开始处理航线 {idx+1}/{len(uo_city_pairs)}: {city_pair}")
  169. import_flight_range_status(atlas_db, mongo_db, city_pair, create_at_begin_stamp, create_at_end_stamp)
  170. print(f"结束处理航线 {idx+1}/{len(uo_city_pairs)}: {city_pair}")
  171. atlas_client.close()
  172. mongo_client.close()
  173. pass
  174. print("整体结束")
  175. print()
  176. if __name__ == "__main__":
  177. create_at_begin = "2026-02-18 00:00:00"
  178. create_at_end = "2026-02-28 23:59:59"
  179. main_import_process(create_at_begin, create_at_end)
  180. # try:
  181. # client, db = mongo_con_parse(mongo_atlas_config)
  182. # print(f"✅ 数据库连接创建成功")
  183. # except Exception as e:
  184. # print(f"❌ 数据库连接创建失败: {e}")
  185. # db = None