使用pyorient查询OrientDB返回内部ID而非指定属性的问题求助
解决pyorientdb查询返回OrientRecord对象而非属性值的问题
pyorientdb执行查询后返回的OrientRecord对象并非"内部ID",而是封装了查询结果的实体对象,直接打印只会显示对象的内存地址。要获取你请求的属性值,需要从对象中提取对应字段:
方法1:通过字典键直接访问
每个OrientRecord对象支持字典式的属性访问,直接用属性名作为键即可取值:
loadedProteinUIDs = client.command("select uID from Protein LIMIT 5") # 提取所有uID值 uid_results = [record['uID'] for record in loadedProteinUIDs] print(uid_results) loadedProteinXIDs = client.command("select xID from Protein LIMIT 5") xid_results = [record['xID'] for record in loadedProteinXIDs] print(xid_results)
方法2:通过oRecordData属性访问
OrientRecord对象的oRecordData属性是存储所有查询属性的字典,也可以通过它提取值:
loadedProteinUIDs = client.command("select uID from Protein LIMIT 5") uid_results = [record.oRecordData['uID'] for record in loadedProteinUIDs] print(uid_results)
处理不存在的属性
如果查询的属性(比如示例中的xxx)不存在于数据中,直接用键访问会抛出KeyError,可以用字典的get方法设置默认值避免报错:
loadedProteinXXXs = client.command("select xxx from Protein LIMIT 5") xxx_results = [record.get('xxx', None) for record in loadedProteinXXXs] print(xxx_results)
原因说明
OrientDB Studio的REST接口会自动将查询结果序列化为包含属性值的JSON返回,而pyorientdb则返回封装了完整记录信息的OrientRecord对象,方便你在代码中操作记录的其他元数据(比如内部RID、版本号等),因此需要手动提取所需属性。
内容的提问来源于stack exchange,提问作者hans
相关产品推荐
相关产品推荐

