本文整理汇总了Python中neo4j.v1.GraphDatabase类的典型用法代码示例。如果您正苦于以下问题:Python GraphDatabase类的具体用法?Python GraphDatabase怎么用?Python GraphDatabase使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了GraphDatabase类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, host, port, username=None, password=None, ssl=False, timeout=None):
port = "7687" if port is None else port
bolt_uri = "bolt://{host}".format(host=host, port=port)
self.http_uri = "http://{host}:{port}/db/data/".format(host=host, port=port)
if username and password:
driver = GraphDatabase.driver(bolt_uri, auth=basic_auth(username, password), encrypted=False)
else:
driver = GraphDatabase.driver(bolt_uri, encrypted=False)
self.session = driver.session()
示例2: connect
def connect(self, url=None, user=None, password=None, **kw):
"""
Parse a Neo4J URL and attempt to connect using Bolt
Note: If the user and password arguments are provided, they
will only be used in case no auth information is provided as
part of the connection URL.
"""
if url is None:
url = 'bolt://localhost'
if user is None:
user = 'neo4j'
if password is None:
password = 'neo4j'
try:
protocol, url = url.split('://')
if protocol.lower() != 'bolt':
warnings.warn('Switching protocols. Only Bolt is supported.')
except ValueError:
pass
try:
credentials, url = url.split('@')
except ValueError:
kw['auth'] = basic_auth(user, password)
else:
kw['auth'] = basic_auth(*credentials.split(':', 1))
self.driver = GraphDatabase.driver('bolt://%s' % url, **kw)
示例3: run_graph
def run_graph(neo4j_conf, args):
opts, args = getopt.getopt(args, "rcsa", ["related", "cluster", "similar", "all"])
if len(args) < 1:
raise getopt.GetoptError("Invalid graph arguments")
query = args[0]
stmt = ''
for o, v in opts:
if o in ["-r", "--related"]:
stmt = ('match (q:Query)<-[r:RELATED]-(a:Query) where q.query={query}'
'return a.query, r.norm_weight order by r.norm_weight desc')
elif o in ["-c", "--cluster"]:
stmt = ('match (q:Query)<-[r:CLUSTER_REP]-(a:Query) where q.query={query}'
'return r.rank, a.query, r.query_terms order by r.rank')
elif o in ["-s", "--similar"]:
stmt = ('match (q:Query)-[r:SIMILAR]-(a:Query) where q.query={query}'
'return a.query, r.score order by r.score desc')
elif o in ["-a", "--all"]:
stmt = ('match (q:Query)<-[r]-() where q.query={query}'
'return q.query, type(r) as rel_type, count(r) as rel_count')
if not stmt:
raise getopt.GetoptError("Invalid graph arguments")
graph = GraphDatabase.driver(neo4j_conf.uri, auth=basic_auth(neo4j_conf.username, neo4j_conf.password))
session = graph.session()
rs = session.run(stmt, parameters={'query': query})
for r in rs:
pprint.pprint(r)
示例4: main
def main(argv=None):
"""Import all data in JSON file into Neo4j database."""
parser = argparse.ArgumentParser(description="Load articles into Neo4j")
parser.add_argument("file",
help="File to read",
type=str,
nargs="?",
metavar="FILE")
parser.add_argument("--no-execute",
action="store_true")
parse_result = parser.parse_args(argv or sys.argv[1:])
with open_or_default(parse_result.file, sys.stdin) as fileobj:
data = json.load(fileobj)
commands = list(commands_from_data(data))
if parse_result.no_execute:
sys.stdout.write(json.dumps(commands))
elif len(commands):
if all(var in os.environ for
var in ["DATABASE_URL", "DATABASE_PASS"]):
url = os.environ["DATABASE_URL"]
pwd = os.environ["DATABASE_PASS"]
usr = os.environ.get("DATABASE_USER", "")
else:
raise ValueError("Ensure environment variables DATABASE_URL, "
"DATABASE_PASS and DATABASE_USER set.")
driver = GraphDatabase.driver(url, auth=basic_auth(usr, pwd))
session = driver.session()
for command in commands:
session.run(command)
session.close()
示例5: main
def main():
parser = argparse.ArgumentParser(description="""
Insert a Terraform state file into neo4j
""")
parser.add_argument('-d','--db', required=True, help="Neo4j host")
parser.add_argument('-u','--username', required=True, help="Neo4j user")
parser.add_argument('-p','--password', required=True, help="Neo4j password")
parser.add_argument('state_file', help="Terraform state file")
args = parser.parse_args()
print args
with open(args.state_file, 'r') as f:
state = json.load(f)
driver = GraphDatabase.driver("bolt://{}".format(args.db),
auth=basic_auth(args.username, args.password))
session = driver.session()
# Reduce all the modules and resouces to a single array of objects
resources = reduce( lambda a,b: a+b,
map(lambda m: m['resources'].values(),
state['modules']))
# Run actions for resources and capture hooks
hooks = set()
for resource in resources:
hooks.add(insert_item(resource, session))
# Run hooks
for hook in hooks:
if hook:
hook(session)
示例6: export_to_neo4j
def export_to_neo4j():
driver = GraphDatabase.driver("bolt://localhost:7687",
encrypted=False,
auth=basic_auth("neo4j", "asdzxc"))
session = driver.session()
for article in db.Article.objects.all():
if article['links']:
# session.run("CREATE (a:Article {name: {name}})",
# {"name": article['title']})
for link in article['links']:
to_article = db.Article.objects.get(id=link)
print(to_article['title'])
session.run("CREATE (a:Article {name: {name}})",
{"name": article['title']})
#
# result = session.run("MATCH (a:Person) WHERE a.name = {name} "
# "RETURN a.name AS name, a.title AS title",
# {"name": "Arthur"})
# for record in result:
# print("%s %s" % (record["title"], record["name"]))
#
session.close()
示例7: test_construct_dwpc_query
def test_construct_dwpc_query():
"""
Test dwpc query construction and computation on the metapath from
https://doi.org/10.1371/journal.pcbi.1004259.g002
"""
directory = pathlib.Path(__file__).parent.absolute()
path = directory.joinpath('data/hetionet-v1.0-metagraph.json')
metagraph = hetio.readwrite.read_metagraph(path)
compound = 'DB01156' # Bupropion
disease = 'DOID:0050742' # nicotine dependency
damping_exponent = 0.4
metapath = metagraph.metapath_from_abbrev('CbGpPWpGaD')
query = hetio.neo4j.construct_dwpc_query(metapath, property='identifier', unique_nodes=True)
assert len(query) > 0
driver = GraphDatabase.driver("bolt://neo4j.het.io")
params = {
'source': compound,
'target': disease,
'w': damping_exponent,
}
with driver.session() as session:
results = session.run(query, params)
results = results.single()
assert results
dwpc = results['DWPC']
assert dwpc == pytest.approx(0.03287590886921623)
示例8: get_session
def get_session(warehouse_home, server_name, password=None,
encrypted=DEFAULT_ENCRYPTED,
silence_loggers=DEFAULT_SILENCE_LOGGERS):
if silence_loggers:
logging.getLogger('neo4j.bolt').setLevel(logging.WARNING)
server = neokit.Warehouse(warehouse_home).get(server_name)
address = server.config('dbms.connector.bolt.address', 'localhost:7687')
server_url = 'bolt://' + address
if password:
driver = GraphDatabase.driver(server_url, encrypted=encrypted,
auth=basic_auth(DEFAULT_USER, password))
else:
driver = GraphDatabase.driver(server_url, encrypted=encrypted)
session = driver.session()
return session
示例9: __init__
def __init__(self):
config = configparser.ConfigParser()
config.read('config.ini')
user_name = config.get('neo4j credentials', 'user_name')
password = config.get('neo4j credentials', 'password')
bolt_host = config.get('neo4j credentials', 'bolt_host')
self.driver = GraphDatabase.driver(bolt_host,
auth=basic_auth(user_name, password))
示例10: init_neo4j_connection
def init_neo4j_connection(app):
server_url = app.config.get('NEO4J_URL', 'bolt://localhost:7687')
encrypted = app.config.get('NEO4J_ENCRYPTED', True)
user = app.config.get('NEO4J_USER', 'neo4j')
password = app.config.get('NEO4J_PASSWORD')
auth = basic_auth(user, password) if password else None
driver = GraphDatabase.driver(server_url,
encrypted=encrypted,
auth=auth)
app.config['NEO4J_DRIVER'] = driver
示例11: server
def server(ctx, host, port, debug):
from . server import app
config = ctx.obj.config
from neo4j.v1 import GraphDatabase, basic_auth
auth = basic_auth(config.neo4j.user, config.neo4j.password)
driver = GraphDatabase.driver(config.neo4j.address, auth=auth)
from attrdict import AttrDict
app.minos = AttrDict({ 'config': config, 'driver': driver })
app.run(host, port, debug)
示例12: __init__
def __init__(self, **kwargs):
#super(Neo4JConn, self).__init__()
config = {
'host': kwargs['db_addr'],
'port': kwargs['db_port'],
'user': kwargs['username'],
'password': kwargs['password']
}
driver = GraphDatabase.driver(
"bolt://%s:%d" % (config['host'], config['port']),
auth=basic_auth(config['user'], config['password']))
self.__session = driver.session()
示例13: neo4j
def neo4j():
from neo4j.v1 import GraphDatabase, basic_auth
driver = GraphDatabase.driver("bolt://localhost:7474", auth=basic_auth("neo4j", "neo4j"))
session = driver.session()
session.run("CREATE (a:Person {name:'Arthur', title:'King'})")
result = session.run("MATCH (a:Person) WHERE a.name = 'Arthur' RETURN a.name AS name, a.title AS title")
for record in result:
print("%s %s" % (record["title"], record["name"]))
session.close()
示例14: __init__
def __init__(self, adress, user, password):
"""
Creates the session to the database
"""
self.driver = GraphDatabase.driver(adress, \
auth=basic_auth(user, password))
try:
self.session = self.driver.session()
except ProtocolError:
print("Cannot connect to neo4j. Aborting.")
exit()
print("Connected to neo4j.")
示例15: __init__
def __init__(self, username = None, password = None, server = None):
if username == None or password == None:
username, password, server = self.loadAuthCredentials()
print(username, password, server)
uri = "bolt://{}:{}@{}".format(username, password, server)
print("Connecting to " + uri)
try:
self.conn = GraphDatabase.driver(uri, auth = (username, password))
self.session = self.conn.session()
except ServiceUnavailable as e:
raise Exception(str(e))