2011-11-18 58 views
2

我已經將這個小小的代碼片斷加載到嵌入式Neo4j數據庫中。如何驗證Python中是否存在Neo4j圖形數據庫?

有了這段代碼我有兩個問題,我沒有找到解決它的文檔。

我正在關注文檔樣本以創建索引,但是: a)如何檢測索引是否存在?文檔說明如果索引已經存在,則返回 ,但在我的情況下它返回一個錯誤。

B)當我從索引中的一個節點我得到一個錯誤

from neo4j import GraphDatabase, INCOMING, Evaluation 

# Create a database 
db = GraphDatabase("c:/temp/graph") 

with db.transaction: 
    # Create an index for "users" nodes 
    # to look for them using some of the properties 

    # HERE I GET AN ERROR WHEN THE INDEX EXISTS PREVIOUSLY, BUT THE DOCUMENTATION EXPLAINS THE OPOSITE. 
    users_idx = db.node.indexes.create('users') 

    # Create the "users_reference" node to connect all "users" nodes to here 
    users_reference = db.node() 
    db.reference_node.USERS(users_reference, provider='lucene', type='fulltext') 

    ''' 
    Content of the file 
    1,Marc 
    2,Didac 
    3,Sergi 
    4,David 
    ''' 

    f = open("../files/users","r") 
    for line in f: 
     v = line.split(",") 
     i = v[0] 
     name = v[1] 

     # All write operations happen in a transaction 
     user = db.node(id=i, name=name) 
     user.INSTANCE_OF(users_reference) 
     users_idx['id'][i] = user 

# I suppose that here, the transaction is closed 

# I want get the node whose property "Id" has value "3" 
# to print the property "name" of the node with id = 3 

# HERE I GET AN ERROR WHEN THE THERE'RE MULTIPLE NODES WITH THE SAME VALUE FOR THE PROPERTY "ID" 

c = users_idx['id']['3'].single 
print c['name']     

''' 
If the file has a duplicated ID, the previouly code returns an error... 
1,Marc 
1,Marc_2 
1,Marc_3 
2,Didac 
3,Sergi 
4,David 
'''  

# Always shut down your database when your application exits 
db.shutdown() 
+0

什麼是錯誤訊息? –

回答

2

在你的第一個例子中,該文件是錯誤的。目前只有一種方法可以確定索引是否存在,並且在獲取索引時檢查ValueError。就像這樣:

try: 
    idx = db.node.indexes.get('my_index') 
except ValueError,e: 
    idx = db.node.indexes.create('my_index') 

應改變以一些更具體的例外,因爲這種模式打破了,如果別的東西觸發一個ValueError ..將增加一個問題了點。

我剛剛推送了文檔的更新,並且添加了一個「exists」方法來檢查索引是否存在。它將在下一個neo4j里程碑版本發佈後在Pypi上發佈。

if db.node.indexes.exists('my_index'): 
    db.node.indexes.get('my_index') 
else: 
    db.node.indexes.create('my_index') 

在你的第二個例子中,我認爲這是正確的行爲。 「單一」財產確保有單一結果。如果你期望得到一個結果,但得到多個結果,那是一個錯誤。如果你想第一結果,你應該能夠做這樣的事情:

hits = iter(users_idx['id']['3']) 
c = hits.next() 
hits.close() 
+0

謝謝jakewins! 我已經解決了您的建議的兩個問題。 –