本文整理汇总了Python中neo4j.GraphDatabase.node方法的典型用法代码示例。如果您正苦于以下问题:Python GraphDatabase.node方法的具体用法?Python GraphDatabase.node怎么用?Python GraphDatabase.node使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类neo4j.GraphDatabase
的用法示例。
在下文中一共展示了GraphDatabase.node方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MetaInfoCreator
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import node [as 别名]
class MetaInfoCreator( object ):
def __init__( self, databasePath, datasetDict):
#increment to existing db
self.db = GraphDatabase( databasePath )
self.datasetDict = datasetDict
def start(self):
self._createInfoNodes()
self._finish()
def _createInfoNodes( self ):
print "Creating info nodes"
# do all insertions within one transaction: complete failure or success!
with self.db.transaction:
metaVertex = self.db.node() #self.db.reference_node
print "Meta node created, id %i" %( metaVertex.id )
index = self.db.node.indexes.create('meta')
index['meta']['meta'] = metaVertex
for num, (label, patientFile) in enumerate( self.datasetDict.items() ):
patientFile = open( patientFile, 'r')
patientFile.readline() #header
datasetVertex = self.db.node()
datasetVertex['datalabel'] = label
datasetVertex['barcode'] = patientFile.readline().strip("\n")
metaVertex.relationships.create('DATASET', datasetVertex, label=label)
patientFile.close()
def _finish(self):
self.db.shutdown()
print "Infonodes created"
示例2: addtodb
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import node [as 别名]
def addtodb(lnode, rnode, relationship):
# Create a database
db = GraphDatabase(workingdb)
# rel['subjsym'], rel['objsym'], rel['filler']
with db.transaction:
lnodef = False #lnodef and rnodef store whether the node has been found in the db
rnodef = False
for node in db.nodes:
for key, value in node.items():
if (key == "name"):
if(value == lnode):
leftnode = node
lnodef = True
if(value == rnode):
rightnode = node
rnodef = True
if (not lnodef):
leftnode = db.node(name=(lnode))
print "Lnode " + lnode + "created"
if (not rnodef):
rightnode = db.node(name=(rnode))
print "Rnode " + rnode + "created"
relf = False
for rel in leftnode.relationships.outgoing:
for key, value in rel.items():
if (str(rel.type) == relationship and key == 'hits'and rel.end == rightnode):
rel[key] = value + 1
relf = True
print "rel found. Increasing number of hits "
if (not relf):
rel = leftnode.relationships.create(relationship, rightnode)
print "created relationship " + relationship
rel['hits'] = 1
db.shutdown()
示例3: test_hello_world
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import node [as 别名]
def test_hello_world(self):
folder_to_put_db_in = tempfile.mkdtemp()
try:
# START SNIPPET: helloworld
from neo4j import GraphDatabase
# Create a database
db = GraphDatabase(folder_to_put_db_in)
# All write operations happen in a transaction
with db.transaction:
firstNode = db.node(name="Hello")
secondNode = db.node(name="world!")
# Create a relationship with type 'knows'
relationship = firstNode.knows(secondNode, name="graphy")
# Read operations can happen anywhere
message = " ".join([firstNode["name"], relationship["name"], secondNode["name"]])
print message
# Delete the data
with db.transaction:
firstNode.knows.single.delete()
firstNode.delete()
secondNode.delete()
# Always shut down your database when your application exits
db.shutdown()
# END SNIPPET: helloworld
finally:
if os.path.exists(folder_to_put_db_in):
import shutil
shutil.rmtree(folder_to_put_db_in)
self.assertEqual(message, "Hello graphy world!")
示例4: __init__
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import node [as 别名]
class NeoCreator:
def __init__(self,path):
self.db = GraphDatabase(path)
def shutdown(self):
self.db.shutdown()
def createNewNode(self,_id,nick):
with self.db.transaction:
newNode = self.db.node(uid=_id,Label=nick)
if newNode is None:
raise
return newNode
def createRelationship(self,origin,destiny):
with self.db.transaction:
origin.tweets(destiny,Label="tweets")
示例5: addUser
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import node [as 别名]
def addUser(usuario):
# Create a database
db = GraphDatabase('/tmp/')
user_idx = db.node.indexes.get('users')
cafe_idx = db.node.indexes.get('cafes')
# All write operations happen in a transaction
with db.transaction:
firstNode = db.node(name=usuario, type_record='user')
user_idx['name'][usuario] = firstNode
secondNode = cafe_idx['name']['lungo'].single
# Create a relationship with type 'knows'
relationship = firstNode.toma(secondNode, cantidad=3)
# Always shut down your database when your application exits
db.shutdown()
示例6: CableNetwork
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import node [as 别名]
class CableNetwork(object):
def __init__(self, config, overwrite=True, minoccs=1, mincoocs=1, maxcables=None, year=None):
self.mongodb = CablegateDatabase(config['general']['mongodb'])["cablegate"]
self.graphdb = GraphDatabase(config['general']['neo4j'])
self.config = config
nodecache = self.update_occurrences_network(minoccs, mincoocs, maxcables, year)
self.update_cooccurrences_network(nodecache, minoccs, mincoocs, maxcables)
def update_occurrences_network(self, minoccs=1, mincoocs=1, maxcables=None, year=None):
nodecache = {}
count=0
if maxcables is None:
maxcables = self.mongodb.cables.count()
if year is None:
cable_curs = self.mongodb.cables.find(timeout=False)
else:
start = datetime(year,1,1,0,0,0)
end = datetime(year+1,1,5,0,0,0)
cable_curs = self.mongodb.cables.find({"start":{"$gte":start,"$lt":end}}, timeout=False)
for cable in cable_curs:
with self.graphdb.transaction as trans:
del cable['content']
#cablenode = self.add_node(cable, trans)
for ngid, occs in cable['edges']['NGram'].iteritems():
ngram = self.mongodb.ngrams.find_one({'_id':ngid})
if ngram is None:
logging.warning('ngram %s linked to document %s but not found in mongodb'%(ngid, cable['_id']))
continue
if ngram['occs'] < minoccs: continue
### first time if export this node
if 'nodeid' not in ngram or str(ngram['nodeid']) not in nodecache:
new_ngramnode = self.add_node(ngram, trans)
ngram['nodeid'] = new_ngramnode.id
nodecache[str(new_ngramnode.id)] = new_ngramnode
self.mongodb.ngrams.save(ngram)
#cablenode.occurrence(nodecache[str(ngram['nodeid'])], weight=occs)
logging.debug("done the network around cable %s"%cable["_id"])
count += 1
if count > maxcables: return nodecache
return nodecache
def update_cooccurrences_network(self, nodecache, minoccs=1, mincoocs=1, maxcables=None):
nodecachedkeys = [int(key) for key in nodecache.keys()]
logging.debug("cooccurrences processing for %d ngram nodes"%self.mongodb.ngrams.find({'nodeid': {"$in": nodecachedkeys}}, timeout=False).count())
with self.graphdb.transaction as trans:
for ngram in self.mongodb.ngrams.find({'nodeid': {"$in": nodecachedkeys}}, timeout=False):
# this REGEXP select only edges with source == ngram['_id']
coocidRE = re.compile("^"+ngram['_id']+"_[a-z0-9]+$")
for cooc in self.mongodb.cooc.find({"_id":{"$regex":coocidRE}}, timeout=False, sort=[("value",pymongo.DESCENDING)], limit=mincoocs):
#if cooc['value'] < mincoocs: continue
ng1, ng2 = cooc['_id'].split("_")
if ng1 == ng2:
self.mongodb.cooc.delete({"_id":cooc['_id']})
continue
ngram2 = self.mongodb.ngrams.find_one({'_id':ng2})
if 'nodeid' not in ngram2:
new_ngramnode = self.add_node(ngram2, trans)
ngram['nodeid'] = new_ngramnode.id
nodecache[str(new_ngramnode.id)] = new_ngramnode
#self.mongodb.ngrams.save(ngram2)
if ngram2['nodeid'] == ngram['nodeid']:
logging.warning("not setting relationship on a node itself")
continue
if ngram2['nodeid'] not in nodecachedkeys:
#logging.warning("ngram not in nodecache keys, skipping")
continue
# inserting the cooccurrence
nodecache[str(ngram['nodeid'])].cooccurrence(nodecache[str(ngram2['nodeid'])], weight=cooc['value'])
def set_node_attr(self, record, node):
"""
Type conversion from python/mongodb to neo4j
restricts a node's attributes to string or numeric
"""
for key, value in record.iteritems():
if type(value) == unicode:
node[key.encode("ascii","ignore")] = value.encode("ascii","ignore")
elif type(value) == int or type(value) == float or type(value) == str:
node[key.encode("utf-8","replace")] = value
elif type(value) == datetime:
node[key.encode("utf-8","replace")] = value.strftime('%Y-%m-%d')
def add_node(self, record, transact=None):
if transact is None:
with self.transaction:
node = self.graphdb.node()
self.set_node_attr(record, node)
return node
else:
node = self.graphdb.node()
self.set_node_attr(record, node)
return node
def get_node(self, _id):
return self.graphdb.node[_id]
示例7: GraphDatabase
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import node [as 别名]
#!/usr/bin/python
#coding:utf8
# Created: 2013-11-05
#
'''
A sample app using cypher and indexes
'''
from neo4j import GraphDatabase, INCOMING, Evaluation
# Create a database
db = GraphDatabase(folder_to_put_db_in)
# All write operations happen in a transaction
with db.transaction:
# A node to connect customers to
customers = db.node()
# A node to connect invoices to
invoices = db.node()
# Connected to the reference node, so
# that we can always find them.
db.reference_node.CUSTOMERS(customers)
db.reference_node.INVOICES(invoices)
# An index, helps us rapidly look up customers
customer_idx = db.node.indexes.create('customers')
示例8: __init__
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import node [as 别名]
class Neo4jHandler:
def __init__(self, graph_path):
config = {"node_keys_indexable":'key,name',"node_auto_indexing":'true' }
self.graph_db = GraphDatabase(graph_path ,**config)
self.node_auto_index = self.graph_db.node.indexes.get('node_auto_index')
#self.graph_db = py2neo.neo4j.GraphDatabaseService( graph_path)
def findNode(self, node_dict):
result = self.node_auto_index['key'][node_dict['key']]
if result:
# .single goes mad when there is a result set with more than one value
return result.single
#py2neo_node = self.graph_db.get_indexed_node('node_auto_index', 'key', node_dict['key'])
#return py2neo_node
def createUniqueNodeByKey(self, node_dict):
py2neo_node = self.findNode(node_dict)
if py2neo_node:
# if it was found return it
return py2neo_node
else:
# if not create it
with self.graph_db.transaction:
return self.graph_db.node( **node_dict )
#return self.graph_db.node( node(**node_dict) )[0]
def findNodeByKey(self, key, value):
return self.node_auto_index[key][value].single
#py2neo_node = self.graph_db.get_indexed_node('node_auto_index', key, value)
#return py2neo_node
def addEvent(self, parsed_data):
# create event node
key_of_relato = "relato:"+str(parsed_data['id_relato'])
with self.graph_db.transaction:
relato_neo4j_node = self.graph_db.node(key=key_of_relato, type="relato")
#relato_neo4j_node = self.graph_db.create( node(key=key_of_relato) )[0]
# connect victims to events via actos
actos_processed = list()
for acto in parsed_data['actos']:
actos_processed.append(self.getCrimes(acto))
victim_groups = set()
for acto in actos_processed:
key_of_victim_node = acto[0]
if key_of_victim_node.startswith('grupo:'):
victim_groups.add(key_of_victim_node)
# get the node dictioanry of the armed entities
list_of_node_dict_armed_entities = list()
list_of_node_dict_victim_groups=list()
for armed_entity in parsed_data['grupo']:
node_dict_entity = self.getArmedEntity(armed_entity)
if not node_dict_entity['key'] in victim_groups:
list_of_node_dict_armed_entities.append( node_dict_entity )
else:
list_of_node_dict_victim_groups.append(node_dict_entity)
# add them to neo4j
list_of_neo4j_armed_nodes =list()
for armed_node_dict in list_of_node_dict_armed_entities:
# create armed group node
armed_node =self.createUniqueNodeByKey(armed_node_dict)
list_of_neo4j_armed_nodes.append(armed_node)
# relate armed group with eevent
#self.graph_db.create( (armed_node,'responsible_for',relato_neo4j_node) )
with self.graph_db.transaction:
armed_node.relationships.create('responsible_for', relato_neo4j_node )
for victim_group in list_of_node_dict_victim_groups:
# create armed group node
victim_group_node =self.createUniqueNodeByKey(victim_group)
# get the node dictionaries for the victims
list_of_node_dict_victims = list()
list_of_adjacent_victim_relation = list()
for victima in parsed_data['victimas']:
victim_node, adjacent_relations = self.getVictim(victima)
list_of_node_dict_victims.append(victim_node)
list_of_adjacent_victim_relation.append(adjacent_relations)
# add them to neo4j
list_of_neo4j_victim_nodes =list()
for index in range(0,len(list_of_node_dict_victims)):
victim_node_dict = list_of_node_dict_victims[index]
other_relations = list_of_adjacent_victim_relation[index]
# create victim node
victim_node =self.createUniqueNodeByKey(victim_node_dict)
list_of_neo4j_victim_nodes.append(victim_node)
#.........这里部分代码省略.........
示例9: test_invoice_app
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import node [as 别名]
def test_invoice_app(self):
folder_to_put_db_in = tempfile.mkdtemp()
try:
# START SNIPPET: invoiceapp-setup
from neo4j import GraphDatabase, INCOMING, Evaluation
# Create a database
db = GraphDatabase(folder_to_put_db_in)
# All write operations happen in a transaction
with db.transaction:
# A node to connect customers to
customers = db.node()
# A node to connect invoices to
invoices = db.node()
# Connected to the reference node, so
# that we can always find them.
db.reference_node.CUSTOMERS(customers)
db.reference_node.INVOICES(invoices)
# An index, helps us rapidly look up customers
customer_idx = db.node.indexes.create('customers')
# END SNIPPET: invoiceapp-setup
# START SNIPPET: invoiceapp-domainlogic-create
def create_customer(name):
with db.transaction:
customer = db.node(name=name)
customer.INSTANCE_OF(customers)
# Index the customer by name
customer_idx['name'][name] = customer
return customer
def create_invoice(customer, amount):
with db.transaction:
invoice = db.node(amount=amount)
invoice.INSTANCE_OF(invoices)
invoice.SENT_TO(customer)
return customer
# END SNIPPET: invoiceapp-domainlogic-create
# START SNIPPET: invoiceapp-domainlogic-get-by-idx
def get_customer(name):
return customer_idx['name'][name].single
# END SNIPPET: invoiceapp-domainlogic-get-by-idx
# START SNIPPET: invoiceapp-domainlogic-get-by-cypher
def get_invoices_with_amount_over(customer, min_sum):
# Find all invoices over a given sum for a given customer.
# Note that we return an iterator over the "invoice" column
# in the result (['invoice']).
return db.query('''START customer=node({customer_id})
MATCH invoice-[:SENT_TO]->customer
WHERE has(invoice.amount) and invoice.amount >= {min_sum}
RETURN invoice''',
customer_id = customer.id, min_sum = min_sum)['invoice']
# END SNIPPET: invoiceapp-domainlogic-get-by-cypher
# START SNIPPET: invoiceapp-create-and-search
for name in ['Acme Inc.', 'Example Ltd.']:
create_customer(name)
# Loop through customers
for relationship in customers.INSTANCE_OF:
customer = relationship.start
for i in range(1,12):
create_invoice(customer, 100 * i)
# Finding large invoices
large_invoices = get_invoices_with_amount_over(get_customer('Acme Inc.'), 500)
# Getting all invoices per customer:
for relationship in get_customer('Acme Inc.').SENT_TO.incoming:
invoice = relationship.start
# END SNIPPET: invoiceapp-create-and-search
self.assertEqual(len(list(large_invoices)), 7)
db.shutdown()
finally:
if os.path.exists(folder_to_put_db_in):
import shutil
shutil.rmtree(folder_to_put_db_in)
示例10: open
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import node [as 别名]
#!/usr/bin/env python
import networkx as nx
import sys
from neo4j import GraphDatabase
#path ='/home/jvipin/scratch/ibm_dns_ocr/misc/graphdb/'
path = '/scratch/vipin/working_dns_data/ccs/precision/ibm_dns_ocr/misc/graphdb/'
f = open(sys.argv[1],'r')
db = GraphDatabase(path)
count = 0
for ln in f:
count += 1
line = ln.rstrip().split(',')
if count%10000 == 0:
print count
# print line[0],line[1],line[2],line[3],line[4]
with db.transaction:
fnode = db.node(name=line[0],ntype=line[2])
snode = db.node(name=line[1],ntype=line[3])
rel = fnode.knows(snode,etype=line[4])
db.shutdown()
f.close()
示例11: GraphDatabase
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import node [as 别名]
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Neo4j图形数据库示例
#
from neo4j import GraphDatabase, INCOMING
# 创建或连接数据库
db = GraphDatabase('neodb')
# 在一个事务内完成写或读操作
with db.transaction:
#创建用户组节点
users = db.node()
# 连接到参考节点,方便查找
db.reference_node.USERS(users)
# 为用户组建立索引,便于快速查找
user_idx = db.node.indexes.create('users')
#创建用户节点
def create_user(name):
with db.transaction:
user = db.node(name=name)
user.INSTANCE_OF(users)
# 建立基于用户name的索引
user_idx['name'][name] = user
return user
#根据用户名获得用户节点
def get_user(name):
return user_idx['name'][name].single
示例12: GraphDatabase
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import node [as 别名]
# Created: 2013-11-05
#
'''
Hello, world!
'''
from neo4j import GraphDatabase
# Create a database
db = GraphDatabase(u'store')
# All write operations happen in a transaction
with db.transaction:
firstNode = db.node(name='Hello')
secondNode = db.node(name='world!')
# Create a relationship with type 'knows'
relationship = firstNode.knows(secondNode, name='graphy')
# Read operations can happen anywhere
message = ' '.join([firstNode['name'], relationship['name'], secondNode['name']])
print message
# Delete the data
with db.transaction:
firstNode.knows.single.delete()
firstNode.delete()
secondNode.delete()
示例13: GraphDatabase
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import node [as 别名]
from neo4j import GraphDatabase
# Create a database
db = GraphDatabase('/tmp/')
user_idx = db.node.indexes.create('users')
cafe_idx = db.node.indexes.create('cafes')
# All write operations happen in a transaction
with db.transaction:
firstNode = db.node(name='usuario', node_type='user')
secondNode = db.node(name='lungo', node_type='cafe')
user_idx['name']['usuario'] = firstNode
cafe_idx['name']['lungo'] = secondNode
# Create a relationship with type 'knows'
relationship = firstNode.toma(secondNode, cantidad=3)
# Always shut down your database when your application exits
db.shutdown()
示例14: Copyrgiht
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import node [as 别名]
Description:
Actions related to database only
Copyrgiht (c) 2012 by huxuan. All rights reserved.
License GPLv3
"""
from neo4j import GraphDatabase
from config import DBNAME
GRAPHDB = GraphDatabase(DBNAME)
if GRAPHDB.node.indexes.exists('user'):
USER_IDX = GRAPHDB.node.indexes.get('user')
else:
USER_IDX = GRAPHDB.node.indexes.create('user')
if GRAPHDB.node.indexes.exists('tweet'):
TWEET_IDX = GRAPHDB.node.indexes.get('tweet')
else:
TWEET_IDX = GRAPHDB.node.indexes.create('tweet')
TWEET_REF_ID = 1000000
if len(TWEET_IDX['tid'][TWEET_REF_ID]) == 0:
with GRAPHDB.transaction:
TWEET_REF = GRAPHDB.node()
TWEET_REF['tot_tweet'] = 0
TWEET_IDX['tid'][TWEET_REF_ID] = TWEET_REF
TWEET_REF = TWEET_IDX['tid'][TWEET_REF_ID].single
示例15: Memory
# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import node [as 别名]
class Memory(object):
def __init__(self,mind,dbpath="data"):
self.mind = mind
self.dbpath = dbpath
self.mind.log("Starting Graph Database at "+dbpath)
self.db = GraphDatabase(dbpath)
self.root = None
memorySize = len(self.db.nodes)
self.log("starting with "+str(memorySize)+" nodes in memory")
self.vars = {}
self.initialGraph(memorySize<=1)
def __del__(self):
self.shutdown()
def shutdown(self):
self.log("shutting down Graph Database...")
self.db.shutdown()
def log(self,something):
self.mind.log(something)
def error(self,errorType,command):
self.mind.error(errorType,command)
def initialTime(self,create=False):
if create:
self.log("create time graph...")
with self.db.transaction:
self.timeIndex = self.db.node.indexes.create('abstractTime')
self.eventIndex = self.db.node.indexes.create('events')
self.vars["timeroot"] = self.createNode("TIME_ROOT")
self.vars["root"].TIMERELATION(self.vars["timeroot"])
self.vars["timeroot"].TIMERELATION(self.createNode("JALALI_CALENDAR"),cal_type="J")
self.vars["timeroot"].TIMERELATION(self.createNode("HIJRI_CALENDAR"),cal_type="H")
self.vars["timeroot"].TIMERELATION(self.createNode("GREGORY_CALENDAR"),cal_type="G")
else:
self.log("initial time...")
with self.db.transaction:
self.vars["timeroot"] = self.vars["root"].TIMERELATION.single.end
self.timeIndex = self.db.node.indexes.get('abstractTime')
self.eventIndex = self.db.nodes.indexes.get('events')
def initialPlace(self,create=False):
if create:
self.log("create place graph ...")
with self.db.transaction:
self.placeIndex = self.db.node.indexes.create('abstractPlace')
self.vars["placeroot"] = self.createNode(name="PLACE_ROOT")
self.vars["root"].PLACERELATION(self.vars["placeroot"])
else:
self.log("initial place ...")
with self.db.transaction:
self.vars["placeroot"] = self.vars["root"].PLACERELATION.single.end
self.placeIndex = self.db.node.indexes.get('abstractPlace')
def initialObjects(self,create=False):
if create:
with self.db.transaction:
self.vars["objectroot"] = self.createNode("OBJECT_ROOT")
self.vars["root"].OBJECTRELATION(self.vars["objectroot"])
self.vars["actionroot"] = self.createNode("ACTION_ROOT")
self.vars["objectroot"].ACTIONRELATION(self.vars["actionroot"])
self.vars["eventroot"] = self.createNode("EVENT_ROOT")
self.vars["objectroot"].EVENTRELATION(self.vars["eventroot"])
self.vars["me"] = self.createNode('me')
self.vars["me"].ISA(self.vars["objectroot"],type="me")
self.vars["master"] = self.createNode('master')
self.vars["master"].ISA(self.vars["objectroot"],type="master")
else:
self.vars["objectroot"] = self.vars["root"].OBJECTRELATION.single.end
self.vars["actionroot"] = self.vars["objectroot"].ACTIONRELATION.single.end
self.vars["eventroot"] = self.vars["objectroot"].EVENTRELATION.single.end
self.vars["me"] = [rel for rel in self.vars["objectroot"].ISA.incoming if rel["type"]=="me" ][0].start
self.vars["master"] = [rel for rel in self.vars["objectroot"].ISA.incoming if rel["type"]=="master" ][0].start
def initialGraph(self,create=False):
if create:
self.log("create Graph ...")
with self.db.transaction:
self.vars["root"] = self.db.node[0]
self.vars["root"]['name'] = 'ROOT'
self.nameIndex = self.db.node.indexes.create('name')
self.indexName(self.vars["root"])
self.messageIndex = self.db.node.indexes.create('message',type='fulltext')
else:
self.log("initial graph...")
with self.db.transaction:
self.vars["root"] = self.db.node[0]
self.nameIndex = self.db.node.indexes.get('name')
self.messageIndex = self.db.node.indexes.get('message')
self.initialTime(create)
self.initialPlace(create)
self.initialObjects(create)
def getNodes(self,str):
if str.startswith("`") and str.endswith("`"):
result = []
for id in str[1:-1].split(","):
result.append(self.db.node[int(id)])
#.........这里部分代码省略.........