-
Notifications
You must be signed in to change notification settings - Fork 127
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
MongoDB Atlas: filters #542
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
4bfc290
wip
anakin87 7c78b79
progress
anakin87 20e14f6
more tests
anakin87 09350c1
Merge branch 'main' into mongo-filters
anakin87 d87769f
improvements
anakin87 3520635
ignore missing imports in pyproject
anakin87 460b2db
fix mypy
anakin87 8c21042
show coverage
anakin87 e21c5df
rm code duplication
anakin87 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
4 changes: 0 additions & 4 deletions
4
integrations/mongodb_atlas/src/haystack_integrations/document_stores/mongodb_atlas/errors.py
This file was deleted.
Oops, something went wrong.
157 changes: 150 additions & 7 deletions
157
...grations/mongodb_atlas/src/haystack_integrations/document_stores/mongodb_atlas/filters.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,9 +1,152 @@ | ||
from typing import Any, Dict, Optional | ||
# SPDX-FileCopyrightText: 2024-present deepset GmbH <[email protected]> | ||
# | ||
# SPDX-License-Identifier: Apache-2.0 | ||
from datetime import datetime | ||
from typing import Any, Dict | ||
|
||
from haystack.errors import FilterError | ||
from haystack.utils.filters import convert | ||
from pandas import DataFrame | ||
|
||
def haystack_filters_to_mongo(filters: Optional[Dict[str, Any]]): | ||
# TODO | ||
if filters: | ||
msg = "Filtering not yet implemented for MongoDBAtlasDocumentStore" | ||
raise ValueError(msg) | ||
return {} | ||
UNSUPPORTED_TYPES_FOR_COMPARISON = (list, DataFrame) | ||
|
||
|
||
def _normalize_filters(filters: Dict[str, Any]) -> Dict[str, Any]: | ||
""" | ||
Converts Haystack filters to MongoDB filters. | ||
""" | ||
if not isinstance(filters, dict): | ||
msg = "Filters must be a dictionary" | ||
raise FilterError(msg) | ||
|
||
if "operator" not in filters and "conditions" not in filters: | ||
filters = convert(filters) | ||
|
||
if "field" in filters: | ||
return _parse_comparison_condition(filters) | ||
return _parse_logical_condition(filters) | ||
|
||
|
||
def _parse_logical_condition(condition: Dict[str, Any]) -> Dict[str, Any]: | ||
if "operator" not in condition: | ||
msg = f"'operator' key missing in {condition}" | ||
raise FilterError(msg) | ||
if "conditions" not in condition: | ||
msg = f"'conditions' key missing in {condition}" | ||
raise FilterError(msg) | ||
|
||
# logical conditions can be nested, so we need to parse them recursively | ||
conditions = [] | ||
for c in condition["conditions"]: | ||
if "field" in c: | ||
conditions.append(_parse_comparison_condition(c)) | ||
else: | ||
conditions.append(_parse_logical_condition(c)) | ||
|
||
operator = condition["operator"] | ||
if operator == "AND": | ||
return {"$and": conditions} | ||
elif operator == "OR": | ||
return {"$or": conditions} | ||
elif operator == "NOT": | ||
# MongoDB doesn't support our NOT operator (logical NAND) directly. | ||
# we combine $nor and $and to achieve the same effect. | ||
return {"$nor": [{"$and": conditions}]} | ||
|
||
msg = f"Unknown logical operator '{operator}'. Valid operators are: 'AND', 'OR', 'NOT'" | ||
raise FilterError(msg) | ||
|
||
|
||
def _parse_comparison_condition(condition: Dict[str, Any]) -> Dict[str, Any]: | ||
field: str = condition["field"] | ||
if "operator" not in condition: | ||
msg = f"'operator' key missing in {condition}" | ||
raise FilterError(msg) | ||
if "value" not in condition: | ||
msg = f"'value' key missing in {condition}" | ||
raise FilterError(msg) | ||
operator: str = condition["operator"] | ||
value: Any = condition["value"] | ||
|
||
if isinstance(value, DataFrame): | ||
value = value.to_json() | ||
|
||
return COMPARISON_OPERATORS[operator](field, value) | ||
|
||
|
||
def _equal(field: str, value: Any) -> Dict[str, Any]: | ||
return {field: {"$eq": value}} | ||
|
||
|
||
def _not_equal(field: str, value: Any) -> Dict[str, Any]: | ||
return {field: {"$ne": value}} | ||
|
||
|
||
def _validate_type_for_comparison(value: Any) -> None: | ||
msg = f"Cant compare {type(value)} using operators '>', '>=', '<', '<='." | ||
if isinstance(value, UNSUPPORTED_TYPES_FOR_COMPARISON): | ||
raise FilterError(msg) | ||
elif isinstance(value, str): | ||
try: | ||
datetime.fromisoformat(value) | ||
except (ValueError, TypeError) as exc: | ||
msg += "\nStrings are only comparable if they are ISO formatted dates." | ||
raise FilterError(msg) from exc | ||
|
||
|
||
def _greater_than(field: str, value: Any) -> Dict[str, Any]: | ||
_validate_type_for_comparison(value) | ||
return {field: {"$gt": value}} | ||
|
||
|
||
def _greater_than_equal(field: str, value: Any) -> Dict[str, Any]: | ||
if value is None: | ||
# we want {field: {"$gte": null}} to return an empty result | ||
# $gte with null values in MongoDB returns a non-empty result, while $gt aligns with our expectations | ||
return {field: {"$gt": value}} | ||
|
||
_validate_type_for_comparison(value) | ||
return {field: {"$gte": value}} | ||
|
||
|
||
def _less_than(field: str, value: Any) -> Dict[str, Any]: | ||
_validate_type_for_comparison(value) | ||
return {field: {"$lt": value}} | ||
|
||
|
||
def _less_than_equal(field: str, value: Any) -> Dict[str, Any]: | ||
if value is None: | ||
# we want {field: {"$lte": null}} to return an empty result | ||
# $lte with null values in MongoDB returns a non-empty result, while $lt aligns with our expectations | ||
return {field: {"$lt": value}} | ||
_validate_type_for_comparison(value) | ||
|
||
return {field: {"$lte": value}} | ||
|
||
|
||
def _not_in(field: str, value: Any) -> Dict[str, Any]: | ||
if not isinstance(value, list): | ||
msg = f"{field}'s value must be a list when using 'not in' comparator in Pinecone" | ||
raise FilterError(msg) | ||
|
||
return {field: {"$nin": value}} | ||
|
||
|
||
def _in(field: str, value: Any) -> Dict[str, Any]: | ||
if not isinstance(value, list): | ||
msg = f"{field}'s value must be a list when using 'in' comparator in Pinecone" | ||
raise FilterError(msg) | ||
|
||
return {field: {"$in": value}} | ||
|
||
|
||
COMPARISON_OPERATORS = { | ||
"==": _equal, | ||
"!=": _not_equal, | ||
">": _greater_than, | ||
">=": _greater_than_equal, | ||
"<": _less_than, | ||
"<=": _less_than_equal, | ||
"in": _in, | ||
"not in": _not_in, | ||
} |
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
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.
I included all the base tests.
They also cover filters.