Exemple #1
0
 def tearDown(self):
     """Get rid of the database again after each test."""
     if self.rpc_client:
         self.rpc_client.transport.close()
     self.http_server.stop()
     self.http_server = None
     caliope_server.app = Flask('caliope_server')
     #:Delete database
     neo4j.GraphDatabaseService().clear()
Exemple #2
0
def test_can_set_properties_on_node_in_same_batch():
    graph_db = neo4j.GraphDatabaseService()
    batch = neo4j.WriteBatch(graph_db)
    alice = batch.create({})
    batch.set_properties(alice, {"name": "Alice", "age": 34})
    results = batch.submit()
    alice = results[batch.find(alice)]
    assert alice["name"] == "Alice"
    assert alice["age"] == 34
Exemple #3
0
def test_can_cast_rel():
    graph_db = neo4j.GraphDatabaseService()
    a, b, ab = graph_db.create({}, {}, (0, "KNOWS", 1))
    casted = rel(ab)
    assert isinstance(casted, neo4j.Relationship)
    assert not casted.is_abstract
    assert casted.start_node == a
    assert casted.type == "KNOWS"
    assert casted.end_node == b
def test_can_delete_properties_on_node_in_same_batch():
    graph_db = neo4j.GraphDatabaseService()
    batch = neo4j.WriteBatch(graph_db)
    alice = batch.create({"name": "Alice", "age": 34})
    batch.delete_properties(alice)
    results = batch.submit()
    alice = results[batch.find(alice)]
    props = alice.get_properties()
    assert props == {}
Exemple #5
0
def dbsetup(readonly=False):
    'Set up our connection to Neo4j'
    ourstore = Store(neo4j.GraphDatabaseService(),
                     uniqueindexmap={},
                     classkeymap={})
    CMAinit(None, readonly=readonly, use_network=False)
    for classname in GraphNode.classmap:
        GraphNode.initclasstypeobj(ourstore, classname)
    return ourstore
Exemple #6
0
def test_can_insert_subgraph_from_geoff_file():
    graph_db = neo4j.GraphDatabaseService()
    planets = geoff.Subgraph.load(PLANETS_GEOFF)
    assert len(planets.nodes) == 25
    assert len(planets.relationships) == 24
    assert len(planets.index_entries) == 0
    out = planets.insert_into(graph_db)
    assert len(out) == 25
    assert all(isinstance(node, neo4j.Node) for node in out.values())
Exemple #7
0
def test_can_insert_single_node():
    graph_db = neo4j.GraphDatabaseService()
    source = '(a {"name": "Alice"})'
    subgraph = geoff.Subgraph(source)
    out = subgraph.insert_into(graph_db)
    assert isinstance(out["a"], neo4j.Node)
    assert out["a"].get_properties() == {"name": "Alice"}
    matches = list(out["a"].match_outgoing())
    assert len(matches) == 0
def test_can_set_labels_on_preexisting_node():
    graph_db = neo4j.GraphDatabaseService()
    if not graph_db.supports_node_labels:
        return
    alice, = graph_db.create({"name": "Alice"})
    alice.add_labels("human", "female")
    batch = neo4j.WriteBatch(graph_db)
    batch.set_labels(alice, "mystery", "badger")
    batch.run()
    assert alice.get_labels() == {"mystery", "badger"}
Exemple #9
0
def update_info(user, path):
    tag = genId()
    id1 = genId()
    id2 = genId()
    id3 = genId()
    g = neo4j.GraphDatabaseService()
    s = "CREATE (p:Photo {path:" "'" + path + "'" ",tag:" "'" + tag + "'" ",id1:" "'" + id1 + "'" ",id2:" "'" + id2 + "'" ",id3:" "'" + id3 + "'" "})"
    cypher.execute(g, s)
    t = "MATCH (n),(p) WHERE n.name= " "'" + user + "'" " AND p.path= " "'" + path + "'" " CREATE (n)-[:UPLOADS]->(p)"
    cypher.execute(g, t)
Exemple #10
0
def test_can_use_return_values_as_references():
    batch = neo4j.WriteBatch(neo4j.GraphDatabaseService())
    a = batch.create(node(name="Alice"))
    b = batch.create(node(name="Bob"))
    batch.create(rel(a, "KNOWS", b))
    results = batch.submit()
    ab = results[2]
    assert isinstance(ab, neo4j.Relationship)
    assert ab.start_node["name"] == "Alice"
    assert ab.end_node["name"] == "Bob"
