Skip to content

Commit

Permalink
analytics: add comparison operators: <, <=, >, >=
Browse files Browse the repository at this point in the history
Change-Id: Ib970576d7635f113a15d8ce9dfdad815b0a4ca22
  • Loading branch information
ylamgarchal committed Oct 30, 2024
1 parent 642592b commit 532e277
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
20 changes: 19 additions & 1 deletion dci/analytics/query_es_dsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
_comma_string = _comma + _word
_list = _lb + _word + pp.ZeroOrMore(_comma_string) + _rb

_comparison_operators = {"=", "!=", "<=" "<", ">=", ">", "=~"}
_comparison_operators = {"=", "!=", "<=", "<", ">=", ">", "=~"}
_comparison_operators = pp.oneOf(" ".join(_comparison_operators))
_comparison = _field + _comparison_operators + _value

Expand Down Expand Up @@ -58,6 +58,20 @@ def parse(q):
return query.parseString(q).asList()


_op_to_es_op = {"<": "lt", "<=": "lte", ">": "gt", ">=": "gte"}


def _handle_comparison_operator(handle_nested, operator, operand_1, operand_2):
if handle_nested and "." in operand_1:
return {
"nested": {
"path": operand_1.split(".")[0],
"query": {"range": {operand_1: {_op_to_es_op[operator]: operand_2}}},
}
}
return {"range": {operand_1: {_op_to_es_op[operator]: operand_2}}}


def _generate_from_operators(parsed_query, handle_nested=False):
operand_1 = parsed_query[0]
operator = parsed_query[1]
Expand All @@ -72,6 +86,10 @@ def _generate_from_operators(parsed_query, handle_nested=False):
}
}
return {"term": {operand_1: operand_2}}
if operator in _op_to_es_op.keys():
return _handle_comparison_operator(
handle_nested, operator, operand_1, operand_2
)
elif operator == "=~":
return {
"regexp": {
Expand Down
38 changes: 38 additions & 0 deletions tests/analytics/test_query_es_dsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,3 +345,41 @@ def test_query_build_regex():
]
}
}


def test_query_build_comparison_operator():
ret = qed.build(
"(((keys_values.a>0) and (keys_values.a<10)) or ((keys_values.b>0) and (keys_values.b<=10)))"
)
assert ret == {
"bool": {
"should": [
{
"nested": {
"path": "keys_values",
"query": {
"bool": {
"filter": [
{"range": {"keys_values.a": {"gt": "0"}}},
{"range": {"keys_values.a": {"lt": "10"}}},
]
}
},
}
},
{
"nested": {
"path": "keys_values",
"query": {
"bool": {
"filter": [
{"range": {"keys_values.b": {"gt": "0"}}},
{"range": {"keys_values.b": {"lte": "10"}}},
]
}
},
}
},
]
}
}

0 comments on commit 532e277

Please sign in to comment.