|
13 | 13 | # See the License for the specific language governing permissions and
|
14 | 14 | # limitations under the License.
|
15 | 15 | from __future__ import annotations
|
| 16 | +import pandas as pd |
16 | 17 |
|
17 | 18 | import logging
|
18 | 19 | from abc import abstractmethod
|
| 20 | +from collections import defaultdict |
| 21 | +from pathlib import Path |
19 | 22 | from typing import Any, Generator, Literal, Optional
|
20 | 23 |
|
21 | 24 | import neo4j
|
@@ -83,6 +86,100 @@ async def run(
|
83 | 86 | pass
|
84 | 87 |
|
85 | 88 |
|
| 89 | +class ParquetWriter(KGWriter): |
| 90 | + """Writes a knowledge graph to Parquet files. |
| 91 | +
|
| 92 | + Args: |
| 93 | + node_file_path (str): The file path to write the nodes Parquet file. |
| 94 | + relationship_file_path (str): The file path to write the relationships Parquet file. |
| 95 | + """ |
| 96 | + |
| 97 | + def __init__( |
| 98 | + self, |
| 99 | + output_folder: str, |
| 100 | + ): |
| 101 | + self._output_folder = Path(output_folder) |
| 102 | + |
| 103 | + @staticmethod |
| 104 | + def _nodes_to_rows( |
| 105 | + nodes: list[Neo4jNode], |
| 106 | + label_to_rows: dict[str, list[dict[str, Any]]], |
| 107 | + lexical_graph_config: LexicalGraphConfig, |
| 108 | + ) -> None: |
| 109 | + for node in nodes: |
| 110 | + row: dict[str, Any] = dict() |
| 111 | + |
| 112 | + labels = [node.label] |
| 113 | + if node.label not in lexical_graph_config.lexical_graph_node_labels: |
| 114 | + labels.append("__Entity__") |
| 115 | + |
| 116 | + row["id"] = node.id |
| 117 | + row["labels"] = labels |
| 118 | + row.update(node.properties) |
| 119 | + if node.embedding_properties is not None: |
| 120 | + row.update(node.embedding_properties) |
| 121 | + |
| 122 | + label_to_rows[node.label].append(row) |
| 123 | + |
| 124 | + @staticmethod |
| 125 | + def _relationships_to_rows( |
| 126 | + relationships: list[Neo4jRelationship], |
| 127 | + type_to_rows: dict[str, list[dict[str, Any]]], |
| 128 | + ) -> None: |
| 129 | + for rel in relationships: |
| 130 | + row: dict[str, Any] = dict() |
| 131 | + |
| 132 | + row["from"] = rel.start_node_id |
| 133 | + row["to"] = rel.end_node_id |
| 134 | + row["type"] = rel.type |
| 135 | + row.update(rel.properties) |
| 136 | + if rel.embedding_properties is not None: |
| 137 | + row.update(rel.embedding_properties) |
| 138 | + |
| 139 | + type_to_rows[rel.type].append(row) |
| 140 | + |
| 141 | + @validate_call |
| 142 | + async def run( |
| 143 | + self, |
| 144 | + graph: Neo4jGraph, |
| 145 | + lexical_graph_config: LexicalGraphConfig = LexicalGraphConfig(), |
| 146 | + ) -> KGWriterModel: |
| 147 | + """Writes a knowledge graph to Parquet files. |
| 148 | +
|
| 149 | + Args: |
| 150 | + graph (Neo4jGraph): The knowledge graph to write to Parquet files. |
| 151 | + lexical_graph_config (LexicalGraphConfig): Node labels and relationship types for the lexical graph. |
| 152 | + """ |
| 153 | + (self._output_folder / "nodes").mkdir(parents=True, exist_ok=True) |
| 154 | + (self._output_folder / "relationships").mkdir(parents=True, exist_ok=True) |
| 155 | + |
| 156 | + label_to_rows: defaultdict[str, list[dict[str, Any]]] = defaultdict(list) |
| 157 | + type_to_rows: defaultdict[str, list[dict[str, Any]]] = defaultdict(list) |
| 158 | + |
| 159 | + # TODO: Parallelize? |
| 160 | + self._nodes_to_rows(graph.nodes, label_to_rows, lexical_graph_config) |
| 161 | + self._relationships_to_rows(graph.relationships, type_to_rows) |
| 162 | + |
| 163 | + for label, node_df in label_to_rows.items(): |
| 164 | + pd.DataFrame(node_df).to_parquet( |
| 165 | + self._output_folder / "nodes" / f"{label}.parquet", index=False |
| 166 | + ) |
| 167 | + |
| 168 | + for rtype, rel_df in type_to_rows.items(): |
| 169 | + pd.DataFrame(rel_df).to_parquet( |
| 170 | + self._output_folder / "relationships" / f"{rtype}.parquet", index=False |
| 171 | + ) |
| 172 | + |
| 173 | + return KGWriterModel( |
| 174 | + status="SUCCESS", |
| 175 | + metadata={ |
| 176 | + "node_count": len(graph.nodes), |
| 177 | + "relationship_count": len(graph.relationships), |
| 178 | + "output_folder": str(self._output_folder), |
| 179 | + }, |
| 180 | + ) |
| 181 | + |
| 182 | + |
86 | 183 | class Neo4jWriter(KGWriter):
|
87 | 184 | """Writes a knowledge graph to a Neo4j database.
|
88 | 185 |
|
|
0 commit comments