Neo4jClient
NODE_VAR
module-attribute
¤
Default variable name used in Cypher queries to match and return Documents, e.g.
match(doc:Document) where doc.id = $id return doc
where doc
is a variable name.
DEFAULT_NEO4J_URI
module-attribute
¤
Default URI to connect to neo4j instance, e.g. a local DB running in Docker container.
DEFAULT_NEO4J_DATABASE
module-attribute
¤
Default Neo4j database name to connect to if not provided.
DEFAULT_NEO4J_USERNAME
module-attribute
¤
Default Neo4j username to be used for authentication with Neo4j. Used to simplify local development.
DEFAULT_NEO4J_PASSWORD
module-attribute
¤
Default Neo4j password to be used for authentication with Neo4j. Used to simplify local development.
Neo4jRecord
module-attribute
¤
Type alias for data items returned from Neo4j queries
Neo4jSessionConfig
module-attribute
¤
Generic dictionary for Session Configuration
Neo4jDriverConfig
module-attribute
¤
Generic dictionary for Driver Configuration
Neo4jTransactionConfig
module-attribute
¤
Generic dictionary for Transaction Configuration
VectorStoreIndexInfo
dataclass
¤
Neo4j vector index information retrieved from the database.
See Create and configure vector indexes documentation to learn more about data representing index configuration.
Attributes:
-
index_name
(str
) –The name of the index.
-
node_label
(str
) –Name of Neo4j node which contains embeddings which are indexed.
-
property_key
(str
) –Name of the property of the node which contains vectors.
-
dimensions
(int
) –Dimension of embedding vector.
-
similarity_function
(str
) –Configured vector similarity function.
Source code in src/neo4j_haystack/client/neo4j_client.py
Neo4jClientConfig
dataclass
¤
Provides extensive configuration options in order to communicate with Neo4j database.
It combines several configuration levels for each entity used by python driver to communicate with a database:
Developers can pick up configuration properties for each entity (e.g. session) which will be applied during
transaction invocations. For example, driver_config={"connection_timeout": 30}
will set amount of time in
seconds to wait for a TCP connection to be established.
username
and password
are optional because developer can choose to provide alternative
authentication options using driver_config
by setting Driver Auth Details.
Attributes:
-
url
(Optional[str]
) –Database connection string, see https://neo4j.com/docs/api/python-driver/current/api.html#uri.
-
database
(Optional[str]
) –Database name to connect.
-
username
(Optional[str]
) –Username to authenticate with the database.
-
password
(Optional[str]
) –Password credential for the given username.
-
driver_config
(Neo4jDriverConfig
) –Additional driver configuration.
-
session_config
(Neo4jSessionConfig
) –Additional session configuration.
-
transaction_config
(Neo4jTransactionConfig
) –Additional transaction configuration (e.g.
timeout
) -
use_env
(Optional[bool]
) –
Raises:
-
ValueError
–In case conflicting auth credentials are provided - choose either username/password combination or
driver_config.auth
.
Source code in src/neo4j_haystack/client/neo4j_client.py
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 |
|
to_dict ¤
Serializes client configuration to a dictionary.
Source code in src/neo4j_haystack/client/neo4j_client.py
from_dict
classmethod
¤
Deserializes client configuration from a dictionary.
Neo4jClient ¤
Neo4j Python Driver wrapper to run low level database transactions using Cypher queries. It abstracts away Neo4j
related details from Neo4jDocumentStore
so that database related interactions are encapsulated in a single
place.
Neo4jClient
can be created with a number of configuration options represented by the Neo4jClientConfig
data
class. The configuration applied when connecting to a database or running transactions.
Attributes:
-
_config
–Neo4j configuration options.
-
_driver
–An instance of neo4j.Driver which is used to start a session for transaction execution.
-
_filter_converter
–Instance of
Neo4jQueryConverter
which converts parsed Metadata filters to Cypher queries.
Source code in src/neo4j_haystack/client/neo4j_client.py
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 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 |
|
delete_nodes ¤
Deletes nodes with with given label and filters using DELETE Cypher clause.
Parameters:
-
node_label
(str
) –The name of the label to delete (e.g.
"Document"
) -
filter_ast
(Optional[AST]
, default:None
) –Metadata filters to delete only specific nodes which match filtering conditions.
Source code in src/neo4j_haystack/client/neo4j_client.py
create_index ¤
create_index(
index_name: str,
label: str,
property_key: str,
dimension: int,
similarity_function: SimilarityFunction,
) -> None
Creates a new vector index in database for a given node label and vector specific attributes (e.g. dimension, similarity function etc). See documentation for the index creation procedure db.index.vector.createNodeIndex
Parameters:
-
index_name
(str
) –The unique name of the index.
-
label
(str
) –The node label to be indexed (e.g.
"Document"
). -
property_key
(str
) –The property key of a node which contains embedding values.
-
dimension
(int
) –Vector embedding dimension (must be between 1 and 2048 inclusively).
-
similarity_function
(SimilarityFunction
) –case-insensitive values for the vector similarity function:
cosine
oreuclidean
.
Source code in src/neo4j_haystack/client/neo4j_client.py
retrieve_vector_index ¤
retrieve_vector_index(
index_name: str, node_label: str, property_key: str
) -> Optional[VectorStoreIndexInfo]
Retrieves information about existing vector index.
For more details and an example query on how to obtain existing indexes see Query a vector index.
Parameters:
-
index_name
(str
) –The name of the vector index to retrieve.
-
node_label
(str
) –The label of the node configured as prt of vector index setup.
-
property_key
(str
) –The property key configured as part of vector index setup.
Raises:
-
Neo4jClientError
–If more than one index found matching search criteria (same index name OR label+property combination).
Returns:
-
Optional[VectorStoreIndexInfo]
–Data retrieved from the query execution or
None
if index was not found.
Source code in src/neo4j_haystack/client/neo4j_client.py
create_index_if_missing ¤
create_index_if_missing(
index_name: str,
label: str,
property_key: str,
dimension: int,
similarity_function: SimilarityFunction,
)
Creates a vector index in case it does not exist in database. Uses same parameters as create_index method.
Source code in src/neo4j_haystack/client/neo4j_client.py
delete_index ¤
Removes index from Neo4j database.
See Cypher manual on Drop vector indexes
Parameters:
-
index_name
(str
) –The name of the index to delete.
Source code in src/neo4j_haystack/client/neo4j_client.py
update_embedding ¤
Updates embedding on a number of Document
nodes. It uses db.create.setNodeVectorProperty()
procedure as
a recommended update method. See more details in Set a vector property on a node
Parameters:
-
node_label
(str
) –A node label to match (e.g.
"Document"
). -
embedding_field
(str
) –The name of the embedding field which stores embeddings (of type
LIST<FLOAT>
) as part node properties. -
records
(List[Dict[str, Any]]
) –
Source code in src/neo4j_haystack/client/neo4j_client.py
merge_nodes ¤
Creates or updates a node in neo4j representing a Document with all properties. Nodes are matched by "id", if not found a new node will be created. See the following manuals:
Parameters:
-
node_label
(str
) –The label of the node to match (e.g. "Document").
-
embedding_field
(str
) –The name of the embedding field which stores embeddings (of type
LIST<FLOAT>
) as part of node properties. Embeddings (if present) will be updated/set bydb.create.setNodeVectorProperty()
procedure -embedding_field
is excluded fromSET
Cypher clause by using map projections. -
records
(List[Neo4jRecord]
) –A list of Documents converted to dictionaries, with
meta
attributes included.
Source code in src/neo4j_haystack/client/neo4j_client.py
count_nodes ¤
Counts number of nodes matching given label and optional filters.
Parameters:
-
node_label
(str
) –The label of the node to match (e.g.
"Document"
). -
filter_ast
(Optional[AST]
, default:None
) –The filter syntax tree (parsed metadata filter) to narrow down counted results.
Returns:
-
int
–Number of found nodes.
Source code in src/neo4j_haystack/client/neo4j_client.py
find_nodes ¤
find_nodes(
node_label: str,
filter_ast: Optional[AST] = None,
skip_properties: Optional[List[str]] = None,
fetch_size: int = 1000,
) -> Generator[Neo4jRecord, None, None]
Search for nodes matching a given label and metadata filters.
Parameters:
-
node_label
(str
) –The label of the nodes to match (e.g.
"Document"
). -
filter_ast
(Optional[AST]
, default:None
) –The filter syntax tree (parsed metadata filter) for search.
-
skip_properties
(Optional[List[str]]
, default:None
) –Properties we would like not to return as part of data payload. Is uses map projection Cypher syntax, e.g.
doc{.*, embedding: null}
- such construct will make sureembedding
is not returned back in results. -
fetch_size
(int
, default:1000
) –Controls how many records are fetched at once from the database which helps with batching process.
Returns:
-
None
–Found records matching search criteria.
Source code in src/neo4j_haystack/client/neo4j_client.py
query_nodes ¤
query_nodes(
query: str,
parameters: Optional[Dict[str, Any]] = None,
fetch_size: int = 1000,
) -> Generator[Record, None, None]
Runs a given Cypher query
. The implementation is based on Unmanaged Transactions
for greater control and possibility to yield
results as soon as those are fetched from database. The Neo4j
python driver internally manages a buffer which replenished while records are being consumed thus making sure we
do not store all fetched records in memory. That greatly simplifies batching mechanism as it is implemented by
the buffer. See more details about how python driver implements Explicit/Unmanaged Transactions
Note
Please notice results are yielded while read transaction is still open. That should impact your choice of transaction timeout setting, see Neo4jClientConfig.
Parameters:
-
query
(str
) –Cypher query to run in Neo4j.
-
parameters
(Optional[Dict[str, Any]]
, default:None
) –Query parameters which can be used as placeholders in the
query
. -
fetch_size
(int
, default:1000
) –Controls how many records are fetched at once from the database which helps with batching process.
Returns:
-
None
–Records containing data specified in
RETURN
Cypher query statement.
Source code in src/neo4j_haystack/client/neo4j_client.py
query_embeddings ¤
query_embeddings(
index: str,
top_k: int,
embedding: List[float],
filter_ast: Optional[AST] = None,
skip_properties: Optional[List[str]] = None,
vector_top_k: Optional[int] = None,
) -> List[Neo4jRecord]
Query a vector index and apply filtering using WHERE
clause on results returned by vector search.
See the following documentation for more details:
Parameters:
-
index
(str
) –Refers to the unique name of the vector index to query.
-
top_k
(int
) –Number of results to return from vector search.
-
embedding
(List[float]
) –The query vector (a
LIST<FLOAT>
) in which to search for the neighborhood. -
filter_ast
(Optional[AST]
, default:None
) –Additional filters translated into
WHERE
Cypher clause by Neo4jQueryConverter -
skip_properties
(Optional[List[str]]
, default:None
) –Properties we would like not to return as part of data payload. Is uses map projection Cypher syntax, e.g.
doc{.*, embedding: null}
- such construct will make sureembedding
is not returned back in results. -
vector_top_k
(Optional[int]
, default:None
) –If provided
vector_top_k
is used instead oftop_k
in order to increase number of results (nearest neighbors) from vector search. It makes sense when filters (filter_ast
) could further narrow down vector search result. Onlytop_k
number of records will be returned back thusvector_top_k
should be preferably greater thantop_k
.
Returns:
An ordered by score top_k
nodes found in vector search which are optionally filtered using
WHERE
clause.
Source code in src/neo4j_haystack/client/neo4j_client.py
execute_write ¤
execute_write(
query: str, parameters: Optional[Dict[str, Any]] = None
) -> Tuple[ResultSummary, List[Dict[str, Any]]]
Runs an arbitrary write Cypher query with parameters.
Parameters:
-
query
(str
) –Cypher query to run in Neo4j.
-
parameters
(Optional[Dict[str, Any]]
, default:None
) –Query parameters which can be used as placeholders in the
query
.
Returns:
-
Tuple[ResultSummary, List[Dict[str, Any]]]
–A tuple consisting of execution result summary (
neo4j.ResultSummary
) and data records (dict
) if any.
Source code in src/neo4j_haystack/client/neo4j_client.py
execute_read ¤
execute_read(
query: str, parameters: Optional[Dict[str, Any]] = None
) -> Tuple[ResultSummary, List[Dict[str, Any]]]
Runs an arbitrary "read" Cypher query with parameters.
Parameters:
-
query
(str
) –Cypher query to run in Neo4j.
-
parameters
(Optional[Dict[str, Any]]
, default:None
) –Query parameters which can be used as placeholders in the
query
.
Returns:
-
Tuple[ResultSummary, List[Dict[str, Any]]]
–A tuple consisting of execution result summary (
neo4j.ResultSummary
) and data records if any.
Source code in src/neo4j_haystack/client/neo4j_client.py
update_node ¤
Updates a given node matched by the given id (doc_id
). Properties are mutated by +=
operator,
see more details in Setting properties using map.
Parameters:
-
node_label
(str
) –A node label to match (e.g. "Document").
-
doc_id
(str
) –Node id to match. Please notice the
id
used in Cypher query is not a native element id but the one which mapped from the haystack.schema.Document. -
data
(Dict[str, Any]
) –A dictionary of data which will be set as node's properties.
Returns:
-
Optional[Neo4jRecord]
–Updated Neo4j record data.
Source code in src/neo4j_haystack/client/neo4j_client.py
verify_connectivity ¤
Verifies connection to Neo4j database as per configuration and auth credentials provided.
Raises:
-
Neo4jClientError
–In case connection could not be established.
Source code in src/neo4j_haystack/client/neo4j_client.py
_begin_session ¤
Creates a database session with common as well as client specific configuration settings.
Returns:
-
Session
–A new
Session
object to execute transactions.
Source code in src/neo4j_haystack/client/neo4j_client.py
_unit_of_work ¤
An extended version of managed transaction decorator to pass through configuration options from
self._config.transaction_config
:
metadata
- will be attached to the executing transactiontimeout
- the transaction timeout in seconds
See more details in Managed Transactions
Returns:
-
Callable
–A pre-configured neo4j.unit_of_work decorator
Source code in src/neo4j_haystack/client/neo4j_client.py
_where_clause ¤
Converts a given filter syntax tree filter_ast
into a Cypher query in order to build WHERE
filter clause.
Along with the query method also returns parameters used in the query to be included into final request.
Find out more details about WHERE clause
Parameters:
-
filter_ast
(Optional[AST]
) –Filters AST to be converted into Cypher query by Neo4jQueryConverter.convert.
Returns:
WHERE
filter clause used in filtering logic (e.g. WHERE doc.age > $age
) as well as
parameters used in the clause (e.g. {"age": 25}
)
Source code in src/neo4j_haystack/client/neo4j_client.py
_map_projection ¤
Creates a map projection Cypher query syntax with the option to skip certain properties.
Example query would be {.*, embedding=null}
, where skip_properties=["embedding"]
See Neo4j manual about Map Projections
Parameters:
-
skip_properties
(Optional[List[str]]
) –a list of property names to skip (set values to
null
) from map projection.
Returns:
-
str
–A map projection Cypher query with skipped properties if any.
Source code in src/neo4j_haystack/client/neo4j_client.py
_vector_store_index_info ¤
Creates a dataclass from a data record returned by a SHOW INDEXES
Cypher query output.
See Neo4j manual for SHOW INDEXES
Parameters:
-
record
(Record
) –A Neo4j record containing
SHOW INDEXES
output.
Returns:
-
VectorStoreIndexInfo
–Custom dataclass with vector index information.