Esempio n. 1
0
 def test_must_use_valid_url_scheme(self):
     try:
         GraphDatabase.driver("x://xxx")
     except ValueError:
         assert True
     else:
         assert False
Esempio n. 2
0
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" 
Esempio n. 3
0
def showAllDB():
	db = GraphDatabase(workingdb)

	query = """START n=node(*)
				MATCH (n) - [r] -> (m)
				RETURN n.name, r, m.name"""

	print db.query(query)

	db.shutdown()
Esempio n. 4
0
def get_rel_info(dbname,relid):        
    from neo4j import GraphDatabase
    from neo4j import OUTGOING, INCOMING, ANY
    db = GraphDatabase(dbname)
    relid = int(relid) #make sure it is an int
    rel = db.relationship[relid]
    print rel
    for key,value in rel.items():
        print "\t"+key,value
    db.shutdown()
Esempio n. 5
0
def get_node_info(dbname,nodeid):
    from neo4j import GraphDatabase
    from neo4j import OUTGOING, INCOMING, ANY
    db = GraphDatabase(dbname)
    nodeid = int(nodeid) #make sure it is an int
    nd = db.node[nodeid]
    print nd
    for key,value in nd.items():
        print "\t"+key,value
        if "uniqname" in str(key):
            break
    db.shutdown()
Esempio n. 6
0
def showAllRelations(qname):
	db = GraphDatabase(workingdb)


	query = """START n=node(*)
			   MATCH (n) - [r] -> (m)
			   WHERE HAS(n.name) AND n.name = {name}
			   RETURN n.name, r, m.name"""

	print db.query(query, name=qname)


	db.shutdown()
Esempio n. 7
0
 def test_create_configured_db(self):
     folder_to_put_db_in = tempfile.mkdtemp()
     try:
         # START SNIPPET: creatingConfiguredDatabase
         from neo4j import GraphDatabase
         
         # Example configuration parameters
         db = GraphDatabase(folder_to_put_db_in, string_block_size=200, array_block_size=240)
         
         db.shutdown()
         # END SNIPPET: creatingConfiguredDatabase
     finally:
        if os.path.exists(folder_to_put_db_in):
           import shutil
           shutil.rmtree(folder_to_put_db_in)
Esempio n. 8
0
    def __init__(self, options, columns):

        # Calling super constructor
        super(Neo4jForeignDataWrapper, self).__init__(options, columns)

        # Managed server option
        if 'url' not in options:
            log_to_postgres('The Bolt url parameter is required and the default is "bolt://localhost:7687"', WARNING)
        self.url = options.get("url", "bolt://localhost:7687")

        if 'user' not in options:
            log_to_postgres('The user parameter is required  and the default is "neo4j"', ERROR)
        self.user = options.get("user", "neo4j")

        if 'password' not in options:
            log_to_postgres('The password parameter is required for Neo4j', ERROR)
        self.password = options.get("password", "")

        if 'cypher' not in options:
            log_to_postgres('The cypher parameter is required', ERROR)
        self.cypher = options.get("cypher", "MATCH (n) RETURN n LIMIT 100")

        # Setting table columns
        self.columns = columns

        # Create a neo4j driver instance
        self.driver = GraphDatabase.driver( self.url, auth=basic_auth(self.user, self.password))

        self.columns_stat = self.compute_columns_stat()
        self.table_stat = int(options.get("estimated_rows", -1))
        if(self.table_stat < 0):
            self.table_stat = self.compute_table_stat()
        log_to_postgres('Table estimated rows : ' + unicode(self.table_stat), DEBUG)
Esempio n. 9
0
 def test_can_run_simple_statement(self):
     session = GraphDatabase.driver("bolt://localhost").session()
     count = 0
     for record in session.run("RETURN 1 AS n"):
         assert record[0] == 1
         assert record["n"] == 1
         try:
             record["x"]
         except AttributeError:
             assert True
         else:
             assert False
         assert record.n == 1
         try:
             record.x
         except AttributeError:
             assert True
         else:
             assert False
         try:
             record[object()]
         except TypeError:
             assert True
         else:
             assert False
         assert repr(record)
         assert len(record) == 1
         count += 1
     session.close()
     assert count == 1
