如何使用 PyOrient 找出 OrientDB 上是否存在 class?

How to find out if a class exists on an OrientDB using PyOrient?

如何才能查明 class 是否存在;这允许防止 'class x already exists in current database' 错误消息?

我看过下面的,在Java和SQL中给出了答案。我正在寻找 Python 等价物。

我在 pyorient 中创建了以下示例:

我的结构:

PyORIENT 代码:

import pyorient

db_name = 'Stack37277880'

print("Connecting to the server...")
client = pyorient.OrientDB("localhost",2424)
session_id = client.connect("root","root")
print("OK - sessionID: ",session_id,"\n")

if client.db_exists( db_name, pyorient.STORAGE_TYPE_PLOCAL ):
    client.db_open(db_name, "root", "root")
    dbClasses = client.command("SELECT name FROM (SELECT expand(classes) FROM metadata:schema)")
    newClass = "MyClass"
    classFound = False
    for idx, val in enumerate(dbClasses):
        if (val.name == newClass):
            classFound = True
            break
    if (classFound != True):
        client.command("CREATE CLASS " + newClass)
        print("Class " + newClass + " correctly created")
    else:
        print("Class " + newClass + " already exists into the DB")

client.db_close() 

第一个运行输出:

Connecting to the server...
OK - sessionID:  70 

Class MyClass correctly created

OrientDB Studio:

第二个运行输出:

Connecting to the server...
OK - sessionID:  74 

Class MyClass already exists into the DB

希望对您有所帮助

您可以使用与 Java 示例中相同的查询。

import pyorient

className = "MyClass"

database = pyorient.OrientDB("localhost", 2424)
database.db_open(
"DB_name",
"user",
"password"
)

if not database.command("SELECT FROM ( SELECT expand( classes ) FROM metadata:schema ) WHERE name = '%s'" % className):
    print("Create class %s" % className)
    database.command("CREATE CLASS %s EXTENDS V" % className)
else:
    print("Class already exist.")