Exemple #11
0
def test_can_create_path_with_new_nodes():
    graph_db = neo4j.GraphDatabaseService()
    batch = neo4j.WriteBatch(graph_db)
    batch.create_path({"name": "Alice"}, "KNOWS", {"name": "Bob"})
    results = batch.submit()
    path = results[0]
    assert len(path) == 1
    assert path.nodes[0]["name"] == "Alice"
    assert path.relationships[0].type == "KNOWS"
    assert path.nodes[1]["name"] == "Bob"
Exemple #12
0
def test_many_queries():
    graph_db = neo4j.GraphDatabaseService()
    node, = graph_db.create({})
    query = "START z=node({0}) RETURN z".format(node._id)
    for i in range(40):
        with neo4j.CypherQuery(graph_db, query).execute() as records:
            for record in records:
                assert record.columns == ("z", )
                assert record.values == (node, )
    graph_db.delete(node)
def get_all_relationships():
    # returns ALL of the possible relationship types in the graph
    graph_db = neo4j.GraphDatabaseService(NEO4J_SERVER_ADDRESS)
    # get the relationship types from the database
    s = [str(x) for x in graph_db.relationship_types]
    # sort them alphabetically
    s.sort()
    # maybe not necessary?
    graph_db = None
    return s
Exemple #14
0
def test_cannot_add_labels_to_abstract_nodes():
    graph_db = neo4j.GraphDatabaseService()
    if not graph_db.supports_node_labels:
        return
    alice = node(name="Alice")
    try:
        alice.add_labels("human", "female")
    except TypeError:
        assert True
    else:
        assert False
Exemple #15
0
def test_can_insert_subgraph_from_xml_file():
    graph_db = neo4j.GraphDatabaseService()
    planets = geoff.Subgraph.load_xml(PLANETS_XML)
    if sys.version_info >= (2, 7):
        assert planets.source == PLANETS_GEOFF.getvalue()
    assert len(planets.nodes) == 25
    assert len(planets.relationships) == 24
    assert len(planets.index_entries) == 0
    out = planets.insert_into(graph_db)
    assert len(out) == 25
    assert all(isinstance(node, neo4j.Node) for node in out.values())
Exemple #16
0
def hello_cypher():
    graph_db = neo4j.GraphDatabaseService()
    query_str = """\
    match (n:User)-[:FOLLOWS]->(m:User)
    where n.screenName = {screenName}
    return m.screenName as friend
    order by friend
    """
    query = neo4j.CypherQuery(graph_db, query_str)
    results = query.execute(screenName="wefreema")
    return [result.friend for result in results]
def login():
    form = LoginForm()
    global db_client
    app.graph_db = neo4j.GraphDatabaseService("http://localhost:7474/db/data/")
    user_data, user_metadata = cypher.execute(app.graph_db, "MATCH (n:USER {{ id : {0}}}) RETURN (n)".format(int(form.id.data)))

    if user_data[0][0]['id']:
        session['user'] = int(form.id.data)
        return redirect('/')
    else:
        return redirect('/')
Exemple #18
0
def like_connection(id, user, remove=False):
    """
    Find the restaurant node from 'id' and find user node from 'user' and create the new relationship
    """
    graph_db = neo4j.GraphDatabaseService()
    restaurant = graph_db.find("Restaurant", "_id", id).next()
    user_node = get_current_user_node(user, graph_db)
    path = user_node.get_or_create_path("LIKES", restaurant)

    if remove:
        path.relationships[0].delete()
def test_can_get_or_create_path_with_existing_nodes():
    graph_db = neo4j.GraphDatabaseService()
    alice, bob = graph_db.create({"name": "Alice"}, {"name": "Bob"})
    batch = neo4j.WriteBatch(graph_db)
    batch.get_or_create_path(alice, "KNOWS", bob)
    results = batch.submit()
    path = results[0]
    assert len(path) == 1
    assert path.nodes[0] == alice
    assert path.relationships[0].type == "KNOWS"
    assert path.nodes[1] == bob
