database_dml.py 8.4 KB

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