MongodbHandler.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Mon Sep 16 13:27:44 2019
  5. @author: oskar
  6. @description: Implementation of a database handler for abstraction of the mongodb.
  7. """
  8. import json
  9. import simplejson
  10. import sys
  11. import os
  12. import jsonref
  13. from copy import deepcopy
  14. from pymongo import MongoClient
  15. import pandas as pd
  16. import numpy as np
  17. sys.path.append(os.getcwd())
  18. from cdplib.log import Log
  19. from cdplib.configuration import default as cfg
  20. class MongodbHandler:
  21. '''
  22. '''
  23. def __init__(self, database_url: str = cfg['MONGO_DB']['URI'],
  24. database_name: str = cfg['MONGO_DB']['DATABASE_NAME']):
  25. '''
  26. :param str database_url: Url for the mongodb database
  27. :param str database_name: Name of the database the database handler should handle
  28. '''
  29. assert(isinstance(database_url, str)),\
  30. "Parameter 'database_url' must be a string type"
  31. assert(isinstance(database_name, str)),\
  32. "Parameter 'database_name' must be a string type"
  33. self._log = Log("\nMongodbHandler script")
  34. self._log.info('Mongodb Handler has been initialized')
  35. # Connect to the MongoDB
  36. self._client = MongoClient(database_url)
  37. # Connect to the oebb_db database, or create it if it doesnt exist.
  38. self._database = self._client[database_name]
  39. def _read_schema(self, schema_path: str) -> dict:
  40. '''
  41. :param str schema_path: path to the schema file.
  42. '''
  43. assert(isinstance(schema_path, str)),\
  44. "Parameter 'schema_path must be a string type"
  45. with open(schema_path) as json_file:
  46. schema = json.load(json_file)
  47. if 'definitions' in schema:
  48. schema = self._dereference_schema(schema)
  49. return schema
  50. def _dereference_schema(self, schema: dict) -> dict:
  51. '''
  52. :param dict schema: dictionary containing a schema which uses references.
  53. '''
  54. assert(isinstance(schema, dict)),\
  55. "Parameter 'schema' must be a dictionary type"
  56. schema = jsonref.loads(str(schema).replace("'", "\""))
  57. schema = deepcopy(schema)
  58. schema.pop('definitions', None)
  59. return schema
  60. def set_collection_schema(self, collection_name: str, schema_path: str,
  61. validation_level: str = 'moderate',validation_action: str = 'error'):
  62. '''
  63. :param str collection_name: name on the collection for which the schema will be set.
  64. :param str schema_path: path to the schema file.
  65. :param str validation_level: level of validation done by the mongodb.
  66. :param str validation_action: what will happen upon validation error, warning or error message.
  67. '''
  68. assert(isinstance(collection_name, str)),\
  69. "Parameter 'collection_name' must be a string type"
  70. assert(isinstance(schema_path, str)),\
  71. "Parameter 'schema_path' must be a string type"
  72. assert(isinstance(validation_level, str)),\
  73. "Parameter 'validation_lever' must be a string type"
  74. assert(isinstance(validation_action, str)),\
  75. "Parameter 'validation_action' must be a string type"
  76. schema = self._read_schema(schema_path)
  77. command = {
  78. 'collMod': collection_name,
  79. 'validator': {
  80. '$jsonSchema': schema
  81. },
  82. 'validationLevel': validation_level,
  83. 'validationAction': validation_action
  84. }
  85. self._database.command(command)
  86. def create_collection(self, collection_name):
  87. '''
  88. :param str collection_name: name of the collection to be created.
  89. '''
  90. assert(isinstance(collection_name, str)),\
  91. "Parameter 'collection_name' must be a string type"
  92. if collection_name not in self._database.list_collection_names():
  93. self._log.info(("Collection '{}' has been created").format(collection_name))
  94. return self._database.create_collection(collection_name)
  95. else:
  96. self._log.info(("Collection '{}' already exists").format(collection_name))
  97. return self._database[collection_name]
  98. def insert_data_into_collection(self, data: (dict, list, np.ndarray, pd.DataFrame, pd.Series),
  99. collection_name: str,
  100. ordered: bool = False):
  101. '''
  102. :param dict data: dictionary containing the data to be inserted in the collection
  103. :param pymongo.database.Collection collection: The collection the data will be added to.
  104. '''
  105. allowed_types = (dict, list, np.ndarray, pd.DataFrame, pd.Series)
  106. assert(isinstance(data, allowed_types)),\
  107. "Parameter 'data' is of invalid type"
  108. if isinstance(data, np.ndarray):
  109. data = pd.DataFrame(data)
  110. if isinstance(data, pd.DataFrame):
  111. data = simplejson.loads(data.to_json(orient="records",
  112. date_format="iso"))
  113. elif isinstance(data, pd.Series):
  114. data = simplejson.loads(data.to_json(date_format="iso"))
  115. if (len(data) == 1) or (isinstance(data, dict)):
  116. if isinstance(data, pd.DataFrame) and (len(data) == 1):
  117. data = data.iloc[0]
  118. self._database[collection_name].insert_one(data)
  119. else:
  120. self._database[collection_name].insert_many(data, ordered=ordered)
  121. self._log.info(('Data has been inserted into the {} collection').format(collection_name))
  122. def create_collection_and_set_schema(self, collection_name: str, schema_path: str):
  123. '''
  124. :param str collection_name: name of the collection to be created.
  125. :param str schema_path: path to the schema file.
  126. '''
  127. assert(isinstance(collection_name, str)),\
  128. "Parameter 'collection_name' must be a string type"
  129. assert(isinstance(schema_path, str)),\
  130. "Parameter 'schema_path' must be a string type"
  131. self.create_collection(collection_name)
  132. self.set_collection_schema(collection_name=collection_name, schema_path=schema_path)
  133. def query_data_and_generate_dataframe(self, collection_name: str, attribute: str = None,
  134. attribute_value: str = None, comparison_operator: str = '$eq'):
  135. '''
  136. '''
  137. if attribute is None or attribute_value is None:
  138. data = self._database[collection_name].find()
  139. else:
  140. data = self._database[collection_name].find({attribute: {comparison_operator: attribute_value}})
  141. df = pd.DataFrame(list(data))
  142. df.set_index('radsatznummer', inplace=True)
  143. return df
  144. if __name__ == "__main__":
  145. log = Log("Test MongodbHandler:")
  146. log.info('Script started')
  147. db_handler = MongodbHandler()
  148. # Create a colleciton for the wheelsets and give it its schema.
  149. for schema_path in [
  150. os.path.join(".", "mongo_schema", "schema_wheelsets.json"),
  151. os.path.join(".", "mongo_schema", "schema_process_instances.json"),
  152. os.path.join(".", "mongo_schema", "schema_componets.json")]:
  153. if os.path.isfile(schema_path):
  154. collection_name = os.path.basename(schema_path).lstrip("_schema").split(".")[0]
  155. db_handler.create_collection_and_set_schema(collection_name, schema_path)
  156. log.info(("Existing databases: {}, Collection in OEBB database {}")\
  157. .format(db_handler._client.list_database_names(), db_handler._database.list_collection_names()))