cpa_agg.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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
  8. from log import get_log
  9. from sdk.WinhcAllClient import get_all_client
  10. from utils.datetime_utils import get_ds, get_now, datetime_format_transform
  11. from utils import map_2_json_str, json_path
  12. from utils.base_utils import tuple_max
  13. from utils.mysql_utils import insert_many
  14. from utils.xxl_queue import xxl_queue
  15. import re
  16. import sys
  17. import argparse
  18. from project_const import TOPIC_NAME, MONGODB_NAME
  19. date_part = re.compile('\\d{4}年\\d{2}月\\d{2}日')
  20. all_client = get_all_client()
  21. col = all_client.get_mongo_collection(MONGODB_NAME)
  22. del_col = all_client.get_mongo_collection(MONGODB_NAME + '_del')
  23. log = get_log('cpa_agg')
  24. holo_client = all_client.get_holo_client(db='winhc_biz')
  25. HOLO_TABLE_NAME = 'public.ads_waa_dim_info'
  26. def get_max_data(data: list, key: str, exclude_product_name: list = ['winhc']):
  27. max_data = None
  28. for i in data:
  29. tmp_v = json_path(i, key)
  30. if tmp_v is None:
  31. continue
  32. product_name = i['competitor_product_name']
  33. if product_name in exclude_product_name:
  34. continue
  35. pass
  36. if max_data is None:
  37. max_data = (tmp_v, product_name)
  38. else:
  39. max_data = tuple_max(max_data, (tmp_v, product_name))
  40. if max_data is None:
  41. return None, None
  42. return max_data
  43. def get_all_data_by_item(data: list, key):
  44. result_data = {}
  45. for i in data:
  46. result_data[i['competitor_product_name']] = json_path(i, key)
  47. return result_data
  48. def data_transform(data: list):
  49. log.info('input data: {}'.format(data))
  50. deleted_key = [i['_id'] for i in data][0]
  51. deleted_key = deleted_key[:deleted_key.rfind('_')]
  52. base_info = data[0]['base_info']
  53. ds = get_ds()
  54. key_set = set()
  55. winhc_data = None
  56. for i in data:
  57. key_set = key_set | set(i['summary'].keys())
  58. key_set = key_set | set(i['latest_date'].keys())
  59. if i['competitor_product_name'] == 'winhc':
  60. winhc_data = i
  61. pass
  62. pass
  63. if winhc_data is None:
  64. return
  65. li = []
  66. holo_keys = None
  67. for i in key_set:
  68. tmp_json = base_info.copy()
  69. summary_max, summary_max_p_name = get_max_data(data, "$.summary." + i)
  70. latest_date_max, latest_date_max_p_name = get_max_data(data, "$.latest_date." + i)
  71. if (latest_date_max is None or latest_date_max == '') and (summary_max is None or summary_max == 0):
  72. # print('这个维度为空...', i, )
  73. continue
  74. pass
  75. if latest_date_max is not None and date_part.match(latest_date_max):
  76. latest_date_max = datetime_format_transform(latest_date_max, '%Y年%m月%d日', "%Y-%m-%d %H:%M:%S")
  77. pass
  78. winhc_dim_date = json_path(winhc_data, '$.latest_date.' + i)
  79. if winhc_dim_date is not None and winhc_dim_date == '':
  80. winhc_dim_date = None
  81. if winhc_dim_date is not None and date_part.match(winhc_dim_date):
  82. winhc_dim_date = datetime_format_transform(winhc_dim_date, '%Y年%m月%d日', "%Y-%m-%d %H:%M:%S")
  83. pass
  84. other_data = {
  85. "id": tmp_json['company_id'] + "_" + ds + "_" + i,
  86. "dim_name": i,
  87. "dim_max_num": summary_max,
  88. "dim_max_num_business_name": summary_max_p_name,
  89. "winhc_dim_num": json_path(winhc_data, '$.summary.' + i),
  90. "dim_max_date": latest_date_max,
  91. "dim_max_date_business_name": latest_date_max_p_name,
  92. "winhc_dim_date": winhc_dim_date,
  93. "other_info": json.dumps({"summary": get_all_data_by_item(data, '$.summary.' + i),
  94. 'latest_date': get_all_data_by_item(data, '$.latest_date.' + i)}),
  95. "update_time": get_now(),
  96. "create_time": get_now(),
  97. "ds": ds,
  98. }
  99. tmp_json.update(other_data)
  100. li.append(tmp_json)
  101. if holo_keys is None:
  102. holo_keys = list(tmp_json.keys())
  103. pass
  104. log.info('output data: {}'.format(li))
  105. insert_many(li, holo_keys, HOLO_TABLE_NAME, holo_client)
  106. del_num = 0
  107. try:
  108. del_col.insert_many(data, ordered=False)
  109. del_num = col.delete_many({"_id": {"$regex": "^" + deleted_key}}).deleted_count
  110. except:
  111. pass
  112. log.info("deleted mongo _id: {} , deleted count: {}".format(deleted_key, del_num))
  113. return li
  114. def main(max_round: int = 2, interval_of_sed: int = 300):
  115. round_num = 0
  116. while True:
  117. round_num += 1
  118. ds = get_ds()
  119. # ds = '20221205'
  120. log.info('{},第{}遍轮循...'.format(ds, round_num))
  121. q = xxl_queue(pop_threshold=2)
  122. for i in col.find({"_id": {"$regex": "^" + ds}}).batch_size(200):
  123. _id = i['_id']
  124. key = _id[:_id.rfind('_')]
  125. result = q.append(key=key, obj=i)
  126. if result:
  127. data_transform(result)
  128. pass
  129. if round_num >= max_round:
  130. break
  131. try:
  132. log.info('{},第{}遍轮循结束.'.format(ds, round_num))
  133. time.sleep(interval_of_sed)
  134. pass
  135. except:
  136. pass
  137. pass
  138. pass
  139. if __name__ == '__main__':
  140. log.info(f"input args: {sys.argv}")
  141. parser = argparse.ArgumentParser()
  142. parser.add_argument("-m", "--max-round", type=int, default=2, help='最大迭代轮次')
  143. parser.add_argument("-i", "--interval_of_sed", type=int, default=300, help='每轮间隔时间(秒)')
  144. args = parser.parse_args()
  145. main(max_round=args.max_round, interval_of_sed=args.interval_of_sed)
  146. pass