cpa_agg.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. # -*- coding: utf-8 -*-
  2. # @Time : 2022/12/1 14:46
  3. # @Author : XuJiakai
  4. # @File : cpa_agg
  5. # @Software: PyCharm
  6. import json
  7. import time, queue
  8. from threading import Thread
  9. from utils.datetime_utils import datetime_format
  10. from log import get_log
  11. from sdk.WinhcAllClient import get_all_client
  12. from utils.datetime_utils import get_ds, get_now, datetime_format_transform
  13. from utils import map_2_json_str, json_path
  14. from utils.base_utils import tuple_max
  15. from utils.mysql_utils import insert_many
  16. from utils.xxl_queue import xxl_queue
  17. import re
  18. import sys
  19. import argparse
  20. from project_const import TOPIC_NAME, MONGODB_NAME
  21. date_part = re.compile('\\d{4}年\\d{2}月\\d{2}日')
  22. all_client = get_all_client()
  23. col = all_client.get_mongo_collection(MONGODB_NAME)
  24. del_col = all_client.get_mongo_collection(MONGODB_NAME + '_del')
  25. log = get_log('cpa_agg')
  26. holo_client = all_client.get_holo_client(db='winhc_biz')
  27. HOLO_TABLE_NAME = 'public.ads_waa_dim_info'
  28. def get_max_data(data: list, key: str, exclude_product_name: list = ['winhc']):
  29. max_data = None
  30. for i in data:
  31. tmp_v = json_path(i, key)
  32. if tmp_v is None:
  33. continue
  34. product_name = i['competitor_product_name']
  35. if product_name in exclude_product_name:
  36. continue
  37. pass
  38. if max_data is None:
  39. max_data = (tmp_v, product_name)
  40. else:
  41. max_data = tuple_max(max_data, (tmp_v, product_name))
  42. if max_data is None:
  43. return None, None
  44. return max_data
  45. def get_all_data_by_item(data: list, key):
  46. result_data = {}
  47. for i in data:
  48. result_data[i['competitor_product_name']] = json_path(i, key)
  49. return result_data
  50. def data_transform(data: list):
  51. log.info('input data: {}'.format(data))
  52. deleted_key = [i['_id'] for i in data][0]
  53. deleted_key = deleted_key[:deleted_key.rfind('_')]
  54. base_info = data[0]['base_info']
  55. ds = get_ds()
  56. key_set = set()
  57. winhc_data = None
  58. for i in data:
  59. key_set = key_set | set(i['summary'].keys())
  60. key_set = key_set | set(i['latest_date'].keys())
  61. if i['competitor_product_name'] == 'winhc':
  62. winhc_data = i
  63. pass
  64. pass
  65. if winhc_data is None:
  66. return
  67. li = []
  68. winhc_spider_date = winhc_data['spider_date']
  69. holo_keys = None
  70. for i in key_set:
  71. tmp_json = base_info.copy()
  72. summary_max, summary_max_p_name = get_max_data(data, "$.summary." + i)
  73. latest_date_max, latest_date_max_p_name = get_max_data(data, "$.latest_date." + i)
  74. winhc_dim_num = json_path(winhc_data, '$.summary.' + i)
  75. latest_date_max = datetime_format(latest_date_max)
  76. winhc_dim_date = json_path(winhc_data, '$.latest_date.' + i)
  77. if winhc_dim_date is not None and winhc_dim_date == '':
  78. winhc_dim_date = None
  79. winhc_dim_date = datetime_format(winhc_dim_date)
  80. if (latest_date_max is None or latest_date_max == '') and (
  81. summary_max is None or summary_max == 0) and winhc_dim_date is None and (
  82. winhc_dim_num is None or winhc_dim_num == 0):
  83. # print('这个维度为空...', i, )
  84. continue
  85. pass
  86. if winhc_spider_date is None:
  87. winhc_spider_date = get_now()
  88. other_data = {
  89. "id": tmp_json['company_id'] + "_" + ds + "_" + i,
  90. "dim_name": i,
  91. "dim_max_num": summary_max,
  92. "dim_max_num_business_name": summary_max_p_name,
  93. "winhc_dim_num": winhc_dim_num,
  94. "dim_max_date": latest_date_max,
  95. "dim_max_date_business_name": latest_date_max_p_name,
  96. "winhc_dim_date": winhc_dim_date,
  97. "other_info": json.dumps({"summary": get_all_data_by_item(data, '$.summary.' + i),
  98. 'latest_date': get_all_data_by_item(data, '$.latest_date.' + i)}),
  99. "update_time": winhc_spider_date,
  100. "create_time": winhc_spider_date,
  101. "ds": ds,
  102. }
  103. tmp_json.update(other_data)
  104. li.append(tmp_json)
  105. if holo_keys is None:
  106. holo_keys = list(tmp_json.keys())
  107. pass
  108. log.info('output data: {}'.format(li))
  109. if li is not None and len(li) > 0:
  110. insert_many(li, holo_keys, HOLO_TABLE_NAME, holo_client)
  111. del_num = 0
  112. try:
  113. del_col.insert_many(data, ordered=False)
  114. del_num = col.delete_many({"_id": {"$regex": "^" + deleted_key}}).deleted_count
  115. except:
  116. pass
  117. log.info("deleted mongo _id: {} , deleted count: {}".format(deleted_key, del_num))
  118. return li
  119. q = queue.Queue(5000)
  120. class Work(Thread):
  121. def run(self):
  122. while True:
  123. data_transform(q.get())
  124. today_ds = get_ds()
  125. scan_ds = today_ds[:-2]
  126. def overwrite_handle(key, obj_list):
  127. if obj_list is None or len(obj_list) == 0:
  128. return
  129. _id = obj_list[0]['_id']
  130. if not key.startswith(today_ds) and len(obj_list) == 1:
  131. deleted_count = col.delete_one({'_id': _id}).deleted_count
  132. log.info(f"delete id: {_id} , {deleted_count}")
  133. else:
  134. # log.info(f"skip :{_id}")
  135. pass
  136. pass
  137. def main(max_round: int = 2, interval_of_sed: int = 300):
  138. thread_num = 10
  139. for i in range(thread_num):
  140. w = Work()
  141. w.setDaemon(True)
  142. w.start()
  143. pass
  144. round_num = 0
  145. while True:
  146. round_num += 1
  147. log.info('{},第{}遍轮循...'.format(scan_ds, round_num))
  148. xxl_q = xxl_queue(pop_threshold=2, overwrite_handle=overwrite_handle)
  149. # for i in col.find({"_id": {"$regex": "^" + ds}}).batch_size(200):
  150. for i in col.find({"_id": {"$regex": "^" + scan_ds}}).batch_size(200):
  151. # for i in col.find().batch_size(200):
  152. _id = i['_id']
  153. key = _id[:_id.rfind('_')]
  154. result = xxl_q.append(key=key, obj=i)
  155. if result:
  156. q.put(result)
  157. pass
  158. if round_num >= max_round:
  159. # sys.exit(0)
  160. break
  161. try:
  162. log.info('{},第{}遍轮循结束.'.format(scan_ds, round_num))
  163. time.sleep(interval_of_sed)
  164. pass
  165. except:
  166. pass
  167. pass
  168. pass
  169. if __name__ == '__main__':
  170. # test()
  171. #
  172. log.info(f"input args: {sys.argv}")
  173. parser = argparse.ArgumentParser()
  174. parser.add_argument("-m", "--max-round", type=int, default=2, help='最大迭代轮次')
  175. parser.add_argument("-i", "--interval_of_sed", type=int, default=300, help='每轮间隔时间(秒)')
  176. args = parser.parse_args()
  177. main(max_round=args.max_round, interval_of_sed=args.interval_of_sed)
  178. while not q.empty():
  179. log.info(f"遍历未结束,队列剩余:{q.qsize()}")
  180. time.sleep(300)
  181. pass
  182. log.info(f"遍历完成,队列剩余:{q.qsize()}")
  183. pass