Esempio n. 10
0
 def test_create_db(self):
     folder_to_put_db_in = tempfile.mkdtemp()
     try:
         # START SNIPPET: creatingDatabase
         from neo4j import GraphDatabase
         
         # Create db
         db = GraphDatabase(folder_to_put_db_in)
         
         # Always shut down your database
         db.shutdown()
         # END SNIPPET: creatingDatabase
     finally:
        if os.path.exists(folder_to_put_db_in):
           import shutil
           shutil.rmtree(folder_to_put_db_in)
Esempio n. 11
0
 def test_fails_on_missing_parameter(self):
     session = GraphDatabase.driver("bolt://localhost").session()
     try:
         session.run("RETURN {x}").consume()
     except CypherError:
         assert True
     else:
         assert False
Esempio n. 12
0
 def test_can_run_statement_that_returns_multiple_records(self):
     session = GraphDatabase.driver("bolt://localhost").session()
     count = 0
     for record in session.run("unwind(range(1, 10)) AS z RETURN z"):
         assert 1 <= record[0] <= 10
         count += 1
     session.close()
     assert count == 10
Esempio n. 13
0
def get_nodeinfo_for_name(dbname,name):
    from neo4j import GraphDatabase
    from neo4j import OUTGOING, INCOMING, ANY
    db = GraphDatabase(dbname)
    with db.transaction:
        node_idx = db.node.indexes.get('graphNamedNodes')
        hits = node_idx['name'][name]
        for i in hits:
            print i
            for key,value in i.items():
                print "\t"+key,value
                #printing after, prints mrcas which are usually too long
                #comment to let it go, but don't commit
                if "uniqname" in str(key):
                    break
        hits.close()
    db.shutdown()
Esempio n. 14
0
 def get_db(self, data_dir=None):
     from neo4j import GraphDatabase
     if self._db is None:
         if data_dir is None:
             data_dir = settings.GRAPH_DATABASE_PATH
         self._db = GraphDatabase(data_dir)
     db = self._db
     return self._db
Esempio n. 15
0
 def test_fails_on_bad_syntax(self):
     session = GraphDatabase.driver("bolt://localhost").session()
     try:
         session.run("X").consume()
     except CypherError:
         assert True
     else:
         assert False
Esempio n. 16
0
def showAllNodes():

	# open the db
	db = GraphDatabase(workingdb)

	number_of_nodes = len(db.nodes)
	query = "START n=node(*) RETURN n"

	print "This db has " + str(number_of_nodes) +"nodes" 
	
	if(number_of_nodes>0):

		print db.query(query)
	else: 
		print "no nodes"
	
	db.shutdown()
Esempio n. 17
0
 def test_can_handle_cypher_error(self):
     with GraphDatabase.driver("bolt://localhost").session() as session:
         try:
             session.run("X")
         except CypherError:
             assert True
         else:
             assert False
Esempio n. 18
0
 def test_can_obtain_summary_info(self):
     with GraphDatabase.driver("bolt://localhost").session() as session:
         result = session.run("CREATE (n) RETURN n")
         summary = result.summarize()
         assert summary.statement == "CREATE (n) RETURN n"
         assert summary.parameters == {}
         assert summary.statement_type == "rw"
         assert summary.statistics.nodes_created == 1
Esempio n. 19
0
 def __init__(self, config, graphtype, minoccs=1, maxcoocs=1, maxcables=None, year=None):
     self.mongodb = CablegateDatabase(config['general']['mongodb'])["cablegate"]
     self.graphdb = GraphDatabase(config['general']['neo4j'])
     self.config = config
     if graphtype is None or graphtype=="occurrences":
         self.update_occurrences_network(minoccs, maxcoocs, maxcables, year, documents=False)
     elif graphtype == "cooccurrences":
         (nodecache, ngramcache) = self.update_occurrences_network(minoccs, maxcoocs, maxcables, year, documents=False)
         self.update_cooccurrences_network(nodecache, ngramcache, minoccs, maxcoocs)
Esempio n. 20
0
 def test_can_return_node(self):
     with GraphDatabase.driver("bolt://localhost").session() as session:
         result = session.run("MERGE (a:Person {name:'Alice'}) RETURN a")
         assert len(result) == 1
         for record in result:
             alice = record[0]
             assert isinstance(alice, Node)
             assert alice.labels == {"Person"}
             assert alice.properties == {"name": "Alice"}
