Neo4jQueryConverter
NodeVisitor ¤
A base class for a converter which is responsible for converting filters abstract syntax tree into a particular DocumentStore specific syntax (e.g. SQL/Cypher queries). It provides a basic structure for a "Visitor Pattern" where each node of the tree could be "visited" (a method called with the node as a parameter).
Source code in src/neo4j_haystack/metadata_filter/neo4j_query_converter.py
visit ¤
Resolves a method name (visitor) to be called with a particular AST node
. The visitor is responsible for
handling logic of the node (e.g. converting it to a database specific query). The method to be called is
determined by a descriptor (python friendly name, e.g. logical_op
for a node of type LogicalOp
).
If visitor method could not be found a generic exception is raised.
Parameters:
-
node
(AST
) –AST
node to be visited.
Returns:
-
Any
–Any result implementing class is planning to return.
Source code in src/neo4j_haystack/metadata_filter/neo4j_query_converter.py
generic_visit ¤
A fallback visitor in case no specific ones have been found. Raises error by default.
_descriptor ¤
Composes a full name for the visitor method with the prefix, e.g. "visit_"
+ "logical_op"
.
Neo4jQueryConverter ¤
Bases: NodeVisitor
This class acts as a visitor for all nodes in an abstract syntax tree built by the FilterParser
. Its job is
to traverse the tree and "visit" (call respective method) nodes to accomplish the conversion between metadata
filters into Neo4j Cypher expressions. Resulting Cypher query is then used as part of the WHERE
Neo4j clause and
is based on the following concepts:
below is an example usage of the converter:
parser = FilterParser()
converter = Neo4jQueryConverter("doc")
filters = {
"operator": "OR",
"conditions": [
{
"operator": "AND",
"conditions": [
{"field": "meta.type", "operator": "==", "value": "news"},
{"field": "meta.likes", "operator": "!=", "value": 100},
],
},
{
"operator": "AND",
"conditions": [
{"field": "meta.type", "operator": "==", "value": "blog"},
{"field": "meta.likes", "operator": ">=", "value": 500},
],
},
],
}
filter_ast = parser.parse(filters)
cypher_query, params = converter.convert(filter_ast)
The above code will produce the following Neo4j Cypher query (cypher_query
):
((doc.type = $fv_type AND doc.likes < $fv_likes) OR (doc.type = $fv_type_1 AND doc.likes >= $fv_likes_1))
with parameters (params
):
The reason Cypher query is accompanied with parameters is because we delegate data type conversion of parameter values to Neo4j Python Driver instead of repeating the logic in this class. See the full mapping of core and extended types in the Data Types document.
The conversion logic of this class starts with root node of the abstract syntax tree which is usually a logical
operator (e.g. "$and") and calls visit
method with that node. Depending on type of the node respective visitor
method is called:
visit_logical_op
if node represents a logical operator (LogicalOp
)visit_comparison_op
if node represents a comparison operator (LogicalOp
)
Each visitor is responsible of producing a Cypher expression which is then combined with other expressions up in the tree. Parentheses are used to group expressions if required.
Source code in src/neo4j_haystack/metadata_filter/neo4j_query_converter.py
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 |
|
__init__ ¤
__init__(
field_name_prefix: Optional[str] = None,
include_null_values_when_not_equal: Optional[bool] = False,
flatten_field_name: Optional[bool] = True,
)
Parameters:
-
field_name_prefix
(Optional[str]
, default:None
) –A prefix to be added to field names in Cypher queries (e.g.
doc.age = 20
, where"doc"
is the prefix). -
include_null_values_when_not_equal
(Optional[bool]
, default:False
) –When
True
will enable additional Cypher expressions for inequality operators "not in" and "!=" so thatnull
values are considered as "not equal" instead of being skipped. This is experimental and by default is disabled. -
flatten_field_name
(Optional[bool]
, default:True
) –In case filed names are composite/nested like "meta.age" replace dot (".") with underscores ("_").
Source code in src/neo4j_haystack/metadata_filter/neo4j_query_converter.py
convert ¤
The method to be called for converting metadata filter AST into Cypher expression. It starts with calling
self.visit
for the root node of the tree.
Examples:
>>> op_tree = FilterParser().parse({ "age", 30 })
>>> Neo4jQueryConverter("n").convert(op_tree)
('n.age = $fv_age', {'$fv_age': 30})
Parameters:
-
op_tree
(AST
) –The abstract syntax tree representing a parsed metadata filter. See
FilterParser
to learn about parsing logic.
Returns:
Source code in src/neo4j_haystack/metadata_filter/neo4j_query_converter.py
visit_logical_op ¤
Handles logical operators of type LogicalOp
by visiting all its operands first. This might result in
recursive calls as operands might be logical operators as well. Once all operands render its own Cypher
expressions all of those expressions are combined in a single query using operator of the node
(e.g. "AND").
If there are more than one operand parentheses are used to group all expressions.
Examples:
>>> operand1 = ComparisonOp("age", "!=", 20)
>>> operand2 = ComparisonOp("age", "<=", 30)
>>> logical_op = LogicalOp([operand1, operand2], "OR")
>>> self.visit_logical_op(operator)
"(doc.age <> 20 OR doc.age <= 30"
Parameters:
-
node
(LogicalOp
) –The logical operator
AST
node to be converted.
Returns:
-
str
–Cypher expression converted from the logical operator.
Source code in src/neo4j_haystack/metadata_filter/neo4j_query_converter.py
visit_comparison_op ¤
Handles comparison operators of type ComparisonOp
by checking each operator type and delegating to
appropriate method for translating the operator to a Cypher comparison expression. Each comparison expression
might produce respective query parameters (and its values) which are added to the common parameters dictionary.
Parameter names are unique in order to avoid clashes between potentially multiple comparison operators.
Examples:
>>> operator = ComparisonOp("age", "in", [10, 11])
>>> self.visit_comparison_op(operator)
"doc.age IN [10, 11]"
Parameters:
-
node
(ComparisonOp
) –The comparison operator
AST
node to be converted.
Returns:
-
str
–Cypher expression converted from a comparison operator.
Source code in src/neo4j_haystack/metadata_filter/neo4j_query_converter.py
_field_is_null_expr ¤
Constructs "IS NULL" Cypher operator for the provided field (e.g. doc.age IS NULL
).
Non-empty expression will be returned only when self._include_null_values_when_not_equal
is set to
True
.
Note
This is experimental feature and is disabled as of now
Additional "IS NULL" checks can be useful for non-equality checks (e.g. "doc.age <> 0"
) as by default Neo4j
skips properties with null values, see Operators Equality
manual. The doc.age <> 0 OR doc.age IS NULL
expression will make sure all nodes are included in
comparison.
Parameters:
-
param
(CypherFieldParam
) –Field parameter metadata to be use in he Cypher expression.
Returns:
-
str
–Cypher "IS NULL" query clause for a given
param.field_name
. Emptystr
if logic is disabled byself._include_null_values_when_not_equal
.
Source code in src/neo4j_haystack/metadata_filter/neo4j_query_converter.py
_op_exists ¤
Translates "exists"
metadata filter into "IS NULL / IS NOT NULL"
Cypher expression. Useful for checking
absent properties. See more details in Neo4j documentation:
An example metadata filter would look as follows { "age": { "$exists": True } }
, which translates into
::cypher doc.age IS NOT NULL
Cypher expression. With False
in the filter value expression would become
doc.age IS NULL
.
Parameters:
-
param
(CypherFieldParam
) –Field parameter metadata to be use in he Cypher expression.
Returns:
-
CypherQueryExpression
–Cypher expression to check if property is
null
(property existence in Neo4j)
Source code in src/neo4j_haystack/metadata_filter/neo4j_query_converter.py
_op_neq ¤
Translates "!="
(not equal) metadata filter into "<>"
Cypher expression.
Parameters:
-
param
(CypherFieldParam
) –Field parameter metadata to be use in he Cypher expression.
Returns:
-
CypherQueryExpression
–Cypher expression using Cypher inequality operator, e.g.
doc.age <> 18
.
Source code in src/neo4j_haystack/metadata_filter/neo4j_query_converter.py
_op_in ¤
Translates "in"
(element exists in a list) metadata filter into "IN"
Cypher expression.
See more details in Neo4j documentation:
Please notice a combination of "CASE" expression and "IN" operator are being used to comply with
all metadata filtering options. In simple cases we would expect the following Cypher expression to be built:
"doc.age in [20, 30]"
,however, if the "age"
property is a list the expression
would not work in Neo4j. Thus CASE
checks the type of the property and if its a list any()
function
evaluates every element in the list with "IN" operator.
Parameters:
-
param
(CypherFieldParam
) –Field parameter metadata to be use in he Cypher expression.
Returns:
-
CypherQueryExpression
–Cypher expression using Cypher
IN
operator.
Source code in src/neo4j_haystack/metadata_filter/neo4j_query_converter.py
_op_nin ¤
Translates "not in"
(element not in a list) metadata filter into "NOT..IN"
Cypher expression. See
documentation of the _op_in
method for more details.
Additional "IS NULL" expression will be added if such configuration is enabled. See implementation of _field_is_null_expr.
Parameters:
-
param
(CypherFieldParam
) –Field parameter metadata to be use in he Cypher expression.
Returns:
-
CypherQueryExpression
–Cypher expression using Cypher
NOT IN
operator, e.g."NOT doc.age IN [20, 30]"
.
Source code in src/neo4j_haystack/metadata_filter/neo4j_query_converter.py
_op_default ¤
Default method to translate comparison metadata filter into Cypher expression.
The mapping between metadata filter operators and Neo4j operators is stored in self.COMPARISON_MAPPING
.
Parameters:
-
param
(CypherFieldParam
) –Field parameter metadata to be use in he Cypher expression.
Returns:
-
CypherQueryExpression
–Cypher expression using Cypher operator, e.g.
doc.age > 18
Source code in src/neo4j_haystack/metadata_filter/neo4j_query_converter.py
_cypher_expression ¤
_cypher_expression(
query: str, field_param: Optional[CypherFieldParam] = None
) -> CypherQueryExpression
A factory method to create CypherQueryExpression
data structure comprised of a Cypher query and
respective query parameters.
Parameters:
-
query
(str
) –Cypher query (expression)
-
field_param
(Optional[CypherFieldParam]
, default:None
) –Optional parameters to be added to the query execution.
Returns:
-
CypherQueryExpression
–Data class with query and parameters if any.
Source code in src/neo4j_haystack/metadata_filter/neo4j_query_converter.py
_wrap_in_parentheses ¤
_wrap_in_parentheses(
*cypher_expressions: str,
join_operator: str = "AND",
prefix_expr: Optional[str] = None
) -> str
Wraps given list of Cypher expressions in parentheses and combines them with a given operator which is
"AND" by default. For example if cypher_expressions=("age > $fv_age", "height <> $fv_height")
the method will return ("age > $fv_age AND height <> $fv_height")
.
For a single Cypher expression no parentheses are added and no operator is used.
Parameters:
-
join_operator
(str
, default:'AND'
) –Logical operator to combine given expressions.
-
prefix_expr
(Optional[str]
, default:None
) –Additional operators to be added in-front of the final Cypher query. Could be
"NOT "
in order to add negation to the combined expressions.
Returns:
-
str
–Cypher query expression, wrapped in parentheses if needed.
Source code in src/neo4j_haystack/metadata_filter/neo4j_query_converter.py
_field_param ¤
Constructs CypherFieldParam
data class with aggregated information about comparison operation.
Below is an example with resolved attribute values:
CypherFieldParam(
field_name="doc.age",
field_param_name="fv_age",
field_param_ref="$fv_age", # to be referenced in Cypher query
field_value=10,
op="<>", # mapped from "$ne" to "<>"
)
In a simplest case information from CypherFieldParam
could be converted into doc.age <> $fv_age
,
params={"fv_age": 10}
Parameters:
-
node
(ComparisonOp
) –Comparison
AST
node.
Returns:
-
CypherFieldParam
(CypherFieldParam
) –data class with required field parameter metadata.
Source code in src/neo4j_haystack/metadata_filter/neo4j_query_converter.py
_normalize_field_type ¤
Adjusts field value type if need. Generally we delegate the type conversion of python field values (data types)
to neo4j
python driver. This way we reduce amount of logic in the converter and rely on the driver to make
sure field value types are properly mapped between Python and Neo4j. In some cases though we can handle
additional conversions which are not supported by the driver. See example below:
The following Metadata filter query { "age": {30, 20 ,40} }
should produce IN
Cypher clause, e.g.
doc.age IN [20, 30, 40]
. However neo4j python driver does not accept set
python type, thus we
convert it to list
to make such filters possible.
Parameters:
-
field_value
(FieldValueType
) –Field value to be adjusted to be compatible with Neo4j types.
Returns:
-
FieldValueType
–Adjusted field value type if required.
Source code in src/neo4j_haystack/metadata_filter/neo4j_query_converter.py
_update_query_parameters ¤
_generate_param_name ¤
Generates a new Cypher query parameter name ensuring it is unique in a given parameter dictionary
self._params
. For example if self._params
is equal to { "fv_age": 20 }
a new parameter name called
fv_age_1
will be generated by adding appropriate incremented index.
Parameters:
-
field_name
(str
) –The nme of the filed to be generated.
"fv_"
prefix is added to all fields to avoid collisions with parameters given during Cypher query execution.
Returns:
-
str
–A new parameter name, with an unique index if needed.