forked from SolaceLabs/solace-ai-connector
-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
JDE: Added MongoDB insert action + example #81
Merged
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
4e0e505
Added mongodb insert component
cyrus2281 9fc1f03
type
cyrus2281 ba06c46
added search component
cyrus2281 8562c31
applied comments
cyrus2281 8fcccfd
updated docs
cyrus2281 d348e26
Merge branch 'main' into cyrus/jde/mongodb
cyrus2281 2f08029
Added the option to support custom keys for reply and metadata for re…
cyrus2281 d546aaa
Merge branch 'cyrus/request-response/custom-key' into cyrus/jde/mongodb
cyrus2281 341a49c
fixed issue
cyrus2281 b524447
Merge branch 'main' into cyrus/jde/mongodb
cyrus2281 bc889d2
Updated insert with type
cyrus2281 2316d36
added docs
cyrus2281 2c85c3b
added config value validation
cyrus2281 77668a8
added value check for mongo insert
cyrus2281 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
--- | ||
log: | ||
stdout_log_level: INFO | ||
log_file_level: INFO | ||
log_file: solace_ai_connector.log | ||
|
||
trace: | ||
trace_file: solace_ai_connector_trace.log | ||
|
||
shared_config: | ||
- broker_config: &broker_connection | ||
broker_type: solace | ||
broker_url: ${SOLACE_BROKER_URL} | ||
broker_username: ${SOLACE_BROKER_USERNAME} | ||
broker_password: ${SOLACE_BROKER_PASSWORD} | ||
broker_vpn: ${SOLACE_BROKER_VPN} | ||
|
||
flows: | ||
# Data ingestion to MongoDB for context mesh | ||
- name: real_time_data_ingest | ||
components: | ||
# Data Input from Solace broker | ||
- component_name: solace_data_input | ||
component_module: broker_input | ||
component_config: | ||
<<: *broker_connection | ||
broker_queue_name: demo_data_ingest | ||
broker_subscriptions: | ||
- topic: data/ingest | ||
qos: 1 | ||
payload_encoding: utf-8 | ||
payload_format: json | ||
|
||
# Batch messages to avoid frequent calls to DB | ||
- component_name: batch_aggregate | ||
component_module: aggregate | ||
component_config: | ||
max_items: 100 | ||
max_time_ms: 3000 | ||
input_selection: | ||
source_expression: input.payload:event | ||
|
||
# Insert into MongoDB | ||
- component_name: mongo_insert | ||
component_module: mongo_insert | ||
component_config: | ||
database_host: ${MONGO_HOST} | ||
database_port: ${MONGO_PORT} | ||
database_user: ${MONGO_USER} | ||
database_password: ${MONGO_PASSWORD} | ||
database_name: ${MONGO_DB} | ||
database_collection: ${MONGO_COLLECTION} | ||
data_types: | ||
timestamp: Date | ||
input_selection: | ||
source_expression: previous |
80 changes: 79 additions & 1 deletion
80
src/solace_ai_connector/components/general/db/mongo/mongo_insert.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,21 +1,99 @@ | ||
"""MongoDB Agent Component for handling database insert.""" | ||
|
||
import datetime | ||
import dateutil.parser | ||
from .mongo_base import MongoDBBaseComponent, info as base_info | ||
|
||
info = base_info.copy() | ||
info["class_name"] = "MongoDBInsertComponent" | ||
info["description"] = "Inserts data into a MongoDB database." | ||
info["config_parameters"].extend([ | ||
{ | ||
"name": "data_types", | ||
"required": False, | ||
"description": "Key value pairs to specify the data types for each field in the data. Used for non-JSON types like Date. Supports nested dotted names", | ||
}, | ||
]) | ||
|
||
POSSIBLE_TYPES = ["date", "timestamp", "int", "int32", "int64", "float", "double", "bool", "string", "null"] | ||
|
||
class MongoDBInsertComponent(MongoDBBaseComponent): | ||
"""Component for handling MongoDB database operations.""" | ||
|
||
def __init__(self, **kwargs): | ||
super().__init__(info, **kwargs) | ||
self.data_types_map = self.get_config("data_types") | ||
if self.data_types_map: | ||
if not isinstance(self.data_types_map, dict): | ||
raise ValueError( | ||
"Invalid data types provided for MongoDB insert. Expected a dictionary." | ||
) | ||
for key, field_type in self.data_types_map.items(): | ||
if not isinstance(key, str) or not isinstance(field_type, str) or field_type.lower() not in POSSIBLE_TYPES: | ||
raise ValueError( | ||
"Invalid data types provided for MongoDB insert. Expected a dictionary with key value pairs where key is a string and value is a string from the following list: " | ||
+ ", ".join(POSSIBLE_TYPES) | ||
) | ||
|
||
|
||
def invoke(self, message, data): | ||
if not data: | ||
if not data or not isinstance(data, dict) and not isinstance(data, list): | ||
raise ValueError( | ||
"Invalid data provided for MongoDB insert. Expected a dictionary or a list of dictionary." | ||
) | ||
|
||
if self.data_types_map: | ||
for key, field_type in self.data_types_map.items(): | ||
if isinstance(data, list): | ||
new_data = [] | ||
for item in data: | ||
new_data.append(self._convert_data_type(item, key, field_type)) | ||
data = new_data | ||
else: | ||
data = self._convert_data_type(data, key, field_type) | ||
return self.db_handler.insert_documents(data) | ||
|
||
def _convert_data_type(self, data, key, field_type): | ||
if not key or not field_type: | ||
cyrus2281 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return data | ||
if not isinstance(data, list) and not isinstance(data, dict): | ||
return data | ||
if "." in key: | ||
segments = key.split(".") | ||
segment = segments[0] | ||
if segment not in data: | ||
if key in data: | ||
data[key] = self._convert_field_type(data[key], field_type) | ||
return data | ||
if len(segments) > 1: | ||
data[segment] = self._convert_data_type(data[segment], ".".join(segments[1:]), field_type) | ||
else: | ||
data[segment] = self._convert_field_type(data[segment], field_type) | ||
else: | ||
if key in data: | ||
data[key] = self._convert_field_type(data[key], field_type) | ||
return data | ||
|
||
def _convert_field_type(self, value, field_type): | ||
field_type = field_type.lower() | ||
if field_type == "date" or field_type == "timestamp": | ||
if isinstance(value, str): | ||
return dateutil.parser.parse(value) | ||
elif isinstance(value, int) or isinstance(value, float): | ||
return datetime.datetime.fromtimestamp(value) | ||
else: | ||
return value | ||
if field_type == "int" or field_type == "int32" or field_type == "int64": | ||
return int(value) | ||
if field_type == "float" or field_type == "double": | ||
return float(value) | ||
if field_type == "bool": | ||
if isinstance(value, str) and value.lower() == "false": | ||
return False | ||
return bool(value) | ||
if field_type == "string": | ||
return str(value) | ||
if field_type == "null": | ||
return None | ||
return value | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please give some examples of data_types and data. Since the
data
variable may include any complex data structure (e.g., List[List[List]]), would your code expect to handle all possible combinations?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added proper validation.
As for example, you can find some here
solace-ai-connector/examples/db/mongodb_insert.yaml
Line 53 in 2c85c3b