Esempio n. 21
0
 def test_can_return_relationship(self):
     with GraphDatabase.driver("bolt://localhost").session() as session:
         result = session.run("MERGE ()-[r:KNOWS {since:1999}]->() RETURN r")
         assert len(result) == 1
         for record in result:
             rel = record[0]
             assert isinstance(rel, Relationship)
             assert rel.type == "KNOWS"
             assert rel.properties == {"since": 1999}
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")
Esempio n. 23
0
 def test_can_obtain_plan_info(self):
     with GraphDatabase.driver("bolt://localhost").session() as session:
         result = session.run("EXPLAIN CREATE (n) RETURN n")
         plan = result.summarize().plan
         assert plan.operator_type == "ProduceResults"
         assert plan.identifiers == ["n"]
         assert plan.arguments == {"planner": "COST", "EstimatedRows": 1.0, "version": "CYPHER 3.0",
                                   "KeyNames": "n", "runtime-impl": "INTERPRETED", "planner-impl": "IDP",
                                   "runtime": "INTERPRETED"}
         assert len(plan.children) == 1
Esempio n. 24
0
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()
def main():
    
    global db

    try:
        shutil.rmtree('benchmark_db')
    except:
        pass
    db = GraphDatabase('benchmark_db')
    repetitions = 10
    count = 1000

    transaction_benchmark(repetitions)
    node_benchmark(repetitions,count)
    relation_benchmark(repetitions,count)
    traversal_benchmark(repetitions,count)
    indexing_benchmark(repetitions,count)
    lookup_benchmark(repetitions,count)

    db.shutdown()
Esempio n. 26
0
 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)
Esempio n. 27
0
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()
Esempio n. 28
0
 def test_can_obtain_profile_info(self):
     with GraphDatabase.driver("bolt://localhost").session() as session:
         result = session.run("PROFILE CREATE (n) RETURN n")
         profile = result.summarize().profile
         assert profile.db_hits == 0
         assert profile.rows == 1
         assert profile.operator_type == "ProduceResults"
         assert profile.identifiers == ["n"]
         assert profile.arguments == {"planner": "COST", "EstimatedRows": 1.0, "version": "CYPHER 3.0",
                                      "KeyNames": "n", "runtime-impl": "INTERPRETED", "planner-impl": "IDP",
                                      "runtime": "INTERPRETED", "Rows": 1, "DbHits": 0}
         assert len(profile.children) == 1
Esempio n. 29
0
 def test_can_return_path(self):
     with GraphDatabase.driver("bolt://localhost").session() as session:
         result = session.run("MERGE p=({name:'Alice'})-[:KNOWS]->({name:'Bob'}) RETURN p")
         assert len(result) == 1
         for record in result:
             path = record[0]
             assert isinstance(path, Path)
             assert path.start.properties == {"name": "Alice"}
             assert path.end.properties == {"name": "Bob"}
             assert path.relationships[0].type == "KNOWS"
             assert len(path.nodes) == 2
             assert len(path.relationships) == 1
Esempio n. 30
0
 def test_can_run_simple_statement_from_bytes_string(self):
     session = GraphDatabase.driver("bolt://localhost").session()
     count = 0
     for record in session.run(b"RETURN 1 AS n"):
         assert record[0] == 1
         assert record["n"] == 1
         assert record.n == 1
         assert repr(record)
         assert len(record) == 1
         count += 1
     session.close()
     assert count == 1
Esempio n. 31
0
 def __init__(self, uri, user, password):
     self.driver = GraphDatabase.driver(uri,
                                        auth=(user, password),
                                        encrypted=False)
Esempio n. 32
0
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 27 19:29:30 2020

