database_dml.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. from pymongo import MongoClient, UpdateOne
  2. import pandas as pd
  3. from scripts.regsetup import description
  4. from sqlalchemy import create_engine
  5. import pickle
  6. from io import BytesIO
  7. import joblib
  8. import h5py
  9. import tensorflow as tf
  10. def get_data_from_mongo(args):
  11. mongodb_connection = "mongodb://root:sdhjfREWFWEF23e@192.168.1.43:30000/"
  12. mongodb_database = args['mongodb_database']
  13. mongodb_read_table = args['mongodb_read_table']
  14. query_dict = {}
  15. if 'timeBegin' in args.keys():
  16. timeBegin = args['timeBegin']
  17. query_dict.update({"$gte": timeBegin})
  18. if 'timeEnd' in args.keys():
  19. timeEnd = args['timeEnd']
  20. query_dict.update({"$lte": timeEnd})
  21. client = MongoClient(mongodb_connection)
  22. # 选择数据库(如果数据库不存在,MongoDB 会自动创建)
  23. db = client[mongodb_database]
  24. collection = db[mongodb_read_table] # 集合名称
  25. if len(query_dict) != 0:
  26. query = {"dateTime": query_dict}
  27. cursor = collection.find(query)
  28. else:
  29. cursor = collection.find()
  30. data = list(cursor)
  31. df = pd.DataFrame(data)
  32. # 4. 删除 _id 字段(可选)
  33. if '_id' in df.columns:
  34. df = df.drop(columns=['_id'])
  35. client.close()
  36. return df
  37. def get_df_list_from_mongo(args):
  38. mongodb_connection,mongodb_database,mongodb_read_table = "mongodb://root:sdhjfREWFWEF23e@192.168.1.43:30000/",args['mongodb_database'],args['mongodb_read_table'].split(',')
  39. df_list = []
  40. client = MongoClient(mongodb_connection)
  41. # 选择数据库(如果数据库不存在,MongoDB 会自动创建)
  42. db = client[mongodb_database]
  43. for table in mongodb_read_table:
  44. collection = db[table] # 集合名称
  45. data_from_db = collection.find() # 这会返回一个游标(cursor)
  46. # 将游标转换为列表,并创建 pandas DataFrame
  47. df = pd.DataFrame(list(data_from_db))
  48. if '_id' in df.columns:
  49. df = df.drop(columns=['_id'])
  50. df_list.append(df)
  51. client.close()
  52. return df_list
  53. def insert_data_into_mongo(res_df, args):
  54. """
  55. 插入数据到 MongoDB 集合中,可以选择覆盖、追加或按指定的 key 进行更新插入。
  56. 参数:
  57. - res_df: 要插入的 DataFrame 数据
  58. - args: 包含 MongoDB 数据库和集合名称的字典
  59. - overwrite: 布尔值,True 表示覆盖,False 表示追加
  60. - update_keys: 列表,指定用于匹配的 key 列,如果存在则更新,否则插入 'col1','col2'
  61. """
  62. mongodb_connection = "mongodb://root:sdhjfREWFWEF23e@192.168.1.43:30000/"
  63. mongodb_database = args['mongodb_database']
  64. mongodb_write_table = args['mongodb_write_table']
  65. overwrite = 1
  66. update_keys = None
  67. if 'overwrite' in args.keys():
  68. overwrite = int(args['overwrite'])
  69. if 'update_keys' in args.keys():
  70. update_keys = args['update_keys'].split(',')
  71. client = MongoClient(mongodb_connection)
  72. db = client[mongodb_database]
  73. collection = db[mongodb_write_table]
  74. # 覆盖模式:删除现有集合
  75. if overwrite:
  76. if mongodb_write_table in db.list_collection_names():
  77. collection.drop()
  78. print(f"Collection '{mongodb_write_table}' already exists, deleted successfully!")
  79. # 将 DataFrame 转为字典格式
  80. data_dict = res_df.to_dict("records") # 每一行作为一个字典
  81. # 如果没有数据,直接返回
  82. if not data_dict:
  83. print("No data to insert.")
  84. return
  85. # 如果指定了 update_keys,则执行 upsert(更新或插入)
  86. if update_keys and not overwrite:
  87. operations = []
  88. for record in data_dict:
  89. # 构建查询条件,用于匹配要更新的文档
  90. query = {key: record[key] for key in update_keys}
  91. operations.append(UpdateOne(query, {'$set': record}, upsert=True))
  92. # 批量执行更新/插入操作
  93. if operations:
  94. result = collection.bulk_write(operations)
  95. print(f"Matched: {result.matched_count}, Upserts: {result.upserted_count}")
  96. else:
  97. # 追加模式:直接插入新数据
  98. collection.insert_many(data_dict)
  99. print("Data inserted successfully!")
  100. def get_data_fromMysql(params):
  101. mysql_conn = params['mysql_conn']
  102. query_sql = params['query_sql']
  103. #数据库读取实测气象
  104. engine = create_engine(f"mysql+pymysql://{mysql_conn}")
  105. # 定义SQL查询
  106. env_df = pd.read_sql_query(query_sql, engine)
  107. return env_df
  108. def insert_pickle_model_into_mongo(model, args):
  109. mongodb_connection, mongodb_database, mongodb_write_table, model_name = "mongodb://root:sdhjfREWFWEF23e@192.168.1.43:30000/", \
  110. args['mongodb_database'], args['mongodb_write_table'], args['model_name']
  111. client = MongoClient(mongodb_connection)
  112. db = client[mongodb_database]
  113. # 序列化模型
  114. model_bytes = pickle.dumps(model)
  115. model_data = {
  116. 'model_name': model_name,
  117. 'model': model_bytes, # 将模型字节流存入数据库
  118. }
  119. print('Training completed!')
  120. if mongodb_write_table in db.list_collection_names():
  121. db[mongodb_write_table].drop()
  122. print(f"Collection '{mongodb_write_table} already exist, deleted successfully!")
  123. collection = db[mongodb_write_table] # 集合名称
  124. collection.insert_one(model_data)
  125. print("model inserted successfully!")
  126. def insert_h5_model_into_mongo(model,feature_scaler_bytes,target_scaler_bytes ,args):
  127. mongodb_connection,mongodb_database,scaler_table,model_table,model_name = ("mongodb://root:sdhjfREWFWEF23e@192.168.1.43:30000/",
  128. args['mongodb_database'],args['scaler_table'],args['model_table'],args['model_name'])
  129. client = MongoClient(mongodb_connection)
  130. db = client[mongodb_database]
  131. if scaler_table in db.list_collection_names():
  132. db[scaler_table].drop()
  133. print(f"Collection '{scaler_table} already exist, deleted successfully!")
  134. collection = db[scaler_table] # 集合名称
  135. # Save the scalers in MongoDB as binary data
  136. collection.insert_one({
  137. "feature_scaler": feature_scaler_bytes.read(),
  138. "target_scaler": target_scaler_bytes.read()
  139. })
  140. print("scaler_model inserted successfully!")
  141. if model_table in db.list_collection_names():
  142. db[model_table].drop()
  143. print(f"Collection '{model_table} already exist, deleted successfully!")
  144. model_table = db[model_table]
  145. # 创建 BytesIO 缓冲区
  146. model_buffer = BytesIO()
  147. # 将模型保存为 HDF5 格式到内存 (BytesIO)
  148. model.save(model_buffer, save_format='h5')
  149. # 将指针移到缓冲区的起始位置
  150. model_buffer.seek(0)
  151. # 获取模型的二进制数据
  152. model_data = model_buffer.read()
  153. # 将模型保存到 MongoDB
  154. model_table.insert_one({
  155. "model_name": model_name,
  156. "model_data": model_data
  157. })
  158. print("模型成功保存到 MongoDB!")
  159. def insert_trained_model_into_mongo(model ,args):
  160. mongodb_connection,mongodb_database,model_table,model_name = ("mongodb://root:sdhjfREWFWEF23e@192.168.1.43:30000/",
  161. args['mongodb_database'],args['model_table'],args['model_name'])
  162. gen_time, params_json, descr = args['gen_time'], args['params'], args['descr']
  163. client = MongoClient(mongodb_connection)
  164. db = client[mongodb_database]
  165. if model_table in db.list_collection_names():
  166. db[model_table].drop()
  167. print(f"Collection '{model_table} already exist, deleted successfully!")
  168. model_table = db[model_table]
  169. # 创建 BytesIO 缓冲区
  170. model_buffer = BytesIO()
  171. # 将模型保存为 HDF5 格式到内存 (BytesIO)
  172. model.save(model_buffer, save_format='h5')
  173. # 将指针移到缓冲区的起始位置
  174. model_buffer.seek(0)
  175. # 获取模型的二进制数据
  176. model_data = model_buffer.read()
  177. # 将模型保存到 MongoDB
  178. model_table.insert_one({
  179. "model_name": model_name,
  180. "model_data": model_data,
  181. "gen_time": gen_time,
  182. "params": params_json,
  183. "descr": descr
  184. })
  185. print("模型成功保存到 MongoDB!")
  186. def insert_scaler_model_into_mongo(feature_scaler_bytes, args):
  187. mongodb_connection,mongodb_database,scaler_table,model_table,model_name = ("mongodb://root:sdhjfREWFWEF23e@192.168.1.43:30000/",
  188. args['mongodb_database'],args['scaler_table'],args['model_table'],args['model_name'])
  189. client = MongoClient(mongodb_connection)
  190. db = client[mongodb_database]
  191. if scaler_table in db.list_collection_names():
  192. db[scaler_table].drop()
  193. print(f"Collection '{scaler_table} already exist, deleted successfully!")
  194. collection = db[scaler_table] # 集合名称
  195. # Save the scalers in MongoDB as binary data
  196. collection.insert_one({
  197. "feature_scaler": feature_scaler_bytes.read(),
  198. })
  199. print("scaler_model inserted successfully!")
  200. def get_h5_model_from_mongo(args):
  201. mongodb_connection,mongodb_database,model_table,model_name = "mongodb://root:sdhjfREWFWEF23e@192.168.1.43:30000/",args['mongodb_database'],args['model_table'],args['model_name']
  202. client = MongoClient(mongodb_connection)
  203. # 选择数据库(如果数据库不存在,MongoDB 会自动创建)
  204. db = client[mongodb_database]
  205. collection = db[model_table] # 集合名称
  206. # 查询 MongoDB 获取模型数据
  207. model_doc = collection.find_one({"model_name": model_name})
  208. if model_doc:
  209. model_data = model_doc['model_data'] # 获取模型的二进制数据
  210. # 将二进制数据加载到 BytesIO 缓冲区
  211. model_buffer = BytesIO(model_data)
  212. # 从缓冲区加载模型
  213. # 使用 h5py 和 BytesIO 从内存中加载模型
  214. with h5py.File(model_buffer, 'r') as f:
  215. model = tf.keras.models.load_model(f)
  216. print(f"{model_name}模型成功从 MongoDB 加载!")
  217. client.close()
  218. return model
  219. else:
  220. print(f"未找到model_name为 {model_name} 的模型。")
  221. client.close()
  222. return None
  223. def get_scaler_model_from_mongo(args):
  224. mongodb_connection, mongodb_database, scaler_table, = ("mongodb://root:sdhjfREWFWEF23e@192.168.1.43:30000/",
  225. args['mongodb_database'], args['scaler_table'])
  226. client = MongoClient(mongodb_connection)
  227. # 选择数据库(如果数据库不存在,MongoDB 会自动创建)
  228. db = client[mongodb_database]
  229. collection = db[scaler_table] # 集合名称
  230. # Retrieve the scalers from MongoDB
  231. scaler_doc = collection.find_one()
  232. # Deserialize the scalers
  233. feature_scaler_bytes = BytesIO(scaler_doc["feature_scaler"])
  234. feature_scaler = joblib.load(feature_scaler_bytes)
  235. target_scaler_bytes = BytesIO(scaler_doc["target_scaler"])
  236. target_scaler = joblib.load(target_scaler_bytes)
  237. return feature_scaler,target_scaler