在Python中投影的neo4j图可以转换为pandas dataframe/tensor/numpy/etc以便与pytorch/etc一起使用吗?

问题描述 投票:0回答:1

我正在尝试在 Neo4j 的 Aura DS 数据库上运行算法。

我似乎已经大致了解如何连接到 Aura DS 数据库,投影特定图形,然后应用图形数据科学 (GDS) 库中的一种算法来进行节点分类或解决其他一些机器学习问题问题。

但是,我可以以某种方式连接到 Aura DS 数据库并以 pandas dataframe/tensor/numpy array/etc 等格式检索数据吗?并使用GDS之外的其他库来训练?

python neo4j
1个回答
0
投票

Aura DS 和 Aura DB 支持来自 python 驱动程序的 Cypher。 您可以获取节点的属性并从中生成数据帧。

这里的小挑战是 Pandas DF 在架构方面不像 Neo4j Graph 那样宽容。
因此,从已知节点获取属性列表,然后根据结果生成 RETURN Cypher 查询是一种更好的方法。
或者,您可以将特定参数和别名硬编码在 'nodesQuery' Cypher 语句。但如果您有太多的列/属性需要获取,这可能会变得乏味。

from neo4j import GraphDatabase # pip install neo4j
import pandas as pd #pip install pandas

AuraDBId = 'ENTER DB ID HERE'
dbUsername = 'ENTER USERNAME HERE' #Default neo4j for Aura
password = 'ENTER YOUR PASSWORD HERE'
boltUrl = f"neo4j+ssc://{AuraDBId}.databases.neo4j.io:7687"     
graphDBDriver = GraphDatabase.driver(boltUrl,auth=(dbUsername, password))
graphDBDriver.verify_connectivity()

#Fetching properties and generating the List of columns
nodeV = 'n'
yourLabel = 'Movie' #Replace this with your actual label

columnsQuery=f"MATCH({nodeV}:{yourLabel}) RETURN keys(n) LIMIT 1" # Add a WHERE clause to filter this node if required. The properties of this node are going to be used as a reference for the columns
with graphDBDriver.session() as session:
    propertiesRes = session.run(columnsQuery)
    propertiesList = propertiesRes.data() # Returs a List with 1 dictionary
cols = propertiesList[0].get(f'keys({nodeV})')
returnString = ', '.join([f'{nodeV}.{col} as {col}' for col in cols]) #Generating a return statement with aliases 

nodesQuery = f"MATCH({nodeV}:{yourLabel}) RETURN {returnString}"
with graphDBDriver.session() as session:
    nodesRes = session.run(nodesQuery)
    nodeResList = nodesRes.data()

graphDF = pd.DataFrame(nodeResList) 

graphDBDriver.close()

确保您更改 AuraDBId、dbUsername、密码和 yourLabel(如果适用)。 一旦你有了 Python 中的数据框,一切就应该如常了。

注意事项:

  1. 这种在代码中硬编码数据库凭据的方法既简单又简短,但不推荐。始终单独存储您的凭据并将其加载到使用它们的实际代码中。在 .env 文件中并使用 loadenv() 或存储为 json 文件并使用 json.load 读取内容。
  2. Neo4j 从应用程序驱动程序与图进行交互的推荐方法是使用托管事务会话中的参数化查询。我跳过了这些,因为用例看起来很简单而且很少见。但如果您的工作量较重,请始终使用事务和参数化方法。
© www.soinside.com 2019 - 2024. All rights reserved.