@author: Owner
"""

import os
import glob
import json
from getpass import getpass

from tqdm import tqdm
from neo4j import GraphDatabase

driver = GraphDatabase.driver("neo4j://localhost:7687",
                              auth=("neo4j", getpass()))
Esempio n. 33
0
from neo4j import GraphDatabase
import json

driver = GraphDatabase.driver("bolt://neo4j:7687",
                              auth=("neo4j", "test"),
                              encrypted=False)

session = driver.session()

node_id = 1835

query = "MATCH (rn:RootNode)--(cf:ContentField)--(sen:Sentence)--(ent:Entity) "
query += "WHERE (rn.name = '" + str(node_id) + "') "
query += "RETURN DISTINCT rn.name as node_id, ent.ner as ent_ner, ent.text as ent_text "
query += "ORDER BY ent.ner ASC"

result = session.run(query)

res_dict = []
for record in result:
    res_dict.append({
        'node_id': record['node_id'],
        'ent_ner': record['ent_ner'],
        'ent_text': record['ent_text']
    })

print(res_dict)
Esempio n. 34
0
from neo4j import GraphDatabase
from Database import Database
from Classes.Career import *
import tkinter as tk

uri = "bolt://localhost:7687"

driver = GraphDatabase.driver(uri, auth=("neo4j", "password"))
db = Database("bolt://localhost:7687", "neo4j", "password")

career_name = "Prueba"

# Prueba para crear a base de datos.
db.deleteCareer(career_name)

nodeType1 = "Clase"
nodeType2 = "Persona"
nodeType3 = "gusto"
nodeType4 = "Carrera"

materias = []
personas = []
hobbies = []
carreras = []

# Prueba para obtener todos de un tipo
result1 = db.getAllType(nodeType1)
for record in result1:
    materias.append(record[0]["nombre"])

result2 = db.getAllType(nodeType2)
Esempio n. 35
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 29 18:31:17 2018

@author: geoffrey
"""

from neo4j import GraphDatabase

uri = "bolt://localhost:7687"
driver = GraphDatabase.driver(uri, auth=("test", "test"))


###############################################################################
# FONCTION nombre de proteines
###############################################################################
def number_of_protein(tx):
    for record in tx.run("match (n:Protein) return count(n)"):
        return record["count(n)"]


def number_of_protein_interface():
    with driver.session() as session:
        a = session.read_transaction(number_of_protein)
    return a


###############################################################################
# FONCTION nombre de relation et moyenne du nombre de voisin
###############################################################################
Esempio n. 36
0
 def protocol_version(cls):
     with GraphDatabase.driver(cls.bolt_uri, auth=cls.auth_token) as driver:
         with driver.session() as session:
             return session.run("RETURN 1").summary().protocol_version
Esempio n. 37
0
 def setUp(self):
     from neo4j import GraphDatabase
     self.driver = GraphDatabase.driver(self.bolt_routing_uri,
                                        auth=self.auth_token)
Esempio n. 38
0
#     language: python
#     name: python3
# ---

# # Building a co-author graph
#
# In this notebook we're going to build an inferred graph of co-authors based on people collaborating on the same papers. We're also going to store a property on the relationship indicating the year of their first collaboration.

# tag::imports[]
from neo4j import GraphDatabase
# end::imports[]

# +
# tag::driver[]
bolt_uri = "bolt://link-prediction-neo4j"
driver = GraphDatabase.driver(bolt_uri, auth=("neo4j", "admin"))
# end::driver[]

print(driver.address)
# -

# We can create the co-author graph by running the query below to do this:

# +
# tag::data-import[]
query = """
CALL apoc.periodic.iterate(
  "MATCH (a1)<-[:AUTHOR]-(paper)-[:AUTHOR]->(a2:Author)
   WITH a1, a2, paper
   ORDER BY a1, paper.year
   RETURN a1, a2, collect(paper)[0].year AS year, count(*) AS collaborations",
Esempio n. 39
0
'''
Program to establish connection to database
'''
import json
from neo4j import GraphDatabase
import os
'''
.env file needs to be in current director of the following format

{
"uri":"bolt://ec2-18-220-22-55.us-east-2.compute.amazonaws.com:7687",
"neo4j_user" : "test_user",
"neo4j_passw" : "test123"
}

'''

#load params
env_file_fp = open('./db_conn/.env')
params = json.load(env_file_fp)

uri = params.get('uri')
driver = GraphDatabase.driver(uri,
                              auth=(params.get('neo4j_user'),
                                    params.get('neo4j_passw')))
Esempio n. 40
0
from neo4j import GraphDatabase
import time
driver = GraphDatabase.driver('bolt://localhost:7687',
                              auth=('neo4j', '12345678'))

for tempo in range(0, 31):
    tempo_iniziale = time.clock() * 1000

    def print_friends_of(tx, name):
        for record in tx.run(
                "MATCH path=(:Person {name:'DONALD J. TRUMP'})-[:RELATED_TO*1..3]-(other:Person) WHERE  ALL(x IN NODES(path) WHERE x.name <> 'IVANKA TRUMP') WITH DISTINCT(other) as other RETURN other, EXISTS( (other)-[:RELATED_TO]-(:Person{ name:'IVANKA TRUMP' }) ) as friendOfTrump ORDER BY other.name",
                name=name):
            print(record["other"], record["friendOfTrump"])

    tempo_finale = time.clock() * 1000
    print(tempo_finale - tempo_iniziale)
with driver.session() as session:
    session.read_transaction(print_friends_of, "Trump")
 def test_bolt_uri_constructs_bolt_driver(self):
     with StubCluster("v3/empty.script"):
         uri = "bolt://127.0.0.1:9001"
         with GraphDatabase.driver(uri, auth=self.auth_token) as driver:
             assert isinstance(driver, BoltDriver)
 def _get_driver(self):
     return GraphDatabase.driver(GRAPH_DATABASE_URI,
                                 auth=basic_auth(GRAPH_DATABASE_USER,
                                                 GRAPH_DATABASE_PASSWORD))
Esempio n. 43
0
from neo4j import GraphDatabase

from tests import api_
from reddit_detective import RedditNetwork, Comments
from reddit_detective.data_models import Redditor

driver_ = GraphDatabase.driver("bolt://localhost:7687",
                               auth=("neo4j", "testing"))


def test_network():
    net = RedditNetwork(driver=driver_,
                        components=[
                            Comments(
                                Redditor(api_, "BloodMooseSquirrel", limit=5)),
                            Comments(Redditor(api_, "Anub_Rekhan", limit=5))
                        ])
    assert net
    assert net.cypher_code()
    net.run_cypher_code()


def run():
    test_network()


if __name__ == '__main__':
    run()
Esempio n. 44
0
def openDatabase(uri: str, username: str, password: str):
    driver = GraphDatabase.driver(uri, auth=basic_auth(username, password))
    session = driver.session()
    return (session, driver)
Esempio n. 45
0
 def __init__(self):
     self.__driver = GraphDatabase.driver("bolt://localhost:7687",
                                          auth=("neo4j", "1111"))
Esempio n. 46
0
# %% init
from pathlib import Path
import datetime
from py2neo import Graph, Node, Relationship
from neo4j import GraphDatabase, basic_auth
import urllib.request
from bs4 import BeautifulSoup
import glob
import random, time
import os

graph = Graph("bolt://localhost:7687", auth=("neo4j", "Password"))
driver = GraphDatabase.driver('bolt://localhost',auth=basic_auth("neo4j", "Password"))
db = driver.session()

import sys
dataPath = 'C:\\Users\\Jo\\Documents\\Tech\\Atom_prj\\MyMedia-FillDB\\data' # <<<<<< hardcoded
if dataPath not in sys.path:
    sys.path.insert(0, dataPath)
from FromNotebook import myUrlParse

ytAPI_client_secrets_file_path = "C:\\Users\\Jo\\Documents\\Tech\\Notebooks\\client_secret_1054515006139-e0p34lt262qbh4af24t2po4c5ophspjo.apps.googleusercontent.com.json"

path = "C:\\Users\\Jo\\Documents\\Tech\\ScrapData\\20200709"

def create_YT_API():

    import os
    import google_auth_oauthlib.flow
    import googleapiclient.discovery
    import googleapiclient.errors
Esempio n. 47
0
from faker import Faker
from random import randint
import uuid
from neo4j import GraphDatabase, basic_auth
from helpers import get_connection_details

graphenedb_url = get_connection_details()[0]
graphenedb_user = get_connection_details()[1]
graphenedb_pass = get_connection_details()[2]

# Create graph driver
# This is used to create a session so we can run the code while working on it.
driver = GraphDatabase.driver(graphenedb_url,
                              auth=basic_auth(graphenedb_user,
                                              graphenedb_pass))


class User:
    def __init__(self,
                 id='',
                 username='',
                 name='',
                 age='',
                 university='',
                 password=''):
        self.age = age
        self.id = id
        self.name = name
        self.password = password
        self.university = university
        self.username = username
Esempio n. 48
0
# %% Import e inicialização da conexão
from neo4j import GraphDatabase
import nxneo4j as nx
import wget, os
import pandas as pd
import numpy as np

driver = GraphDatabase.driver(uri="bolt://localhost:7687",
                              auth=("neo4j", "test"))
G = nx.Graph(driver)

# %% Primeiros testes
G.delete_all()
G.add_node(1)  #single node
G.add_nodes_from([2, 3, 4])  #multiple nodes
G.add_edge(1, 2)  #single edge
G.add_edges_from([(2, 3), (3, 4)])  #multiple edges
G.add_node('Mike', gender='M', age=17)
G.add_edge('Mike', 'Jenny', type='friends', weight=3)
nx.draw(G)

# %% Deleta os dados existentes e insere os novos dados
G.delete_all()
colaboracao = pd.read_csv('dados\collaboration.edgelist.txt',
                          delimiter='\t',
                          header=None)

lista_df = np.array_split(colaboracao, 20)

# %%
for resultado in lista_df:
Esempio n. 49
0
 def server_version_info(cls):
     with GraphDatabase.driver(cls.bolt_uri, auth=cls.auth_token) as driver:
         with driver.session() as session:
             full_version = session.run("RETURN 1").summary().server.version
             return ServerVersion.from_str(full_version)
Esempio n. 50
0
# -*- coding: utf-8 -*-
"""
Created on Fri Oct  2 15:19:46 2020

