├── .github └── workflows │ └── pypi.yaml ├── .gitignore ├── LICENSE ├── README.md ├── docs └── API.md ├── ng_nx ├── __init__.py ├── query_reader.py ├── scan_reader.py ├── utils.py └── writer.py ├── pdm.lock ├── pyproject.toml └── tests ├── integration └── setup │ └── docker-compose.yaml └── unit └── test_query_reader.py /.github/workflows/pypi.yaml: -------------------------------------------------------------------------------- 1 | name: Upload package to pypi 2 | 3 | on: 4 | release: 5 | types: 6 | - published 7 | 8 | jobs: 9 | ci: 10 | runs-on: ubuntu-22.04 11 | 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: pdm-project/setup-pdm@v4 15 | with: 16 | python-version: '3.x' 17 | cache: true 18 | 19 | - name: Build and publish 20 | env: 21 | PDM_PUBLISH_USERNAME: __token__ 22 | PDM_PUBLISH_PASSWORD: ${{ secrets.PYPI_PASSWORD }} 23 | run: pdm publish 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | # pdm 132 | .pdm-python 133 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | NebulaGraph NetworkX Adaptor(ng_nx) 2 | 3 |

4 | Manipulate and analyze NebulaGraph data using the NetworkX API 5 |

6 | 7 |

8 | 9 | License 10 | 11 | 12 | PyPI version 13 | 14 | 15 | pdm-managed 16 | 17 |