Exemple #20
0
    def new_session(self):
        try:
            self.session = neo4j.GraphDatabaseService(self.url)
        except SocketError as e:
            raise SocketError("Error connecting to {0} - {1}".format(self.url, e))

        if self.session.neo4j_version < (2, 0):
            raise Exception("Support for neo4j versions prior to 2.0 are "
                    + "supported by the 0.x.x series releases of neomodel")

        if hasattr(self, 'tx_session'):
            delattr(self, 'tx_session')
Exemple #21
0
def test_can_merge_simple_graph():
    graph_db = neo4j.GraphDatabaseService()
    source = '(a {"name": "Alice"}) (b {"name": "Bob"}) (a)-[:KNOWS]->(b)'
    subgraph = geoff.Subgraph(source)
    out = subgraph.merge_into(graph_db)
    assert isinstance(out["a"], neo4j.Node)
    assert isinstance(out["b"], neo4j.Node)
    assert out["a"].get_properties() == {"name": "Alice"}
    assert out["b"].get_properties() == {"name": "Bob"}
    matches = list(out["a"].match_outgoing(end_node=out["b"]))
    assert len(matches) == 1
    assert matches[0].type == "KNOWS"
Exemple #22
0
def createMatrix():
    g = neo4j.GraphDatabaseService()
    s = "MATCH (a)-[k:KNOWS]-(b) RETURN a.name,k.heavy,b.name"
    gr = nx.Graph()
    b = cypher.execute(g, s)[0]
    for i in b:
        if i[1] == None:
            gr.add_edge(str(i[0]), str(i[2]), weight=0)
        else:
            gr.add_edge(str(i[0]), str(i[2]), weight=float(i[1]))
    a = nx.to_numpy_matrix(gr)
    return a
def test_can_set_labels_on_node():
    graph_db = neo4j.GraphDatabaseService()
    if not graph_db.supports_node_labels:
        return
    alice, = graph_db.create(node(name="Alice"))
    alice.add_labels("human", "female")
    labels = alice.get_labels()
    assert len(labels) == 2
    assert labels == set(["human", "female"])
    alice.set_labels("mystery", "badger")
    labels = alice.get_labels()
    assert labels == set(["mystery", "badger"])
    assert labels != set(["human", "female"])
Exemple #24
0
def test_can_query_node_index():
    graph_db = neo4j.GraphDatabaseService()
    graph_db.clear()
    people = graph_db.get_or_create_index(neo4j.Node, "people")
    a = people.create("name", "Alice", {"name": "Alice"})
    b = people.create("name", "Bob", {"name": "Bob"})
    c = people.create("name", "Carol", {"name": "Carol"})
    d = people.create("name", "Dave", {"name": "Dave"})
    e = people.create("name", "Eve", {"name": "Eve"})
    f = people.create("name", "Frank", {"name": "Frank"})
    for person in people.query("name:*a*"):
        print(person)
        assert person in (c, d, f)
Exemple #25
0
def func(tag, user, rate):
    g = neo4j.GraphDatabaseService()
    a = check_rate.func(tag)
    if user in a:
        print "Already Rated"
        exit()
    s = "MATCH (n),(b:People) WHERE n.tag= " "'" + tag + "'" " AND b.name= " "'" + user + "'" " CREATE (b)-[:RATES {rate:" + str(
        rate) + "}]->(n)"
    if (cypher.execute(g, s)):
        a = check_rate.func(tag)
        print str(len(a))
    else:
        print "No"
def main(graph_db):
    '''
    spouštím funkci main()
    '''
    

    graph_db = neo4j.GraphDatabaseService(neo4j.DEFAULT_URI)
    print(graph_db.neo4j_version)
    graph_db.clear()
    
    # create a single node
    alice, = graph_db.create({"name": "Alice"})
    print(alice)
Exemple #27
0
 def test_can_create_path(self):
     graph_db = neo4j.GraphDatabaseService()
     path = neo4j.Path({"name": "Alice"}, "KNOWS", {"name": "Bob"})
     assert path.nodes[0] == {"name": "Alice"}
     assert path._relationships[0]._type == "KNOWS"
     assert path.nodes[1] == {"name": "Bob"}
     path = path.create(graph_db)
     assert isinstance(path.nodes[0], neo4j.Node)
     assert path.nodes[0]["name"] == "Alice"
     assert isinstance(path.relationships[0], neo4j.Relationship)
     assert path._relationships[0]._type == "KNOWS"
     assert isinstance(path.nodes[1], neo4j.Node)
     assert path.nodes[1]["name"] == "Bob"
