-
Notifications
You must be signed in to change notification settings - Fork 46
perf(graph): batch DB operations for entity insertion #624
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
base: staging
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -1,10 +1,18 @@ | ||||||
| import os | ||||||
| import re | ||||||
| import time | ||||||
| from collections import defaultdict | ||||||
| from .entities import * | ||||||
| from typing import Optional | ||||||
| from falkordb import FalkorDB, Path, Node, QueryResult | ||||||
| from falkordb.asyncio import FalkorDB as AsyncFalkorDB | ||||||
|
|
||||||
| # Maximum items per UNWIND batch to avoid overwhelming FalkorDB/Redis | ||||||
| BATCH_SIZE = 500 | ||||||
|
|
||||||
| # Regex to validate graph labels/relation types (alphanumeric + underscore only) | ||||||
| _VALID_LABEL_RE = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$') | ||||||
|
|
||||||
| # Configure the logger | ||||||
| import logging | ||||||
| logging.basicConfig(level=logging.DEBUG, | ||||||
|
|
@@ -248,6 +256,9 @@ def add_entity(self, label: str, name: str, doc: str, path: str, src_start: int, | |||||
| Args: | ||||||
| """ | ||||||
|
|
||||||
| if not _VALID_LABEL_RE.match(label): | ||||||
| raise ValueError(f"Invalid entity label: {label!r}") | ||||||
|
|
||||||
| q = f"""MERGE (c:{label}:Searchable {{name: $name, path: $path, src_start: $src_start, | ||||||
| src_end: $src_end}}) | ||||||
| SET c.doc = $doc | ||||||
|
|
@@ -267,6 +278,47 @@ def add_entity(self, label: str, name: str, doc: str, path: str, src_start: int, | |||||
| node = res.result_set[0][0] | ||||||
| return node.id | ||||||
|
|
||||||
| def add_entities_batch(self, entities_data: list) -> None: | ||||||
| """ | ||||||
| Batch add entity nodes to the graph database using UNWIND. | ||||||
| Groups by label, then processes in chunks of BATCH_SIZE. | ||||||
|
|
||||||
| Args: | ||||||
| entities_data: list of tuples | ||||||
| (entity_obj, label, name, doc, path, src_start, src_end, props) | ||||||
| entity_obj.id will be set after insertion. | ||||||
| """ | ||||||
|
|
||||||
| if not entities_data: | ||||||
| return | ||||||
|
|
||||||
| by_label = defaultdict(list) | ||||||
| for item in entities_data: | ||||||
| by_label[item[1]].append(item) | ||||||
|
|
||||||
| for label, group in by_label.items(): | ||||||
| if not _VALID_LABEL_RE.match(label): | ||||||
| raise ValueError(f"Invalid entity label: {label!r}") | ||||||
|
|
||||||
| q = f"""UNWIND $entities AS e | ||||||
| MERGE (c:{label}:Searchable {{name: e['name'], path: e['path'], | ||||||
| src_start: e['src_start'], | ||||||
| src_end: e['src_end']}}) | ||||||
| SET c.doc = e['doc'] | ||||||
| SET c += e['props'] | ||||||
| RETURN c""" | ||||||
|
|
||||||
| for start in range(0, len(group), BATCH_SIZE): | ||||||
| chunk = group[start:start + BATCH_SIZE] | ||||||
| data = [{ | ||||||
| 'name': item[2], 'doc': item[3], 'path': item[4], | ||||||
| 'src_start': item[5], 'src_end': item[6], 'props': item[7] | ||||||
| } for item in chunk] | ||||||
|
|
||||||
| res = self._query(q, {'entities': data}) | ||||||
| for j, item in enumerate(chunk): | ||||||
| item[0].id = res.result_set[j][0].id | ||||||
|
|
||||||
| def get_class_by_name(self, class_name: str) -> Optional[Node]: | ||||||
| q = "MATCH (c:Class) WHERE c.name = $name RETURN c LIMIT 1" | ||||||
| res = self._query(q, {'name': class_name}).result_set | ||||||
|
|
@@ -406,6 +458,30 @@ def add_file(self, file: File) -> None: | |||||
| node = res.result_set[0][0] | ||||||
| file.id = node.id | ||||||
|
|
||||||
| def add_files_batch(self, files: list[File]) -> None: | ||||||
| """ | ||||||
| Batch add file nodes to the graph database using UNWIND. | ||||||
| Processes in chunks of BATCH_SIZE to avoid oversized queries. | ||||||
|
|
||||||
| Args: | ||||||
| files: list of File objects. Each file.id will be set after insertion. | ||||||
| """ | ||||||
|
|
||||||
| if not files: | ||||||
| return | ||||||
|
|
||||||
| q = """UNWIND $files AS fd | ||||||
| MERGE (f:File:Searchable {path: fd['path'], name: fd['name'], ext: fd['ext']}) | ||||||
| RETURN f""" | ||||||
|
|
||||||
| for start in range(0, len(files), BATCH_SIZE): | ||||||
| chunk = files[start:start + BATCH_SIZE] | ||||||
| file_data = [{'path': str(f.path), 'name': f.path.name, 'ext': f.path.suffix} | ||||||
| for f in chunk] | ||||||
| res = self._query(q, {'files': file_data}) | ||||||
| for i, row in enumerate(res.result_set): | ||||||
| chunk[i].id = row[0].id | ||||||
|
|
||||||
| def delete_files(self, files: list[Path]) -> tuple[str, dict, list[int]]: | ||||||
| """ | ||||||
| Deletes file(s) from the graph in addition to any other entity | ||||||
|
|
@@ -485,6 +561,44 @@ def connect_entities(self, relation: str, src_id: int, dest_id: int, properties: | |||||
| params = {'src_id': src_id, 'dest_id': dest_id, "properties": properties} | ||||||
| self._query(q, params) | ||||||
|
|
||||||
| def connect_entities_batch(self, relationships: list[tuple[str, int, int, dict]]) -> None: | ||||||
| """ | ||||||
| Batch create relationships between entities using UNWIND. | ||||||
| Groups by relation type, then processes in chunks of BATCH_SIZE. | ||||||
|
|
||||||
| Args: | ||||||
| relationships: list of (relation, src_id, dest_id, properties) | ||||||
| """ | ||||||
|
|
||||||
| if not relationships: | ||||||
| return | ||||||
|
|
||||||
| by_relation = defaultdict(list) | ||||||
| for rel in relationships: | ||||||
| if rel[1] is None or rel[2] is None: | ||||||
| logging.warning(f"Skipping relationship {rel[0]} with None ID: src={rel[1]}, dest={rel[2]}") | ||||||
| continue | ||||||
| by_relation[rel[0]].append(rel) | ||||||
|
|
||||||
| for relation, group in by_relation.items(): | ||||||
| if not _VALID_LABEL_RE.match(relation): | ||||||
| raise ValueError(f"Invalid relation type: {relation!r}") | ||||||
|
|
||||||
| q = f"""UNWIND $rels AS r | ||||||
| MATCH (src) | ||||||
| WHERE ID(src) = r['src_id'] | ||||||
| MATCH (dest) | ||||||
| WHERE ID(dest) = r['dest_id'] | ||||||
| MERGE (src)-[e:{relation}]->(dest) | ||||||
|
||||||
| MERGE (src)-[e:{relation}]->(dest) | |
| CREATE (src)-[e:{relation}]->(dest) |
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.
add_entities_batchinterpolateslabeldirectly into the Cypher string. Since labels can’t be parameterized, this should defensively validatelabel(e.g., allowlist known entity labels or enforce a strict[A-Za-z0-9_]+regex) to avoid Cypher injection if this method is ever called with untrusted input.