18 | 19 | --- 20 | 21 | **Documentation**: https://github.com/wey-gu/nebulagraph-nx#documentation 22 | 23 | **Source Code**: https://github.com/wey-gu/nebulagraph-nx 24 | 25 | --- 26 | 27 | ## Table of Contents 28 | 29 | - [Introduction](#introduction) 30 | - [Features](#features) 31 | - [Installation](#installation) 32 | - [Usage](#usage) 33 | - [Reading Data from NebulaGraph](#reading-data-from-nebulagraph) 34 | - [Running Algorithms](#running-algorithms) 35 | - [Writing Results Back to NebulaGraph](#writing-results-back-to-nebulagraph) 36 | - [Advanced Usage](#advanced-usage) 37 | - [NebulaQueryReader](#nebulaqueryreader) 38 | - [Readers](#readers) 39 | - [Documentation](#documentation) 40 | - [Contributing](#contributing) 41 | 42 | ## Introduction 43 | 44 | NebulaGraph NetworkX (ng_nx) is a powerful tool that bridges NebulaGraph and NetworkX, enabling you to leverage NetworkX's rich set of graph algorithms and analysis tools on data stored in NebulaGraph. This integration combines NebulaGraph's advanced storage capabilities with NetworkX's extensive graph analysis functionality. 45 | 46 | ## Features 47 | 48 | - Seamless integration between NebulaGraph and NetworkX 49 | - Multiple reader types for flexible data retrieval 50 | - Easy-to-use writers for storing analysis results back to NebulaGraph 51 | - Support for both vertex and edge data operations 52 | - Compatibility with NetworkX's extensive library of graph algorithms 53 | 54 | ## Installation 55 | 56 | Ensure you have a NebulaGraph cluster running. For a quick setup, you can use [NebulaGraph Lite](https://github.com/nebula-contrib/nebulagraph-lite) to set up a cluster in Colab within 5 minutes. 57 | 58 | Install ng_nx using pip: 59 | 60 | ```bash 61 | pip install ng_nx 62 | ``` 63 | 64 | ## Usage 65 | 66 | ### Reading Data from NebulaGraph 67 | 68 | > With GraphD Client 69 | 70 | ```python 71 | from ng_nx import NebulaReader 72 | from ng_nx.utils import NebulaGraphConfig 73 | 74 | config = NebulaGraphConfig( 75 | space="basketballplayer", 76 | graphd_hosts="127.0.0.1:9669", 77 | metad_hosts="127.0.0.1:9559" 78 | ) 79 | 80 | reader = NebulaReader( 81 | edges=["follow", "serve"], 82 | properties=[["degree"], ["start_year", "end_year"]], 83 | nebula_config=config, limit=10000) 84 | 85 | g = reader.read() 86 | ``` 87 | 88 | > With Storage Client, this requires ng_nx being run within NebulaGraph Network or expose the metad and storaged to it, with same host and port being registered in NebulaGraph(`SHOW HOSTS META;` and `SHOW HOSTS;`). 89 | 90 | ```python 91 | from ng_nx import NebulaScanReader 92 | from ng_nx.utils import NebulaGraphConfig 93 | 94 | # Here, we need to be able to resolve the metad and storaged hosts, where they are the same with `SHOW HOSTS META;` and `SHOW HOSTS;` 95 | 96 | config = NebulaGraphConfig( 97 | space="demo_basketballplayer", 98 | graphd_hosts="graphd0:9669", 99 | metad_hosts="metad0:9559" 100 | ) 101 | 102 | reader = NebulaScanReader( 103 | edges=["follow", "serve"], 104 | properties=[["degree"], ["start_year", "end_year"]], 105 | nebula_config=config, limit=10000, with_rank=True) 106 | 107 | g = reader.read() 108 | ``` 109 | 110 | ### Running Algorithms 111 | 112 | We need to install louvain and graspologic first, to run louvain and leiden algorithm that are not included in NetworkX(not like Pagerank etc). 113 | 114 | ```bash 115 | pip3 install python-louvain graspologic 116 | ``` 117 | 118 | Then we can run the algorithms. 119 | 120 | ```python 121 | import networkx as nx 122 | import community as community_louvain 123 | 124 | # Run PageRank algorithm 125 | pr = nx.pagerank( 126 | g, alpha=0.85, 127 | max_iter=100, 128 | tol=1e-06, 129 | weight='degree') 130 | 131 | # Run Louvain community detection 132 | ug = g.to_undirected() 133 | louvain = community_louvain.best_partition(ug) 134 | 135 | # Run Leiden community detection 136 | 137 | from graspologic.partition import hierarchical_leiden 138 | 139 | # Cast Multi-Graph to Homogeneous Graph 140 | g = nx.Graph(g) 141 | community_hierarchical_clusters = hierarchical_leiden(ug, max_cluster_size=10) 142 | ``` 143 | 144 | ### Writing Results Back to NebulaGraph 145 | 146 | Typical use cases are: 147 | 148 | 1. Write the result of graph algorithm to NebulaGraph as vertex data. 149 | 2. Write the result of graph algorithm to NebulaGraph as edge data. 150 | 151 | #### Write Vertex Data to NebulaGraph after Graph Analysis 152 | 153 | We could create schema for pagerank and louvain like this: 154 | 155 | ```sql 156 | CREATE TAG IF NOT EXISTS pagerank ( 157 | pagerank double NOT NULL 158 | ); 159 | 160 | CREATE TAG IF NOT EXISTS louvain ( 161 | cluster_id int NOT NULL 162 | ); 163 | ``` 164 | 165 | Then we can run pagerank and louvain algorithm and write the result to NebulaGraph like this: 166 | 167 | ```python 168 | from ng_nx import NebulaWriter 169 | 170 | pr_writer = NebulaWriter(data=pr, nebula_config=config) 171 | 172 | # properties to write 173 | properties = ["pagerank"] 174 | 175 | pr_writer.set_options( 176 | label="pagerank", 177 | properties=properties, 178 | batch_size=256, 179 | write_mode="insert", 180 | sink="nebulagraph_vertex", 181 | ) 182 | # write back to NebulaGraph 183 | pr_writer.write() 184 | 185 | # write louvain result 186 | 187 | louvain_writer = NebulaWriter(data=louvain, nebula_config=config) 188 | # properties to write 189 | properties = ["cluster_id"] 190 | louvain_writer.set_options( 191 | label="louvain", 192 | properties=properties, 193 | batch_size=256, 194 | write_mode="insert", 195 | sink="nebulagraph_vertex", 196 | ) 197 | louvain_writer.write() # write back to NebulaGraph 198 | 199 | ``` 200 | 201 | #### Write Edge Data to NebulaGraph after Graph Analysis 202 | 203 | Say we have a graph with player and follow edge, we can write the result to NebulaGraph like this: 204 | 205 | ```sql 206 | CREATE TAG IF NOT EXISTS player ( 207 | name string NOT NULL, 208 | age int NOT NULL 209 | ); 210 | 211 | CREATE EDGE IF NOT EXISTS follow ( 212 | start_year int NOT NULL, 213 | end_year int NOT NULL 214 | ); 215 | ``` 216 | 217 | We can write the result to NebulaGraph like this: 218 | 219 | ```python 220 | from ng_nx import NebulaWriter 221 | 222 | # Example edge data 223 | edge_data = [ 224 | ("player1", "player2", 0, [2022, 2023]), # src, dst, rank, [start_year, end_year] 225 | ("player2", "player3", 1, [2021, 2022]), 226 | # ... more edges ... 227 | ] 228 | 229 | edge_writer = NebulaWriter(data=edge_data, nebula_config=config) 230 | 231 | # properties to write, map the properties to the edge data 232 | properties = ["start_year", "end_year"] 233 | 234 | edge_writer.set_options( 235 | label="follow", # Edge type name 236 | properties=properties, 237 | batch_size=256, 238 | write_mode="insert", 239 | sink="nebulagraph_edge", 240 | ) 241 | 242 | # Write edges to NebulaGraph 243 | edge_writer.write() 244 | ``` 245 | 246 | ### Using NebulaQueryReader 247 | 248 | The `NebulaQueryReader` allows you to execute any NebulaGraph query and construct a NetworkX graph from the result. 249 | 250 | ```python 251 | from ng_nx import NebulaQueryReader 252 | from ng_nx.utils import NebulaGraphConfig 253 | 254 | config = NebulaGraphConfig( 255 | space="demo_basketballplayer", 256 | graphd_hosts="127.0.0.1:9669", 257 | metad_hosts="127.0.0.1:9559" 258 | ) 259 | 260 | reader = NebulaQueryReader(nebula_config=config) 261 | 262 | # Execute a custom query 263 | query = "MATCH p=(v:player{name:'Tim Duncan'})-[e:follow*1..3]->(v2) RETURN p" 264 | g = reader.read(query) 265 | ``` 266 | 267 | This approach allows you to leverage the full power of NebulaGraph's query language while still being able to analyze the results using NetworkX. 268 | 269 | ## Advanced Usage 270 | 271 | ### NebulaQueryReader 272 | 273 | The `NebulaQueryReader` allows you to execute any NebulaGraph query and construct a NetworkX graph from the result. 274 | 275 | ```python 276 | from ng_nx import NebulaQueryReader 277 | from ng_nx.utils import NebulaGraphConfig 278 | 279 | config = NebulaGraphConfig( 280 | space="demo_basketballplayer", 281 | graphd_hosts="127.0.0.1:9669", 282 | metad_hosts="127.0.0.1:9559" 283 | ) 284 | 285 | reader = NebulaQueryReader(nebula_config=config) 286 | 287 | # Execute a custom query 288 | query = "MATCH p=(v:player{name:'Tim Duncan'})-[e:follow*1..3]->(v2) RETURN p" 289 | g = reader.read(query) 290 | ``` 291 | 292 | ## Readers 293 | 294 | NG-NX provides three types of readers to fetch data from NebulaGraph: 295 | 296 | 1. `NebulaReader`(**Load from Edge and Properties via MATCH**): Reads a graph from NebulaGraph based on specified edges and properties, returning a NetworkX graph. It uses the MATCH clause internally to fetch data from NebulaGraph. 297 | 298 | 2. `NebulaQueryReader`(**Construct from Any Query**): Executes a custom NebulaGraph query and constructs a NetworkX graph from the result. This reader is particularly useful when you need to perform complex queries or have specific data retrieval requirements. 299 | 300 | 3. `NebulaScanReader`(**Better for LARGE datasets**): Will read graph data from NebulaGraph using a configuration similar to `NebulaReader`, but it will bypass the MATCH clause and utilize the SCAN interface with the Storage Client for potentially improved performance on large datasets. Note that this reader requires the NebulaGraph cluster to configure the metad and storaged accessible from the ng_nx. 301 | 302 | Each reader is designed to cater to different use cases, providing flexibility in how you interact with and retrieve data from NebulaGraph for analysis with NetworkX. 303 | 304 | ## Documentation 305 | 306 | [API Reference](https://github.com/wey-gu/nebulagraph-nx/blob/main/docs/API.md) 307 | 308 | ## Contributing 309 | 310 | Contributions are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request on the [GitHub repository](https://github.com/wey-gu/nebulagraph-nx). 311 | -------------------------------------------------------------------------------- /docs/API.md: -------------------------------------------------------------------------------- 1 | ## NebulaReader 2 | 3 | ```python 4 | from ng_nx import NebulaReader 5 | from ng_nx.utils import NebulaGraphConfig 6 | 7 | import networkx as nx 8 | 9 | config_dict = { 10 | "graphd_hosts": "127.0.0.1:9669", 11 | "user": "root", 12 | "password": "nebula", 13 | "space": "basketballplayer", 14 | } 15 | config = NebulaGraphConfig(**config_dict) 16 | 17 | reader = NebulaReader( 18 | edges=["follow", "serve"], 19 | properties=[["degree"], ["start_year", "end_year"]], 20 | with_rank=True, # this enable the multi-graph, and the edge_key is "__rank__" from NebulaGraph rank(edge) 21 | nebula_config=config, limit=100) 22 | 23 | g = reader.read() 24 | 25 | # call pagerank algorithm 26 | pr = nx.pagerank( 27 | g, alpha=0.85, 28 | max_iter=100, 29 | tol=1e-06, 30 | weight='degree') 31 | ``` 32 | 33 | 34 | ## NebulaQueryReader 35 | 36 | The `NebulaQueryReader` allows you to execute any NebulaGraph query and construct a NetworkX graph from the result. 37 | 38 | ```python 39 | from ng_nx import NebulaQueryReader 40 | from ng_nx.utils import NebulaGraphConfig 41 | 42 | config = NebulaGraphConfig( 43 | space="demo_basketballplayer", 44 | graphd_hosts="127.0.0.1:9669", 45 | metad_hosts="127.0.0.1:9559" 46 | ) 47 | 48 | reader = NebulaQueryReader( 49 | query="MATCH p=(v:player{name:'Tim Duncan'})-[e:follow*1..3]->(v2) RETURN p", 50 | nebula_config=config, 51 | limit=10000, 52 | with_rank=True, 53 | ) 54 | 55 | g = reader.read() 56 | ``` 57 | 58 | ## NebulaScanReader 59 | 60 | The `NebulaScanReader` allows you to scan all vertexes and edges in NebulaGraph, and construct a NetworkX graph from the result. 61 | 62 | ```python 63 | from ng_nx import NebulaScanReader 64 | from ng_nx.utils import NebulaGraphConfig 65 | 66 | # Here, we need to be able to resolve the metad and storaged hosts, where they are the same with `SHOW HOSTS META;` and `SHOW HOSTS;` 67 | 68 | config = NebulaGraphConfig( 69 | space="demo_basketballplayer", 70 | graphd_hosts="graphd0:9669", 71 | metad_hosts="metad0:9559" 72 | ) 73 | 74 | reader = NebulaScanReader( 75 | edges=["follow", "serve"], 76 | properties=[["degree"], ["start_year", "end_year"]], 77 | nebula_config=config, limit=10000, with_rank=True) 78 | 79 | g = reader.read() 80 | ``` 81 | 82 | ## NebulaWriter 83 | 84 | Let's write them back to tag: pagerank(pagerank) and louvain(cluster_id). So we create TAGs in NebulaGraph on same space with the following schema: 85 | 86 | ```ngql 87 | CREATE TAG IF NOT EXISTS pagerank ( 88 | pagerank double NOT NULL 89 | ); 90 | CREATE TAG IF NOT EXISTS louvain ( 91 | cluster_id int NOT NULL 92 | ); 93 | ``` 94 | 95 | And we could write the result back to NebulaGraph with the following code: 96 | 97 | ```python 98 | 99 | from ng_nx import NebulaWriter 100 | 101 | pr_writer = NebulaWriter(data=pr, nebula_config=config) 102 | 103 | # properties to write 104 | properties = ["pagerank"] 105 | 106 | pr_writer.set_options( 107 | label="pagerank", 108 | properties=properties, 109 | batch_size=256, 110 | write_mode="insert", 111 | sink="nebulagraph_vertex", 112 | ) 113 | # write back to NebulaGraph 114 | pr_writer.write() 115 | 116 | # write louvain result 117 | louvain_writer = NebulaWriter(data=louvain, nebula_config=config) 118 | # properties to write 119 | properties = ["cluster_id"] 120 | 121 | louvain_writer.set_options( 122 | label="louvain", 123 | properties=properties, 124 | batch_size=256, 125 | write_mode="insert", 126 | sink="nebulagraph_vertex", 127 | ) 128 | louvain_writer.write() 129 | ``` 130 | 131 | Then we could verify the result: 132 | 133 | ```cypher 134 | (root@nebula) [basketballplayer]> 135 | 136 | MATCH (n) 137 | RETURN properties(n).name, n.pagerank.pagerank, n.louvain.cluster_id 138 | LIMIT 5 139 | +--------------------+-----------------------+----------------------+ 140 | | properties(n).name | n.pagerank.pagerank | n.louvain.cluster_id | 141 | +--------------------+-----------------------+----------------------+ 142 | | "Tracy McGrady" | 0.015888952964973516 | 4 | 143 | | "Luka Doncic" | 0.008918675093514758 | 1 | 144 | | "Spurs" | 0.008266820546396887 | 6 | 145 | | "Raptors" | 0.005000457949346969 | 4 | 146 | | "Heat" | 0.0038279814310668457 | 2 | 147 | +--------------------+-----------------------+----------------------+ 148 | Got 5 rows (time spent 47723/58029 us) 149 | 150 | Mon, 27 Mar 2023 13:45:40 CST 151 | ``` -------------------------------------------------------------------------------- /ng_nx/__init__.py: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: Apache-2.0 2 | # Copyright 2024 The NebulaGraph Authors. All rights reserved. 3 | 4 | from pkgutil import extend_path 5 | 6 | __path__ = extend_path(__path__, __name__) # type: ignore 7 | 8 | from ng_nx.query_reader import NebulaReader, NebulaQueryReader 9 | from ng_nx.scan_reader import NebulaScanReader 10 | from ng_nx.writer import NebulaWriter 11 | 12 | # export 13 | __all__ = ( 14 | "NebulaReader", 15 | "NebulaScanReader", 16 | "NebulaWriter", 17 | "NebulaQueryReader", 18 | ) 19 | -------------------------------------------------------------------------------- /ng_nx/query_reader.py: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: Apache-2.0 2 | # Copyright 2024 The NebulaGraph Authors. All rights reserved. 3 | 4 | import networkx as nx 5 | import pandas as pd 6 | from nebula3.Config import Config 7 | from nebula3.gclient.net import ConnectionPool 8 | from nebula3.data.ResultSet import ResultSet 9 | 10 | from ng_nx.utils import NebulaGraphConfig, result_to_df 11 | 12 | 13 | class NebulaReader: 14 | def __init__( 15 | self, 16 | edges: list, 17 | properties: list, 18 | nebula_config: NebulaGraphConfig, 19 | limit: int, 20 | with_rank: bool = False, # this enable the multi-graph, and the edge_key is "__rank__" 21 | ): 22 | self.edges = edges 23 | self.properties = properties 24 | self.limit = limit 25 | 26 | config = Config() 27 | graphd_hosts = nebula_config.graphd_hosts.split(",") 28 | graphd_host_list = [ 29 | (host.split(":")[0], int(host.split(":")[1])) for host in graphd_hosts 30 | ] 31 | self.space = nebula_config.space 32 | self.nebula_user = nebula_config.user 33 | self.nebula_password = nebula_config.password 34 | self.connection_pool = ConnectionPool() 35 | assert self.connection_pool.init( 36 | graphd_host_list, config 37 | ), "Init Connection Pool Failed" 38 | assert len(edges) > 0 and len(edges) == len( 39 | properties 40 | ), "edges and properties should have the same length" 41 | self.with_rank = with_rank 42 | 43 | def read(self): 44 | with self.connection_pool.session_context( 45 | self.nebula_user, self.nebula_password 46 | ) as session: 47 | assert session.execute( 48 | f"USE {self.space}" 49 | ).is_succeeded(), f"Failed to use space {self.space}" 50 | result_list = [] 51 | g = nx.MultiDiGraph() 52 | for i in range(len(self.edges)): 53 | edge = self.edges[i] 54 | properties = self.properties[i] 55 | properties_query_field = "" 56 | for property in properties: 57 | properties_query_field += f", e.{property} AS {property}" 58 | if self.with_rank: 59 | properties_query_field += ", rank(e) AS `__rank__`" 60 | result = session.execute( 61 | f"MATCH ()-[e:`{edge}`]->() RETURN src(e) AS src, dst(e) AS dst{properties_query_field} LIMIT {self.limit}" 62 | ) 63 | # print(f'query: MATCH ()-[e:`{edge}`]->() RETURN src(e) AS src, dst(e) AS dst{properties_query_field} LIMIT {self.limit}') 64 | # print(f"Result: {result}") 65 | assert result.is_succeeded() 66 | result_list.append(result) 67 | 68 | # merge all result 69 | for i, result in enumerate(result_list): 70 | _df = result_to_df(result) 71 | # TBD, consider add label of edge 72 | properties = self.properties[i] if self.properties[i] else None 73 | if self.with_rank: 74 | properties = properties + ["__rank__"] 75 | _g = nx.from_pandas_edgelist( 76 | _df, 77 | "src", 78 | "dst", 79 | properties, 80 | create_using=nx.MultiDiGraph(), 81 | edge_key="__rank__", 82 | ) 83 | else: 84 | _g = nx.from_pandas_edgelist( 85 | _df, 86 | "src", 87 | "dst", 88 | properties, 89 | create_using=nx.MultiDiGraph(), 90 | ) 91 | g = nx.compose(g, _g) 92 | return g 93 | 94 | def release(self): 95 | self.connection_pool.close() 96 | 97 | def __del__(self): 98 | self.release() 99 | 100 | 101 | class NebulaQueryReader: 102 | def __init__(self, nebula_config: NebulaGraphConfig): 103 | self.config = nebula_config 104 | self.connection_pool = ConnectionPool() 105 | graphd_hosts = nebula_config.graphd_hosts.split(",") 106 | graphd_host_list = [ 107 | (host.split(":")[0], int(host.split(":")[1])) for host in graphd_hosts 108 | ] 109 | config = Config() 110 | assert self.connection_pool.init( 111 | graphd_host_list, config 112 | ), "Init Connection Pool Failed" 113 | 114 | def read(self, query: str) -> nx.MultiDiGraph: 115 | with self.connection_pool.session_context( 116 | self.config.user, self.config.password 117 | ) as session: 118 | assert session.execute( 119 | f"USE {self.config.space}" 120 | ).is_succeeded(), f"Failed to use space {self.config.space}" 121 | 122 | result: ResultSet = session.execute(query) 123 | assert ( 124 | result.is_succeeded() 125 | ), f"Query execution failed: {result.error_msg()}" 126 | 127 | vis_data = result.dict_for_vis() 128 | return self._construct_graph(vis_data) 129 | 130 | def _construct_graph(self, vis_data: dict) -> nx.MultiDiGraph: 131 | g = nx.MultiDiGraph() 132 | 133 | # Add nodes 134 | for node_data in vis_data["nodes"]: 135 | g.add_node( 136 | node_data["id"], **node_data["props"], labels=node_data["labels"] 137 | ) 138 | 139 | # Add edges 140 | for edge_data in vis_data["edges"]: 141 | g.add_edge( 142 | edge_data["src"], 143 | edge_data["dst"], 144 | key=edge_data["name"], 145 | **edge_data["props"], 146 | ) 147 | 148 | return g 149 | 150 | def release(self): 151 | self.connection_pool.close() 152 | 153 | def __del__(self): 154 | self.release() 155 | -------------------------------------------------------------------------------- /ng_nx/scan_reader.py: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: Apache-2.0 2 | # Copyright 2023 The NebulaGraph Authors. All rights reserved. 3 | 4 | from typing import Dict, List 5 | 6 | import networkx as nx 7 | from nebula3.mclient import MetaCache, HostAddr 8 | from nebula3.sclient.GraphStorageClient import GraphStorageClient 9 | 10 | from ng_nx.utils import NebulaGraphConfig, cast 11 | 12 | 13 | class NebulaScanReader: 14 | def __init__( 15 | self, 16 | edges: List[str], 17 | properties: List[List[str]], 18 | nebula_config: NebulaGraphConfig, 19 | limit: int, 20 | with_rank: bool = False, # this enable the multi-graph, and the edge_key is "__rank__" 21 | ): 22 | self.edges = edges 23 | self.properties = properties 24 | self.limit = limit 25 | self.space = nebula_config.space 26 | 27 | metad_hosts = nebula_config.metad_hosts.split(",") 28 | metad_host_list = [ 29 | (host.split(":")[0], int(host.split(":")[1])) for host in metad_hosts 30 | ] 31 | self.meta_cache = MetaCache(metad_host_list, 50000) 32 | self.graph_storage_client = GraphStorageClient(self.meta_cache) 33 | 34 | self.with_rank = with_rank 35 | 36 | assert len(edges) > 0 and len(edges) == len( 37 | properties 38 | ), "edges and properties should have the same length" 39 | 40 | def read(self) -> nx.MultiDiGraph: 41 | g = nx.MultiDiGraph() 42 | 43 | for i, edge in enumerate(self.edges): 44 | edge_properties = self.properties[i] 45 | resp = self.graph_storage_client.scan_edge( 46 | space_name=self.space, edge_name=edge 47 | ) 48 | edge_count = 0 49 | while resp.has_next() and edge_count < self.limit: 50 | result = resp.next() 51 | for edge_data in result.as_relationships(): 52 | src = cast(edge_data.start_vertex_id()) 53 | dst = cast(edge_data.end_vertex_id()) 54 | props = {} 55 | for prop in edge_properties: 56 | props[prop] = cast(edge_data.properties().get(prop)) 57 | if self.with_rank: 58 | rank = edge_data.ranking() 59 | props["__rank__"] = rank 60 | g.add_edge(src, dst, key=rank, **props) 61 | else: 62 | g.add_edge(src, dst, **props) 63 | edge_count += 1 64 | if edge_count >= self.limit: 65 | break 66 | 67 | return g 68 | 69 | def release(self): 70 | self.graph_storage_client.close() 71 | 72 | def __del__(self): 73 | self.release() 74 | -------------------------------------------------------------------------------- /ng_nx/utils.py: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: Apache-2.0 2 | # Copyright 2023 The NebulaGraph Authors. All rights reserved. 3 | 4 | from __future__ import annotations 5 | 6 | from typing import Dict 7 | 8 | import pandas as pd 9 | from nebula3.data.DataObject import Value, ValueWrapper 10 | from nebula3.data.ResultSet import ResultSet 11 | 12 | # Default Configuration 13 | GRAPHD_HOSTS = "graphd:9669" 14 | METAD_HOSTS = "metad0:9559,metad1:9559,metad2:9559" 15 | USER = "root" 16 | PASSWORD = "nebula" 17 | SPACE = "basketballplayer" 18 | 19 | # TBD when https://github.com/vesoft-inc/nebula-python/pull/269 is merged 20 | # in a release version of nebula-python, I could leverage the ValueWrapper.cast() 21 | # method to simplify the code below 22 | cast_as = { 23 | Value.NVAL: "as_null", 24 | Value.BVAL: "as_bool", 25 | Value.IVAL: "as_int", 26 | Value.FVAL: "as_double", 27 | Value.SVAL: "as_string", 28 | Value.LVAL: "as_list", 29 | Value.UVAL: "as_set", 30 | Value.MVAL: "as_map", 31 | Value.TVAL: "as_time", 32 | Value.DVAL: "as_date", 33 | Value.DTVAL: "as_datetime", 34 | Value.VVAL: "as_node", 35 | Value.EVAL: "as_relationship", 36 | Value.PVAL: "as_path", 37 | Value.GGVAL: "as_geography", 38 | Value.DUVAL: "as_duration", 39 | } 40 | 41 | 42 | def cast(val: ValueWrapper): 43 | _type = val._value.getType() 44 | if _type == Value.__EMPTY__: 45 | return None 46 | if _type in cast_as: 47 | return getattr(val, cast_as[_type])() 48 | if _type == Value.LVAL: 49 | return [x.cast() for x in val.as_list()] 50 | if _type == Value.UVAL: 51 | return {x.cast() for x in val.as_set()} 52 | if _type == Value.MVAL: 53 | return {k: v.cast() for k, v in val.as_map().items()} 54 | 55 | 56 | def result_to_df(result: ResultSet) -> pd.DataFrame: 57 | """ 58 | build list for each column, and transform to dataframe 59 | """ 60 | assert result.is_succeeded() 61 | columns = result.keys() 62 | d: Dict[str, list] = {} 63 | for col_num in range(result.col_size()): 64 | col_name = columns[col_num] 65 | col_list = result.column_values(col_name) 66 | d[col_name] = [cast(x) for x in col_list] 67 | return pd.DataFrame(d) 68 | 69 | 70 | class NebulaGraphConfig: 71 | def __init__( 72 | self, 73 | graphd_hosts: str = GRAPHD_HOSTS, 74 | metad_hosts: str = METAD_HOSTS, 75 | user: str = USER, 76 | password: str = PASSWORD, 77 | space: str = SPACE, 78 | **kwargs, 79 | ): 80 | self.graphd_hosts = graphd_hosts 81 | self.metad_hosts = metad_hosts 82 | self.user = user 83 | self.password = password 84 | self.space = space 85 | self.shuffle_partitions = None 86 | self.executor_memory = None 87 | self.driver_memory = None 88 | for key, value in kwargs.items(): 89 | setattr(self, key, value) 90 | 91 | def __getattr__(self, name): 92 | return None 93 | -------------------------------------------------------------------------------- /ng_nx/writer.py: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: Apache-2.0 2 | # Copyright 2023 The NebulaGraph Authors. All rights reserved. 3 | 4 | from typing import Generator, List, Dict, Literal 5 | 6 | from nebula3.Config import Config 7 | from nebula3.gclient.net import ConnectionPool 8 | 9 | from ng_nx.utils import NebulaGraphConfig, result_to_df 10 | 11 | 12 | class NebulaWriter: 13 | def __init__(self, data: Dict, nebula_config: NebulaGraphConfig): 14 | self.data = data 15 | self.label = None 16 | self.properties = [] 17 | self.batch_size = None 18 | self.write_mode = None 19 | self.sink = None 20 | 21 | config = Config() 22 | graphd_hosts = nebula_config.graphd_hosts.split(",") 23 | graphd_host_list = [ 24 | (host.split(":")[0], int(host.split(":")[1])) for host in graphd_hosts 25 | ] 26 | self.space = nebula_config.space 27 | self.nebula_user = nebula_config.user 28 | self.nebula_password = nebula_config.password 29 | self.connection_pool = ConnectionPool() 30 | assert self.connection_pool.init( 31 | graphd_host_list, config 32 | ), "Init Connection Pool Failed" 33 | 34 | def set_options( 35 | self, 36 | label: str, 37 | properties: List[str], 38 | batch_size: int = 256, 39 | write_mode: str = "insert", 40 | sink: Literal[ 41 | "nebulagraph_vertex", "nebulagraph_edge" 42 | ] = "nebulagraph_vertex", 43 | ): 44 | self.label = label 45 | self.properties = properties 46 | self.batch_size = batch_size 47 | self.write_mode = write_mode.lower() 48 | self.sink = sink.lower() 49 | 50 | def write(self): 51 | if self.write_mode == "update": 52 | raise NotImplementedError("Update mode is not implemented yet") 53 | if self.write_mode != "insert": 54 | raise ValueError("Only insert mode is supported now") 55 | if self.sink == "nebulagraph_vertex": 56 | return self._write_vertex() 57 | elif self.sink == "nebulagraph_edge": 58 | return self._write_edge() 59 | else: 60 | raise ValueError("Invalid sink type") 61 | 62 | def _write_vertex(self): 63 | if self.sink == "nebulagraph_edge": 64 | raise NotImplementedError("Edge sink is not implemented yet") 65 | if self.write_mode != "insert" or self.sink != "nebulagraph_vertex": 66 | raise ValueError("Only insert mode and vertex sink are supported now") 67 | # TODO: add more write modes and sinks later 68 | with self.connection_pool.session_context( 69 | self.nebula_user, self.nebula_password 70 | ) as session: 71 | assert session.execute( 72 | f"USE {self.space}" 73 | ).is_succeeded(), f"Failed to use space {self.space}" 74 | # get types of properties 75 | properties_types = {} 76 | query = f"DESC TAG {self.label}" 77 | result = session.execute(query) 78 | assert result.is_succeeded(), ( 79 | f"Failed to get types of properties: {result.error_msg()}, " 80 | f"consider creating TAG {self.label} first." 81 | ) 82 | types_df = result_to_df(result) 83 | 84 | for i in range(len(types_df)): 85 | properties_types[types_df.iloc[i, 0]] = types_df.iloc[i, 1] 86 | for property in self.properties: 87 | if property not in properties_types: 88 | raise ValueError( 89 | f"Property {property} is not defined in TAG {self.label}" 90 | ) 91 | 92 | # Set up the write query in batches, string value should be enclosed by double quotes 93 | # INSERT VERTEX {label} ({properties}) VALUES 94 | # "{vid}":({value0, value1}),...; 95 | query_prefix = ( 96 | f"INSERT VERTEX {self.label} ({','.join(self.properties)}) VALUES " 97 | ) 98 | query = query_prefix 99 | # now self.data is a dict or a generator object, key is vid, value is a list of properties or single property 100 | quote = '"' 101 | if isinstance(self.data, dict): 102 | for i, (vid, properties) in enumerate(self.data.items()): 103 | if i % self.batch_size == 0 and i != 0: 104 | # execute the query 105 | # remove tailing comma 106 | query = query[:-1] 107 | result = session.execute(query) 108 | assert ( 109 | result.is_succeeded() 110 | ), f"Failed to write data: {result.error_msg()}" 111 | # reset the query 112 | query = query_prefix 113 | if isinstance(properties, list): 114 | # should add quotes to string values 115 | query += f"{quote}{vid}{quote}:({','.join([quote+str(value)+quote if properties_types[self.properties[i]] == 'string' else str(value) for i, value in enumerate(properties)])})," 116 | else: 117 | query += f"{quote}{vid}{quote}:({quote+str(properties)+quote if properties_types[self.properties[0]] == 'string' else str(properties)})," 118 | # execute the last query 119 | query = query[:-1] 120 | result = session.execute(query) 121 | assert ( 122 | result.is_succeeded() 123 | ), f"Failed to write data: {result.error_msg()}" 124 | elif isinstance(self.data, Generator): 125 | for i, (vid, properties) in enumerate(self.data): 126 | if i % self.batch_size == 0 and i != 0: 127 | # execute the query 128 | # remove tailing comma 129 | query = query[:-1] 130 | result = session.execute(query) 131 | assert ( 132 | result.is_succeeded() 133 | ), f"Failed to write data: {result.error_msg()}" 134 | # reset the query 135 | query = query_prefix 136 | if isinstance(properties, list): 137 | # should add quotes to string values 138 | query += f"{quote}{vid}{quote}:({','.join([quote+str(value)+quote if properties_types[self.properties[i]] == 'string' else str(value) for i, value in enumerate(properties)])})," 139 | else: 140 | query += f"{quote}{vid}{quote}:({quote+str(properties)+quote if properties_types[self.properties[0]] == 'string' else str(properties)})," 141 | # execute the last query 142 | query = query[:-1] 143 | result = session.execute(query) 144 | assert ( 145 | result.is_succeeded() 146 | ), f"Failed to write data: {result.error_msg()}" 147 | else: 148 | raise TypeError("Data should be a dict or a generator object") 149 | return True 150 | 151 | def _write_edge(self): 152 | with self.connection_pool.session_context( 153 | self.nebula_user, self.nebula_password 154 | ) as session: 155 | assert session.execute( 156 | f"USE {self.space}" 157 | ).is_succeeded(), f"Failed to use space {self.space}" 158 | 159 | # Get types of edge properties 160 | properties_types = {} 161 | query = f"DESC EDGE {self.label}" 162 | result = session.execute(query) 163 | assert result.is_succeeded(), ( 164 | f"Failed to get types of properties: {result.error_msg()}, " 165 | f"consider creating EDGE {self.label} first." 166 | ) 167 | types_df = result_to_df(result) 168 | 169 | for i in range(len(types_df)): 170 | properties_types[types_df.iloc[i, 0]] = types_df.iloc[i, 1] 171 | for property in self.properties: 172 | if property not in properties_types: 173 | raise ValueError( 174 | f"Property {property} is not defined in EDGE {self.label}" 175 | ) 176 | 177 | # Set up the write query in batches 178 | query_prefix = ( 179 | f"INSERT EDGE {self.label} ({','.join(self.properties)}) VALUES " 180 | ) 181 | query = query_prefix 182 | quote = '"' 183 | 184 | def process_edge(src, dst, rank, props): 185 | nonlocal query 186 | prop_values = ",".join( 187 | [ 188 | f"{quote}{str(value)}{quote}" 189 | if properties_types[self.properties[i]] == "string" 190 | else str(value) 191 | for i, value in enumerate(props) 192 | ] 193 | ) 194 | query += f"{quote}{src}{quote}->{quote}{dst}{quote}@{rank}:({prop_values})," 195 | 196 | batch_count = 0 197 | for edge in self.data: 198 | if batch_count == self.batch_size: 199 | # Execute the query 200 | query = query[:-1] # Remove trailing comma 201 | result = session.execute(query) 202 | assert ( 203 | result.is_succeeded() 204 | ), f"Failed to write data: {result.error_msg()}" 205 | query = query_prefix 206 | batch_count = 0 207 | 208 | src, dst, rank, props = edge 209 | process_edge(src, dst, rank, props) 210 | batch_count += 1 211 | 212 | # Execute the last batch 213 | if batch_count > 0: 214 | query = query[:-1] # Remove trailing comma 215 | result = session.execute(query) 216 | assert ( 217 | result.is_succeeded() 218 | ), f"Failed to write data: {result.error_msg()}" 219 | 220 | return True 221 | -------------------------------------------------------------------------------- /pdm.lock: -------------------------------------------------------------------------------- 1 | # This file is @generated by PDM. 2 | # It is not intended for manual editing. 3 | 4 | [metadata] 5 | groups = ["default"] 6 | strategy = ["inherit_metadata"] 7 | lock_version = "4.5.0" 8 | content_hash = "sha256:2fa24b9e0c28fac6791baafb10c23dc8b145a210bfc8f6876f27e9b87cd4feea" 9 | 10 | [[metadata.targets]] 11 | requires_python = ">=3.7.1" 12 | 13 | [[package]] 14 | name = "anyio" 15 | version = "3.7.1" 16 | requires_python = ">=3.7" 17 | summary = "High level compatibility layer for multiple asynchronous event loop implementations" 18 | groups = ["default"] 19 | dependencies = [ 20 | "exceptiongroup; python_version < \"3.11\"", 21 | "idna>=2.8", 22 | "sniffio>=1.1", 23 | "typing-extensions; python_version < \"3.8\"", 24 | ] 25 | files = [ 26 | {file = "anyio-3.7.1-py3-none-any.whl", hash = "sha256:91dee416e570e92c64041bd18b900d1d6fa78dff7048769ce5ac5ddad004fbb5"}, 27 | {file = "anyio-3.7.1.tar.gz", hash = "sha256:44a3c9aba0f5defa43261a8b3efb97891f2bd7d804e0e1f56419befa1adfc780"}, 28 | ] 29 | 30 | [[package]] 31 | name = "certifi" 32 | version = "2024.7.4" 33 | requires_python = ">=3.6" 34 | summary = "Python package for providing Mozilla's CA Bundle." 35 | groups = ["default"] 36 | files = [ 37 | {file = "certifi-2024.7.4-py3-none-any.whl", hash = "sha256:c198e21b1289c2ab85ee4e67bb4b4ef3ead0892059901a8d5b622f24a1101e90"}, 38 | {file = "certifi-2024.7.4.tar.gz", hash = "sha256:5a1e7645bc0ec61a09e26c36f6106dd4cf40c6db3a1fb6352b0244e7fb057c7b"}, 39 | ] 40 | 41 | [[package]] 42 | name = "exceptiongroup" 43 | version = "1.2.2" 44 | requires_python = ">=3.7" 45 | summary = "Backport of PEP 654 (exception groups)" 46 | groups = ["default"] 47 | marker = "python_version < \"3.11\"" 48 | files = [ 49 | {file = "exceptiongroup-1.2.2-py3-none-any.whl", hash = "sha256:3111b9d131c238bec2f8f516e123e14ba243563fb135d3fe885990585aa7795b"}, 50 | {file = "exceptiongroup-1.2.2.tar.gz", hash = "sha256:47c2edf7c6738fafb49fd34290706d1a1a2f4d1c6df275526b62cbb4aa5393cc"}, 51 | ] 52 | 53 | [[package]] 54 | name = "future" 55 | version = "1.0.0" 56 | requires_python = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*" 57 | summary = "Clean single-source support for Python 3 and 2" 58 | groups = ["default"] 59 | files = [ 60 | {file = "future-1.0.0-py3-none-any.whl", hash = "sha256:929292d34f5872e70396626ef385ec22355a1fae8ad29e1a734c3e43f9fbc216"}, 61 | {file = "future-1.0.0.tar.gz", hash = "sha256:bd2968309307861edae1458a4f8a4f3598c03be43b97521076aebf5d94c07b05"}, 62 | ] 63 | 64 | [[package]] 65 | name = "h11" 66 | version = "0.14.0" 67 | requires_python = ">=3.7" 68 | summary = "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1" 69 | groups = ["default"] 70 | dependencies = [ 71 | "typing-extensions; python_version < \"3.8\"", 72 | ] 73 | files = [ 74 | {file = "h11-0.14.0-py3-none-any.whl", hash = "sha256:e3fe4ac4b851c468cc8363d500db52c2ead036020723024a109d37346efaa761"}, 75 | {file = "h11-0.14.0.tar.gz", hash = "sha256:8f19fbbe99e72420ff35c00b27a34cb9937e902a8b810e2c88300c6f0a3b699d"}, 76 | ] 77 | 78 | [[package]] 79 | name = "h2" 80 | version = "4.1.0" 81 | requires_python = ">=3.6.1" 82 | summary = "HTTP/2 State-Machine based protocol implementation" 83 | groups = ["default"] 84 | dependencies = [ 85 | "hpack<5,>=4.0", 86 | "hyperframe<7,>=6.0", 87 | ] 88 | files = [ 89 | {file = "h2-4.1.0-py3-none-any.whl", hash = "sha256:03a46bcf682256c95b5fd9e9a99c1323584c3eec6440d379b9903d709476bc6d"}, 90 | {file = "h2-4.1.0.tar.gz", hash = "sha256:a83aca08fbe7aacb79fec788c9c0bac936343560ed9ec18b82a13a12c28d2abb"}, 91 | ] 92 | 93 | [[package]] 94 | name = "hpack" 95 | version = "4.0.0" 96 | requires_python = ">=3.6.1" 97 | summary = "Pure-Python HPACK header compression" 98 | groups = ["default"] 99 | files = [ 100 | {file = "hpack-4.0.0-py3-none-any.whl", hash = "sha256:84a076fad3dc9a9f8063ccb8041ef100867b1878b25ef0ee63847a5d53818a6c"}, 101 | {file = "hpack-4.0.0.tar.gz", hash = "sha256:fc41de0c63e687ebffde81187a948221294896f6bdc0ae2312708df339430095"}, 102 | ] 103 | 104 | [[package]] 105 | name = "httpcore" 106 | version = "0.17.3" 107 | requires_python = ">=3.7" 108 | summary = "A minimal low-level HTTP client." 109 | groups = ["default"] 110 | dependencies = [ 111 | "anyio<5.0,>=3.0", 112 | "certifi", 113 | "h11<0.15,>=0.13", 114 | "sniffio==1.*", 115 | ] 116 | files = [ 117 | {file = "httpcore-0.17.3-py3-none-any.whl", hash = "sha256:c2789b767ddddfa2a5782e3199b2b7f6894540b17b16ec26b2c4d8e103510b87"}, 118 | {file = "httpcore-0.17.3.tar.gz", hash = "sha256:a6f30213335e34c1ade7be6ec7c47f19f50c56db36abef1a9dfa3815b1cb3888"}, 119 | ] 120 | 121 | [[package]] 122 | name = "httplib2" 123 | version = "0.22.0" 124 | requires_python = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" 125 | summary = "A comprehensive HTTP client library." 126 | groups = ["default"] 127 | dependencies = [ 128 | "pyparsing!=3.0.0,!=3.0.1,!=3.0.2,!=3.0.3,<4,>=2.4.2; python_version > \"3.0\"", 129 | "pyparsing<3,>=2.4.2; python_version < \"3.0\"", 130 | ] 131 | files = [ 132 | {file = "httplib2-0.22.0-py3-none-any.whl", hash = "sha256:14ae0a53c1ba8f3d37e9e27cf37eabb0fb9980f435ba405d546948b009dd64dc"}, 133 | {file = "httplib2-0.22.0.tar.gz", hash = "sha256:d7a10bc5ef5ab08322488bde8c726eeee5c8618723fdb399597ec58f3d82df81"}, 134 | ] 135 | 136 | [[package]] 137 | name = "httpx" 138 | version = "0.24.1" 139 | requires_python = ">=3.7" 140 | summary = "The next generation HTTP client." 141 | groups = ["default"] 142 | dependencies = [ 143 | "certifi", 144 | "httpcore<0.18.0,>=0.15.0", 145 | "idna", 146 | "sniffio", 147 | ] 148 | files = [ 149 | {file = "httpx-0.24.1-py3-none-any.whl", hash = "sha256:06781eb9ac53cde990577af654bd990a4949de37a28bdb4a230d434f3a30b9bd"}, 150 | {file = "httpx-0.24.1.tar.gz", hash = "sha256:5853a43053df830c20f8110c5e69fe44d035d850b2dfe795e196f00fdb774bdd"}, 151 | ] 152 | 153 | [[package]] 154 | name = "httpx" 155 | version = "0.24.1" 156 | extras = ["http2"] 157 | requires_python = ">=3.7" 158 | summary = "The next generation HTTP client." 159 | groups = ["default"] 160 | dependencies = [ 161 | "h2<5,>=3", 162 | "httpx==0.24.1", 163 | ] 164 | files = [ 165 | {file = "httpx-0.24.1-py3-none-any.whl", hash = "sha256:06781eb9ac53cde990577af654bd990a4949de37a28bdb4a230d434f3a30b9bd"}, 166 | {file = "httpx-0.24.1.tar.gz", hash = "sha256:5853a43053df830c20f8110c5e69fe44d035d850b2dfe795e196f00fdb774bdd"}, 167 | ] 168 | 169 | [[package]] 170 | name = "hyperframe" 171 | version = "6.0.1" 172 | requires_python = ">=3.6.1" 173 | summary = "HTTP/2 framing layer for Python" 174 | groups = ["default"] 175 | files = [ 176 | {file = "hyperframe-6.0.1-py3-none-any.whl", hash = "sha256:0ec6bafd80d8ad2195c4f03aacba3a8265e57bc4cff261e802bf39970ed02a15"}, 177 | {file = "hyperframe-6.0.1.tar.gz", hash = "sha256:ae510046231dc8e9ecb1a6586f63d2347bf4c8905914aa84ba585ae85f28a914"}, 178 | ] 179 | 180 | [[package]] 181 | name = "idna" 182 | version = "3.7" 183 | requires_python = ">=3.5" 184 | summary = "Internationalized Domain Names in Applications (IDNA)" 185 | groups = ["default"] 186 | files = [ 187 | {file = "idna-3.7-py3-none-any.whl", hash = "sha256:82fee1fc78add43492d3a1898bfa6d8a904cc97d8427f683ed8e798d07761aa0"}, 188 | {file = "idna-3.7.tar.gz", hash = "sha256:028ff3aadf0609c1fd278d8ea3089299412a7a8b9bd005dd08b9f8285bcb5cfc"}, 189 | ] 190 | 191 | [[package]] 192 | name = "nebula3-python" 193 | version = "3.8.2" 194 | requires_python = ">=3.6.2" 195 | summary = "Python client for NebulaGraph v3" 196 | groups = ["default"] 197 | dependencies = [ 198 | "future>=0.18.0", 199 | "httplib2>=0.20.0", 200 | "httpx[http2]>=0.22.0", 201 | "pytz>=2021.1", 202 | "six>=1.16.0", 203 | ] 204 | files = [ 205 | {file = "nebula3_python-3.8.2-py3-none-any.whl", hash = "sha256:8942ef87619f05115f643896408f8cbe602670405a3aeab01fdcc454eeabf0d7"}, 206 | {file = "nebula3_python-3.8.2.tar.gz", hash = "sha256:889df21bac0f7ccad1d3a1807d9b736b2136770b24ed03d4fd49b76b3e2612ea"}, 207 | ] 208 | 209 | [[package]] 210 | name = "networkx" 211 | version = "2.6.3" 212 | requires_python = ">=3.7" 213 | summary = "Python package for creating and manipulating graphs and networks" 214 | groups = ["default"] 215 | files = [ 216 | {file = "networkx-2.6.3-py3-none-any.whl", hash = "sha256:80b6b89c77d1dfb64a4c7854981b60aeea6360ac02c6d4e4913319e0a313abef"}, 217 | {file = "networkx-2.6.3.tar.gz", hash = "sha256:c0946ed31d71f1b732b5aaa6da5a0388a345019af232ce2f49c766e2d6795c51"}, 218 | ] 219 | 220 | [[package]] 221 | name = "pyparsing" 222 | version = "3.1.2" 223 | requires_python = ">=3.6.8" 224 | summary = "pyparsing module - Classes and methods to define and execute parsing grammars" 225 | groups = ["default"] 226 | marker = "python_version > \"3.0\"" 227 | files = [ 228 | {file = "pyparsing-3.1.2-py3-none-any.whl", hash = "sha256:f9db75911801ed778fe61bb643079ff86601aca99fcae6345aa67292038fb742"}, 229 | {file = "pyparsing-3.1.2.tar.gz", hash = "sha256:a1bac0ce561155ecc3ed78ca94d3c9378656ad4c94c1270de543f621420f94ad"}, 230 | ] 231 | 232 | [[package]] 233 | name = "pytz" 234 | version = "2024.1" 235 | summary = "World timezone definitions, modern and historical" 236 | groups = ["default"] 237 | files = [ 238 | {file = "pytz-2024.1-py2.py3-none-any.whl", hash = "sha256:328171f4e3623139da4983451950b28e95ac706e13f3f2630a879749e7a8b319"}, 239 | {file = "pytz-2024.1.tar.gz", hash = "sha256:2a29735ea9c18baf14b448846bde5a48030ed267578472d8955cd0e7443a9812"}, 240 | ] 241 | 242 | [[package]] 243 | name = "six" 244 | version = "1.16.0" 245 | requires_python = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*" 246 | summary = "Python 2 and 3 compatibility utilities" 247 | groups = ["default"] 248 | files = [ 249 | {file = "six-1.16.0-py2.py3-none-any.whl", hash = "sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254"}, 250 | {file = "six-1.16.0.tar.gz", hash = "sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926"}, 251 | ] 252 | 253 | [[package]] 254 | name = "sniffio" 255 | version = "1.3.1" 256 | requires_python = ">=3.7" 257 | summary = "Sniff out which async library your code is running under" 258 | groups = ["default"] 259 | files = [ 260 | {file = "sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2"}, 261 | {file = "sniffio-1.3.1.tar.gz", hash = "sha256:f4324edc670a0f49750a81b895f35c3adb843cca46f0530f79fc1babb23789dc"}, 262 | ] 263 | 264 | [[package]] 265 | name = "typing-extensions" 266 | version = "4.7.1" 267 | requires_python = ">=3.7" 268 | summary = "Backported and Experimental Type Hints for Python 3.7+" 269 | groups = ["default"] 270 | marker = "python_version < \"3.8\"" 271 | files = [ 272 | {file = "typing_extensions-4.7.1-py3-none-any.whl", hash = "sha256:440d5dd3af93b060174bf433bccd69b0babc3b15b1a8dca43789fd7f61514b36"}, 273 | {file = "typing_extensions-4.7.1.tar.gz", hash = "sha256:b75ddc264f0ba5615db7ba217daeb99701ad295353c45f9e95963337ceeeffb2"}, 274 | ] 275 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.pdm] 2 | 3 | 4 | [tool.pdm.scripts.test] 5 | shell = """ 6 | pdm update -dG dev 7 | pytest tests/unit/ 8 | """ 9 | 10 | [tool.pdm.scripts.lint] 11 | shell = """ 12 | pdm update -dG lint 13 | flake8 --max-line-length=84 ng_nx tests 14 | isort --check ng_nx tests --diff 15 | black --line-length 84 --check ng_nx tests --diff 16 | """ 17 | 18 | [tool.pdm.scripts.format] 19 | shell = """ 20 | pdm update -dG lint 21 | isort ng_nx tests 22 | black --line-length 84 ng_nx tests 23 | """ 24 | 25 | [tool.pdm.scripts.dockerup] 26 | shell = """ 27 | docker-compose -f 'tests/integration/setup/docker-compose.yaml' up -d --remove-orphans 28 | echo "Waiting for NebulaGraph to start..." 29 | sleep 5 30 | for i in {1..50}; do docker-compose -f 'tests/integration/setup/docker-compose.yaml' ps | grep "unhealthy\\|starting" | wc -l | grep -q 0 && break; echo Waiting for another 5 sec; sleep 5; done 31 | echo "NebulaGraph is up and running, removing console container" 32 | docker-compose -f 'tests/integration/setup/docker-compose.yaml' stop console 33 | docker-compose -f 'tests/integration/setup/docker-compose.yaml' rm -f console 34 | docker-compose -f 'tests/integration/setup/docker-compose.yaml' ps 35 | """ 36 | 37 | [tool.pdm.scripts.dockerstatus] 38 | shell = """ 39 | docker-compose -f 'tests/integration/setup/docker-compose.yaml' ps 40 | """ 41 | 42 | [tool.pdm.scripts.dockerdown] 43 | shell = """ 44 | docker-compose -f 'tests/integration/setup/docker-compose.yaml' down 45 | """ 46 | 47 | [tool.pdm.scripts.int-test] 48 | shell = """ 49 | pdm update -dG dev 50 | pdm run dockerup 51 | 52 | echo "Run integration tests" 53 | 54 | pytest tests/integration/ 55 | """ 56 | 57 | [tool.black] 58 | line-length = 84 59 | exclude = ''' 60 | /( 61 | \.eggs 62 | | \.git 63 | | \.hg 64 | | \.mypy_cache 65 | | \.tox 66 | | \.venv 67 | | _build 68 | | buck-out 69 | | build 70 | | dist 71 | )/ 72 | ''' 73 | 74 | [tool.isort] 75 | profile = "black" 76 | atomic = true 77 | skip_glob = ["*/setup.py"] 78 | filter_files = true 79 | 80 | [project] 81 | name = "ng_nx" 82 | version = "0.2.3" 83 | description = "NebulaGraph NetowrkX Adaptor" 84 | authors = [ 85 | {name = "Wey Gu", email = "weyl.gu@gmail.com"}, 86 | ] 87 | # only numpy==1.21.6, scipy==1.7.3 could work on m1 mac, yet work on py37 88 | # ng_ai need to work with pyspark 2.4.x, which only support py37 89 | dependencies = [ 90 | "networkx>=2.5.1", 91 | "nebula3-python>=3.8.2", 92 | ] 93 | requires-python = ">=3.7.1" 94 | readme = "README.md" 95 | license = {text = "Apache-2.0"} 96 | classifiers = [ 97 | "Topic :: Software Development :: Build Tools", 98 | "Programming Language :: Python :: 3", 99 | "Programming Language :: Python :: 3.7", 100 | "Programming Language :: Python :: 3.8", 101 | "Programming Language :: Python :: 3.9", 102 | "Programming Language :: Python :: 3.10", 103 | "License :: OSI Approved :: Apache Software License", 104 | "Operating System :: OS Independent", 105 | ] 106 | [project.urls] 107 | Homepage = "https://github.com/wey-gu/nebulagraph-nx" 108 | Repository = "https://github.com/wey-gu/nebulagraph-nx" 109 | Documentation = "https://github.com/wey-gu/nebulagraph-nx#documentation" 110 | Changelog = "https://github.com/wey-gu/nebulagraph-nx/releases" 111 | 112 | [build-system] 113 | requires = ["pdm-pep517>=1.0"] 114 | build-backend = "pdm.pep517.api" 115 | 116 | [project.optional-dependencies] 117 | 118 | lint = [ 119 | "flake8>=4.0.1", 120 | "black[jupyter]>=23.1.0", 121 | "isort>=5.11.5", 122 | ] 123 | test = [ 124 | "pytest>=7.2.2", 125 | "pytest-mock>=3.10.0", 126 | ] 127 | dev = [ 128 | "ng_nx[lint,test]", 129 | ] 130 | -------------------------------------------------------------------------------- /tests/integration/setup/docker-compose.yaml: -------------------------------------------------------------------------------- 1 | services: 2 | metad0: 3 | labels: 4 | - "com.vesoft.scope=core" 5 | - "com.vesoft.role=meta" 6 | container_name: nebulagraph_metad0 7 | image: vesoft/nebula-metad:v3.4.0 8 | environment: 9 | USER: root 10 | command: 11 | - --meta_server_addrs=metad0:9559 12 | - --local_ip=metad0 13 | - --ws_ip=metad0 14 | - --port=9559 15 | - --ws_http_port=19559 16 | - --data_path=/data/meta 17 | - --log_dir=/logs 18 | - --v=0 19 | - --minloglevel=0 20 | healthcheck: 21 | test: ["CMD", "curl", "-sf", "http://metad0:19559/status"] 22 | interval: 30s 23 | timeout: 10s 24 | retries: 3 25 | start_period: 20s 26 | ports: 27 | - 9559 28 | - 19559 29 | - 19560 30 | volumes: 31 | - ./data/meta0:/data/meta 32 | - ./logs/meta0:/logs 33 | networks: 34 | - nebula-net 35 | restart: on-failure 36 | 37 | storaged0: 38 | labels: 39 | - "com.vesoft.scope=core" 40 | - "com.vesoft.role=storage" 41 | container_name: nebulagraph_storaged0 42 | image: vesoft/nebula-storaged:v3.4.0 43 | environment: 44 | USER: root 45 | command: 46 | - --meta_server_addrs=metad0:9559 47 | - --local_ip=storaged0 48 | - --ws_ip=storaged0 49 | - --port=9779 50 | - --ws_http_port=19779 51 | - --data_path=/data/storage 52 | - --log_dir=/logs 53 | - --v=0 54 | - --minloglevel=0 55 | depends_on: 56 | - metad0 57 | healthcheck: 58 | test: ["CMD", "curl", "-sf", "http://storaged0:19779/status"] 59 | interval: 30s 60 | timeout: 10s 61 | retries: 3 62 | start_period: 20s 63 | ports: 64 | - 9779 65 | - 19779 66 | - 19780 67 | volumes: 68 | - ./data/storage0:/data/storage 69 | - ./logs/storage0:/logs 70 | networks: 71 | - nebula-net 72 | restart: on-failure 73 | 74 | graphd: 75 | labels: 76 | - "com.vesoft.scope=core" 77 | - "com.vesoft.role=graph" 78 | container_name: nebulagraph_graphd 79 | image: vesoft/nebula-graphd:v3.4.0 80 | environment: 81 | USER: root 82 | command: 83 | - --meta_server_addrs=metad0:9559 84 | - --port=9669 85 | - --local_ip=graphd 86 | - --ws_ip=graphd 87 | - --ws_http_port=19669 88 | - --log_dir=/logs 89 | - --v=0 90 | - --minloglevel=0 91 | depends_on: 92 | - storaged0 93 | healthcheck: 94 | test: ["CMD", "curl", "-sf", "http://graphd:19669/status"] 95 | interval: 30s 96 | timeout: 10s 97 | retries: 3 98 | start_period: 20s 99 | ports: 100 | - "39669:9669" 101 | - 19669 102 | - 19670 103 | volumes: 104 | - ./logs/graph:/logs 105 | networks: 106 | - nebula-net 107 | restart: on-failure 108 | 109 | console: 110 | image: vesoft/nebula-console:v3 111 | container_name: nebula_console 112 | entrypoint: "" 113 | command: 114 | - sh 115 | - -c 116 | - | 117 | for i in `seq 1 180`;do 118 | var=`nebula-console -addr graphd -port 9669 -u root -p nebula -e 'ADD HOSTS "storaged0":9779'`; 119 | if [[ $$? == 0 ]];then 120 | break; 121 | fi; 122 | sleep 1; 123 | echo "retry to add hosts."; 124 | done && tail -f /dev/null; 125 | depends_on: 126 | - graphd 127 | networks: 128 | - nebula-net 129 | 130 | networks: 131 | nebula-net: 132 | -------------------------------------------------------------------------------- /tests/unit/test_query_reader.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wey-gu/NebulaGraph-NX/2e270c918a43a1734aac9b52630dfd4a469394ef/tests/unit/test_query_reader.py --------------------------------------------------------------------------------