Exemple #28
0
 def _send_big_batch(self, node_count):
     graph_db = neo4j.GraphDatabaseService()
     graph_db.clear()
     print("creating batch of " + str(node_count))
     batch = neo4j.WriteBatch(graph_db)
     for i in range(node_count):
         batch.create_node({"number": i})
     print("submitting batch")
     nodes = batch.submit()
     print("checking batch")
     for node in nodes:
         assert isinstance(node, neo4j.Node)
     print("done")
Exemple #29
0
def numberOfEdges(a):
    g = neo4j.GraphDatabaseService()
    for i in a:
        s = "MATCH (a)<-[w:WRITES|UPLOADS]-(n)-[k:KNOWS]-(b) WHERE a.tag= " "'" + i + "'" " RETURN n.name,k.bond,b.name"
        b = cypher.execute(g, s)[0]
        for j in b:
            l = len(b)
            h = j[1] / float(l)
            t = "MATCH (a)-[k:KNOWS]-(b) WHERE a.name= " "'" + j[
                0] + "'" " AND b.name= " "'" + j[
                    2] + "'" " SET k.heavy=" "'" + str(h) + "'"
            cypher.execute(g, t)
            print j
Exemple #30
0
def returnCommitInformation(project, commit):
	try:
		gdb = neo4j.GraphDatabaseService(settings.NEO4J_SERVER)
	except socket.error:
		print "Unable to connect to Neo4j: ", settings.NEO4J_SERVER
		return None

	q = "START a=node(*) where has(a.hash) return max(a.total_delta) as maximum;"
	result = neo4j.CypherQuery(gdb, q) #TODO: switch this so it's only a single return (so we don't have to go through the for loop)
	for r in result.stream():
		maximum = r['maximum']

	commit_info = None

	q = "START a=node(*) match a-[:impact]->() where a.hash = '"+commit+"' return distinct a;"
	result = neo4j.CypherQuery(gdb, q)
	for r in result.stream(): #TODO: switch this so it's only a single return (so we don't have to go through the for loop)
		converted_date = time.strftime('%Y/%m/%d', time.localtime(int(r.a['date'])))
		if r.a['total_delta'] == 0:
			impact_msg = "No technical change"
		elif r.a['total_delta'] < (maximum * 0.25):
			impact_msg = "Minimal technical change"
		elif r.a['total_delta'] < (maximum * 0.5):
			impact_msg = "Low technical change"
		elif r.a['total_delta'] < (maximum * 0.75):
			impact_msg = "Moderate technical change"
		else:
			impact_msg = "Substantial technical change."
		commit_info = CodeImpact(commit_hash=r.a['hash'], date=converted_date, delta_impact=round(r.a['total_delta'], 3), delta_impact_msg=impact_msg, logmsg=r.a['logmsg'], author_developer=r.a['author_developer'], author_email=r.a['author_email'])

	#if we don't have an :impact edge, we still need to populate the commit_info variable
	if not commit_info:
		q = "START a=node(*) where a.hash = '"+commit+"' return a;"
		result = neo4j.CypherQuery(gdb, q)
		for res in result.stream(): #TODO: switch this so it's only a single return (so we don't have to go through the for loop)
			converted_date = time.strftime('%Y/%m/%d', time.localtime(int(res.a['date'])))
			commit_info = CodeImpact(commit_hash=res.a['hash'], date=converted_date, delta_impact=0, delta_impact_msg="No technical change", logmsg=res.a['logmsg'], author_developer=res.a['author_developer'], author_email=res.a['author_email'])


	code_impact = []

	q = "START a=node(*) match a-[r:impact]->b where a.hash = '"+commit+"' optional match b<-[:has]-c return r, b, c order by r.impactvalue desc limit 10;"
	result = neo4j.CypherQuery(gdb, q)
	for r in result.stream():
		if r.c is not None:
			code_impact.append(CodeImpactFiles(code_impact=round(r.r['impactvalue'], 3), filename=r.b['filename'], function=r.b['function'], functionfilename=r.c['filename']))
		else:
			code_impact.append(CodeImpactFiles(code_impact=round(r.r['impactvalue'], 3), filename=r.b['filename'], function=r.b['function'], functionfilename=None))

	return commit_info, code_impact