@author: sookmyung
"""

import csv, sys, time

import pandas as pd
start_time = time.time()

from neo4j import GraphDatabase

driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "wowhi223"), encrypted=False)

'''
    name : 이상우
    pid : 880514-1520414
'''

def extractCreateProps(p, d, ac):

    userNames, userIds = [], []
    dataNames, dataFilePaths, dataVals, dataOrigins = [], [], [], []
    acNames, acDates, acDetails = [], [], []
    
    for idx, val in enumerate(d):
        userNames.append(p[idx]['name'])
        userIds.append(p[idx]['pid'])
        
Esempio n. 51
0
 def __init__(self):
     # インストラクタ
     driver = GraphDatabase.driver("bolt://neo4j",
                                   auth=basic_auth("neo4j", "neo4jpw"))
     self.session = driver.session()
Esempio n. 52
0
from neo4j import GraphDatabase
from manipulator.private_settings import NEO4J_HOST, NEO4J_USER, NEO4J_PASS

_driver = GraphDatabase.driver(NEO4J_HOST, auth=(NEO4J_USER, NEO4J_PASS))

_session = _driver.session()


def get_driver():
    return _driver
Esempio n. 53
0
    parser.add_argument('-a', '--address', help='neo4j address',
                        type=str, default="bolt://127.0.0.1:7687")
    parser.add_argument('-p', '--password',
                        help='neo4j password', type=str, default="neo4j")
    parser.add_argument('-u', '--user', help='neo4j user name',
                        type=str, default="neo4j")
    parser.add_argument('-t', '--thread_num', type=int, default=4)
    args = parser.parse_args()

    time_report = {"vertex_use_time": [], "edge_use_time": [],
                   "vertex_batch_size": vertex_batch_size, "edge_batch_size": edge_batch_size}
    vertex_use_time = time_report["vertex_use_time"]
    edge_use_time = time_report["edge_use_time"]

    thread_num = args.thread_num
    driver = GraphDatabase.driver(
        args.address, auth=(args.user, args.password))
    with open(args.file) as f:
        data = json.load(f)
        print("start write")
        sessions = [driver.session() for i in range(thread_num)]
        total_start_time = time.time()
        time_report["total_start_time"] = total_start_time

        thread_vertex = []
        tag_count = len(data['vertex'])
        thread_tag_count = thread_num // tag_count
        if thread_tag_count < 1:
            raise Exception("thread_num must great tag_count")

        vertices_time = time.time()
        session_ids = 0
 def __init__(self, uri, user, password):
     self.driver = GraphDatabase.driver(uri, auth=(user, password))
Esempio n. 55
0
    if not gene_id in gene_id_to_pubmed_id:
        gene_id_to_pubmed_id[gene_id] = {}
    gene_id_to_pubmed_id[gene_id][pubmed_id] = None

    unique_pubmed_ids[pubmed_id] = None

f.close()

#pp.pprint(gene_id_to_pubmed_id)
#pp.pprint(unique_pubmed_ids)

#
# connect to Neo4j
#
driver = GraphDatabase.driver(uri, auth=(username, password))

#
# clear the way (CRUDE)
#
cmd = 'MATCH (c:NCBI_PUBMED)-[r]-() DELETE r;'
with driver.session() as session:
    session.run(cmd)
cmd = 'MATCH (c:NCBI_PUBMED) DELETE c;'
with driver.session() as session:
    session.run(cmd)

#
# load pubmed
#
pubmed_list = []
Esempio n. 56
0
def main():
    driver = GraphDatabase.driver("bolt://100.25.45.169:33374",
                                  auth=basic_auth("neo4j",
                                                  "age-driver-nomenclatures"))
    session = driver.session()
Esempio n. 57
0
 def __init__(self, uri, auth):
     self.driver = GraphDatabase.driver(uri, auth=auth)
Esempio n. 58
0
    def setup_class(cls):
        cls.creds = [{
            "type": "writer",
            "creds": {
                "host": "localhost",
                "port": "7687",
                "user": "******",
                "password": "******"
            }
        }, {
            "type": "reader",
            "creds": {
                "host": "localhost",
                "port": "7687",
                "user": "******",
                "password": "******"
            }
        }]
        data = [
            {
                'tweet_id': 1,
                'text': 'Tweet 1',
                'hydrated': 'FULL'
            },
            {
                'tweet_id': 2,
                'text': 'Tweet 2',
                'hydrated': 'FULL'
            },
            {
                'tweet_id': 3,
                'text': 'Tweet 3'
            },
            {
                'tweet_id': 4,
                'text': 'Tweet 4',
                'hydrated': 'PARTIAL'
            },
            {
                'tweet_id': 5,
                'text': 'Tweet 5',
                'hydrated': 'PARTIAL'
            },
        ]

        traversal = '''UNWIND $tweets AS t
            MERGE (tweet:Tweet {id:t.tweet_id})
                ON CREATE SET
                    tweet.text = t.text,
                    tweet.hydrated = t.hydrated
        '''
        res = list(filter(lambda c: c["type"] == 'writer', cls.creds))
        creds = res[0]["creds"]
        uri = f'bolt://{creds["host"]}:{creds["port"]}'
        graph = GraphDatabase.driver(uri,
                                     auth=basic_auth(creds['user'],
                                                     creds['password']),
                                     encrypted=False)
        try:
            with graph.session() as session:
                session.run(traversal, tweets=data)
            cls.ids = pd.DataFrame({'id': [1, 2, 3, 4, 5]})
        except Exception as err:
            print(err)

        # Now add some account data
        user_data = [
            {
                'account_id': 1,
                'hydrated': 'FULL'
            },
            {
                'account_id': 2,
                'hydrated': 'FULL'
            },
            {
                'account_id': 3
            },
            {
                'account_id': 4,
                'hydrated': 'PARTIAL'
            },
            {
                'account_id': 5,
                'hydrated': 'PARTIAL'
            },
        ]

        traversal = '''UNWIND $users AS u
            MERGE (account:Account {id:u.account_id})
                ON CREATE SET
                    account.hydrated = u.hydrated
        '''
        try:
            with graph.session() as session:
                session.run(traversal, users=user_data)
            cls.ids = pd.DataFrame({'id': [1, 2, 3, 4, 5]})
        except Exception as err:
            print(err)
Esempio n. 59
0
 def __init__(self, uri, user, password, database):
     self._driver = GraphDatabase.driver(uri,
                                         auth=(user, password),
                                         encrypted=0)
     self.__database = database
Esempio n. 60
0
from neo4j import GraphDatabase
from graphviz import Digraph

### begin config
# connection to Neo4J database
driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "1234"))

##### colors
#c81919 - dark red
#f9cccc - light red
#
#0333a3 - dark blue
#bbd1ff - light blue
#
#feb729 - yellow
#fed47f - light yellow
#
#178544 - dark green
#4ae087 - light green
#
#a034a8 - purple
#e7bdeb - light purple
#
#13857d - dark cyan
#19b1a7 - cyan
#93f0ea - light cyan

c2_cyan = "#318599"
c2_orange = "#ea700d"
c2_light_orange = "#f59d56"
c2_light_yellow = "#ffd965"