예제 #1
0
def create_node(node):
    graph = neo4j_connect()
    transaction = graph.begin()
    node_find = find_node(node.get("labels"), node.get("name"))
    # print(node_find)
    if node_find in ('', None):
        nodes = NodeObject(node.get("labels"))
        nodes.name = node.get("name")
        nodes.full_name = node.get("full_name")
        # if full_name == '':
        #     full_name = ''
        nodes.image = node.get("image")
        # if image == '':
        #     image = ''
        nodes.object_id = node.get("object_id")
        # if object_id == 0:
        #     object_id = ''
        nodes.weight = node.get("weight")
        # if weight == 0:
        #     weight = ''
        nodes.keywords = node.get("keywords")
        # if keywords == '':
        #     keywords = ''
        type1 = node.get("type")
        nodes.date_time = node.get("date_time")
        # if date_time == '':
        #     date_time = ''
        # node_temp = Node(labels, name=name, full_name=full_name, image=image, object_id=object_id,
        #             weight=weight, keywords=keywords, date_time=date_time)
        # node_temp.__primarylabel__ = labels
        # node_temp.__primarykey__ = name
        graph = neo4j_connect()
        transaction = graph.begin()
        # transaction.merge(node_temp, labels, "name", name)
        graph.create(nodes)
        graph.push(nodes)
    else:
        return ("Node đã tồn tại")
    if type1 not in ('', None):
        event_type = Node("event_category", name=type1)
        event_type.__primarylabel__ = "event_category"
        event_type.__primarykey__ = type
        transaction.create(event_type)
        rels_event = Relationship(nodes.__node__,
                                  "Belong to the type of event", event_type)
        transaction.create(rels_event)
        #Create rels event category

    transaction.commit()
    transaction.finished()
    cypher = """MATCH path = (n:`{labels}`)-[]-() where n.name = '{name}' """.format(
        labels=nodes.__primarylabel__, name=nodes.name)
    result = export_json_run_cypher(cypher)
    return result
예제 #2
0
def create_node(node):
    node_find = f"""Match (n:{node.get("labels")}) where n.name='{node.get("name")}'"""
    graph = neo4j_connect()
    if (graph.run(f"{node_find} return r").data() not in ([], None)):
        return ("Nodes already exists")
    else:
        create_query = ""
        for x in node:
            if x != "labels":
                if isinstance(node.get(x), (int, float)) == True:
                    create_query += f"{x}:{node.get(x)},"
                else:
                    if valid_date(node.get(x)) == True:
                        create_query += f"""{x}:date("{node.get(x)}"),"""
                    else:
                        create_query += f"{x}:'{node.get(x)}',"

        create_query = create_query.rstrip(",")
        print(create_query)
        pattern = f"""CREATE (n:{node.get("labels")}{{{create_query}}}) return n"""
        print(pattern)
        graph.run(pattern)
        return export_json_node(
            f"""Match (n:{node.get("labels")}) where n.name='{node.get("name")}'"""
        )
예제 #3
0
def delete_event(key):
    graph = neo4j_connect()
    event = graph.nodes.match("Event").where(
        "_.name = '{name}'".format(name=key)).first()
    graph.delete(event)
    graph.exists(event)
    return ("Success")
예제 #4
0
def delete_country(key):
    graph = neo4j_connect()
    country = graph.nodes.match("Country").where("_.name = '{name}'".format(name=key)).first()
    graph.delete(country)
    graph.exists(country)
    # graph.push(country)
    return ("Success")
예제 #5
0
def update_event(events, key):
    event = NodeObject("Event")
    event.name = key
    event.full_name = events.get("full_name")
    print(event.full_name)
    event.image = events.get("image")
    event.object_id = events.get("object_id")
    event.weight = events.get("weight")
    type1 = events.get("type")
    event.location = events.get("location")
    event.keywords = events.get("keywords")
    # print(event.keywords)
    graph = neo4j_connect()
    graph.nodes.match("Event")
    graph.merge(event)
    graph.push(event)
    graph.run(
        "MATCH(n:Event)-[r]->(p:Event_Category) detach delete r, p return p")
    if type1 not in ('', None):
        transaction = graph.begin()
        event_type = Node("event_category", name=type1)
        event_type.__primarylabel__ = "Event_Category"
        event_type.__primarykey__ = type1
        transaction.create(event_type)
        rels_event = Relationship(event.__node__, "BELONG TYPE OF EVENT",
                                  event_type)
        transaction.create(rels_event)
        transaction.commit()
        transaction.finished()

    return event.__node__
예제 #6
0
def update_node(node):
    node_find = f"""Match (n:{node.get("labels")}) where n.name='{node.get("name")}'"""
    graph = neo4j_connect()
    if (graph.run(f"{node_find} return n").data() in ([], None)):
        return ("Nodes is not found")
    else:
        create_query = ""
        for x in node:
            if x != "labels" and x != "name":
                if node.get(x) == "":
                    create_query += f"{x}:null,"
                elif isinstance(node.get(x), (int, float)) == True:
                    create_query += f"{x}:{node.get(x)},"
                else:
                    if valid_date(node.get(x)) == True:
                        create_query += f"""{x}:date("{node.get(x)}"),"""
                    else:
                        create_query += f"{x}:'{node.get(x)}',"

        create_query = create_query.rstrip(",")
        print(create_query)
        pattern = f"""MATCH (n:{node.get("labels")}) set n+={{{create_query}}} return n"""
        print(pattern)
        graph.run(pattern)
        return export_json_node(
            f"""Match (n:{node.get("labels")}) where n.name='{node.get("name")}'"""
        )
예제 #7
0
def delete_node(node1):
    graph = neo4j_connect()
    node_temp = graph.nodes.match(f"""{node1.get("labels")}""").where(
        "_.name = '{name}'".format(name=node1.get("name"))).first()
    graph.delete(node_temp)
    graph.exists(node_temp)
    return ("Success")
def delete_internaltional_group(key):
    graph = neo4j_connect()
    internaltional_group = graph.nodes.match("Internaltional_Group").where(
        "_.name = '{name}'".format(name=key)).first()
    graph.delete(internaltional_group)
    graph.exists(internaltional_group)
    # graph.push(internaltional_group)
    return ("Success")
예제 #9
0
def delete_party(key):
    graph = neo4j_connect()
    party = graph.nodes.match("Party").where(
        "_.name = '{name}'".format(name=key)).first()
    graph.delete(party)
    graph.exists(party)
    # graph.push(party)
    return ("Success")
예제 #10
0
def delete_personel_group(key):
    graph = neo4j_connect()
    personel_group = graph.nodes.match("Personel_Group").where(
        "_.name = '{name}'".format(name=key)).first()
    graph.delete(personel_group)
    graph.exists(personel_group)
    # graph.push(personel_group)
    return ("Success")
예제 #11
0
def delete_node(node):
    labels = node.get("labels")
    name = node.get("name")
    graph = neo4j_connect()
    cypher = """match(n:`{labels}`)-[r]-(p) where n.name = '{name}' detach delete n, r, p""".format(
        labels=labels, name=name)
    graph.run(cypher)
    return ("Success")
예제 #12
0
def find_node(labels, name):
    if labels in (None, '') or name in (None, ''):
        return None
    graph = neo4j_connect()
    node = graph.nodes.match(labels, name=name).first()
    # matcher = NodeMatcher(graph)
    # node = matcher.match(labels, name = name).first()
    #graph.exists(node)
    return node
예제 #13
0
def create_event(events):
    # print(object)
    # event = NodeObject("event")
    name = events.get('name')
    full_name = events.get("full_name")
    image = events.get("image")
    object_id = events.get("object_id")
    weight = events.get("weight")
    type1 = events.get("type")
    location = events.get("location")
    date_time = events.get("date_time")
    keywords = events.get("keywords")
    graph = neo4j_connect()
    event_find = graph.nodes.match("Event", name=name).first()
    if event_find not in ('', None):
        return ("Event da ton tai")
    pattern = """ Create(m:Event{{name:'{name}', full_name:'{full_name}', image:'{image}', object_id:{object_id}, weight:{weight}, location:'{location}', date_time: datetime("{date_time}"), keywords:'{keywords}'}}) return m"""
    pattern = pattern.format(name=name,
                             full_name=full_name,
                             image=image,
                             object_id=object_id,
                             weight=weight,
                             location=location,
                             date_time=date_time,
                             keywords=keywords)
    print(pattern)
    graph.run(pattern)
    event = graph.nodes.match("Event", name=name).first()
    print(event)
    transaction = graph.begin()
    if type1 not in ('', None):
        event_type = Node("Event_Category", name=type1)
        event_type.__primarylabel__ = "Event_Category"
        event_type.__primarykey__ = type
        transaction.create(event_type)
        rels_event = Relationship(event, "BELONG TYPE OF EVENT", event_type)
        transaction.create(rels_event)
        #Create rels event category
    object = events.get("object")
    if len(object) not in ('', None):
        for x in object.split(","):
            if x not in ('', None):
                object_find = graph.nodes.match(name=x.strip()).first()
                transaction.create(
                    Relationship(object_find, events.get("object_rels"),
                                 event))

    transaction.commit()
    transaction.finished()
    return event
예제 #14
0
def create_continent(continents):
    continent = NodeObject("Continent")
    continent.name = continents.get('name')
    print(continent.name)
    continent.full_name = continents.get("full_name")
    print(continent.full_name)
    continent.image = continents.get("image")
    continent.object_id = continents.get("object_id")
    continent.weight = continents.get("weight")
    continent.keywords = continents.get("keywords")
    # print(continent.keywords)
    graph = neo4j_connect()
    graph.create(continent)
    graph.push(continent)
    return continent.__node__
예제 #15
0
def update_country(countrys, key):
    country = NodeObject("Country")
    country.name = key
    print(country.name)
    country.full_name = countrys.get("full_name")
    print(country.full_name)
    country.image = countrys.get("image")
    country.object_id = countrys.get("object_id")
    country.weight = countrys.get("weight")
    country.keywords = countrys.get("keywords")
    graph = neo4j_connect()
    graph.nodes.match("Country")
    graph.merge(country)
    graph.push(country)
    return country.__node__
def create_internaltional_group(internaltional_groups):
    internaltional_group = NodeObject("Internaltional_Group")
    internaltional_group.name = internaltional_groups.get('name')
    print(internaltional_group.name)
    internaltional_group.full_name = internaltional_groups.get("full_name")
    print(internaltional_group.full_name)
    internaltional_group.image = internaltional_groups.get("image")
    internaltional_group.object_id = internaltional_groups.get("object_id")
    internaltional_group.weight = internaltional_groups.get("weight")
    internaltional_group.keywords = internaltional_groups.get("keywords")
    # print(internaltional_group.keywords)
    graph = neo4j_connect()
    graph.create(internaltional_group)
    graph.push(internaltional_group)
    return internaltional_group.__node__
예제 #17
0
def update_continent(continents, key):
    continent = NodeObject("Continent")
    continent.name = key
    print(continent.name)
    continent.full_name = continents.get("full_name")
    print(continent.full_name)
    continent.image = continents.get("image")
    continent.object_id = continents.get("object_id")
    continent.weight = continents.get("weight")
    continent.keywords = continents.get("keywords")
    graph = neo4j_connect()
    graph.nodes.match("Continent")
    graph.merge(continent)
    graph.push(continent)
    return continent.__node__
예제 #18
0
def create_personel_group(personel_groups):
    personel_group = NodeObject("Personel_Group")
    personel_group.name = personel_groups.get('name')
    print(personel_group.name)
    personel_group.full_name = personel_groups.get("full_name")
    print(personel_group.full_name)
    personel_group.image = personel_groups.get("image")
    personel_group.object_id = personel_groups.get("object_id")
    personel_group.weight = personel_groups.get("weight")
    personel_group.keywords = personel_groups.get("keywords")
    # print(personel_group.keywords)
    graph = neo4j_connect()
    graph.create(personel_group)
    graph.push(personel_group)
    return personel_group.__node__
예제 #19
0
def create_country(countrys):
    country = NodeObject("Country")
    country.name = countrys.get('name')
    print(country.name)
    country.full_name = countrys.get("full_name")
    print(country.full_name)
    country.image = countrys.get("image")
    country.object_id = countrys.get("object_id")
    country.weight = countrys.get("weight")
    country.keywords = countrys.get("keywords")
    print(countrys.get("keywords"))
    graph = neo4j_connect()
    graph.create(country)
    graph.push(country)
    return country.__node__
예제 #20
0
def create_party(partys):
    party = NodeObject("Party")
    party.name = partys.get('name')
    print(party.name)
    party.full_name = partys.get("full_name")
    print(party.full_name)
    party.image = partys.get("image")
    party.object_id = partys.get("object_id")
    party.weight = partys.get("weight")
    party.keywords = party.get("keywords")
    # print(party.keywords)
    graph = neo4j_connect()
    graph.create(party)
    graph.push(party)
    return party.__node__
예제 #21
0
def update_personel_group(personel_groups, key):
    personel_group = NodeObject("Personel_Group")
    personel_group.name = key
    print(personel_group.name)
    personel_group.full_name = personel_groups.get("full_name")
    print(personel_group.full_name)
    personel_group.image = personel_groups.get("image")
    personel_group.object_id = personel_groups.get("object_id")
    personel_group.weight = personel_groups.get("weight")
    personel_group.keywords = personel_groups.get("keywords")
    # print(personel_group.keywords)
    graph = neo4j_connect()
    graph.nodes.match("Personel_Group")
    graph.merge(personel_group)
    graph.push(personel_group)
    return personel_group.__node__
예제 #22
0
def update_party(partys, key):
    party = NodeObject("Party")
    party.name = key
    print(party.name)
    party.full_name = partys.get("full_name")
    print(party.full_name)
    party.image = partys.get("image")
    party.object_id = partys.get("object_id")
    party.weight = partys.get("weight")
    party.keywords = partys.get("keywords")
    # print(party.keywords)
    graph = neo4j_connect()
    graph.nodes.match("Party")
    graph.merge(party)
    graph.push(party)
    return party.__node__
예제 #23
0
def create_person(persons):
    person = NodeObject("Person")
    person.name = persons.get('name')
    print(person.name)
    person.full_name = persons.get("full_name")
    print(person.full_name)
    person.image = persons.get("image")
    person.object_id = persons.get("object_id")
    person.weight = persons.get("weight")
    person.type = persons.get("type")
    person.keywords = persons.get("keywords")
    # print(person.keywords)
    graph = neo4j_connect()
    graph.create(person)
    graph.push(person)
    return person.__node__
def update_internaltional_group(internaltional_groups, key):
    internaltional_group = NodeObject("Internaltional_Group")
    internaltional_group.name = key
    print(internaltional_group.name)
    internaltional_group.full_name = internaltional_groups.get("full_name")
    print(internaltional_group.full_name)
    internaltional_group.image = internaltional_groups.get("image")
    internaltional_group.object_id = internaltional_groups.get("object_id")
    internaltional_group.weight = internaltional_groups.get("weight")
    internaltional_group.keywords = internaltional_groups.get("keywords")
    # print(internaltional_group.keywords)
    graph = neo4j_connect()
    graph.nodes.match("Internaltional_Group")
    graph.merge(internaltional_group)
    graph.push(internaltional_group)
    return internaltional_group.__node__
예제 #25
0
def export_json_node(sql):
    #sql = '''MATCH path = (n:country)-[r:`Đồng minh`]->(p:country) return n ,r, p'''
    query = """CALL apoc.export.json.query("%s RETURN n as nodes","nodej.json",{})""" % (
        sql)
    json_load = """WITH "nodej.json" AS url CALL apoc.load.json(url) YIELD value return value.nodes as node"""
    try:
        graph = neo4j_connect()
        print(query)
        if (graph.run(f"{sql} return n").data() not in ([], None)):
            graph.run(query)
            query_json = graph.run(json_load).to_data_frame()
            result = query_json.to_dict(orient='records')
            return result
        else:
            return ("Not Found")
    except:
        return ("Not Found")
예제 #26
0
def update_relationship(rels):
    graph = neo4j_connect()
    create_query = ""
    relationship_properties = rels.get("Relationship")
    list_node = []
    for y in rels:
        if y != "Relationship":
            list_node.append(y)
    if relationship_properties.get("name") in ('', None):
        relation_find = f"""MATCH (a:{list_node[0]})-[r:`{relationship_properties.get("type")}`]->(b:{list_node[1]}) WHERE a.name = '{rels.get(list_node[0]).get("name")}' AND b.name = '{rels.get(list_node[1]).get("name")}'"""
    else:
        relation_find = f"""MATCH (a:{list_node[0]})-[r:`{relationship_properties.get("type")}`]->(b:{list_node[1]}) WHERE a.name = '{rels.get(list_node[0]).get("name")}' AND b.name = '{rels.get(list_node[1]).get("name")}' AND r.name = '{relationship_properties.get("name")}'"""
    print(relation_find)
    if (graph.run(f"{relation_find} return r").data() in ([], None)):
        return ("relationship already exists")
    else:
        for x in relationship_properties:
            if x != "type":
                if isinstance(relationship_properties.get(x),
                              (int, float)) == True:
                    create_query += f"{x}:{relationship_properties.get(x)},"
                else:
                    if valid_date(relationship_properties.get(x)) == True:
                        create_query += f"""{x}:date("{relationship_properties.get(x)}"),"""
                    else:
                        create_query += f"{x}:'{relationship_properties.get(x)}',"

        create_query = create_query.rstrip(",")
        # list_node =[]
        # for y in rels:
        #     if y!= "Relationship":
        #         list_node.append(y)
        if relationship_properties.get("name") in ('', None):
            pattern = f"""MATCH (a:{list_node[0]})-[r:`{relationship_properties.get("type")}`]-(b:{list_node[1]}) WHERE a.name = '{rels.get(list_node[0]).get("name")}' AND b.name = '{rels.get(list_node[1]).get("name")}' set r+={{{create_query}}} return a, b, r"""
        else:
            pattern = f"""MATCH (a:{list_node[0]})-[r:`{relationship_properties.get("type")}`]-(b:{list_node[1]}) WHERE a.name = '{rels.get(list_node[0]).get("name")}' AND b.name = '{rels.get(list_node[1]).get("name")}' AND r.name = '{relationship_properties.get("name")}' set r+={{{create_query}}} return a, b, r"""
        print(create_query)
        print(pattern)
        print(graph.run(pattern))
        if relationship_properties.get("name") in ('', None):
            pattern_find = f"""MATCH (a:{list_node[0]})-[r:`{relationship_properties.get("type")}`]->(b:{list_node[1]}) WHERE a.name = '{rels.get(list_node[0]).get("name")}' AND b.name = '{rels.get(list_node[1]).get("name")}'"""
        else:
            pattern_find = f"""MATCH (a:{list_node[0]})-[r:`{relationship_properties.get("type")}`]->(b:{list_node[1]}) WHERE a.name = '{rels.get(list_node[0]).get("name")}' AND b.name = '{rels.get(list_node[1]).get("name")}' AND r.name = '{relationship_properties.get("name")}'"""
        print(pattern_find)
        return export_json_relationship(pattern_find)
예제 #27
0
def delete_relationship(rels):
    graph = neo4j_connect()
    if graph.run(
            f"""MATCH (a)-[r:`{rels.get("type")}`]-(b) where r.name='{rels.get("name")}' return r"""
    ).data() == []:
        return ("No Relationship")
    else:
        rels_temp = f"""MATCH (a)-[r:`{rels.get("type")}`]-(b) where r.name='{rels.get("name")}' detach delete r"""
        rels_find = f"""MATCH (a)-[r:`{rels.get("type")}`]-(b) where r.name='{rels.get("name")}' return r"""
        graph.run(rels_temp)
        print(rels_temp)
        result = graph.run(rels_find).data()
        print(result)
        if result != []:
            return ("Delete Fail")
        else:
            return ("Delete Success")
        return ("Success")
예제 #28
0
def export_json_run_cypher(sql):
    #sql = '''MATCH path = (n:country)-[r:`Đồng minh`]->(p:country) return n ,r, p'''
    query = """CALL apoc.export.json.query("%s with nodes(path) as nodes, relationships(path)
                       as rels unwind nodes as nodes1 unwind rels as rels1 with nodes1, rels1 RETURN
                       collect(distinct nodes1) as nodes, collect(distinct rels1) as relationships","query.json",{})""" % (
        sql)
    json_load = """WITH "query.json" AS url CALL apoc.load.json(url) YIELD value return value.nodes as node, value.relationships as relationships"""
    try:
        graph = neo4j_connect()
        print(query)
        if (graph.run(f"{sql} return path").data() not in ([], None)):
            graph.run(query)
            query_json = graph.run(json_load).to_data_frame()
            result = query_json.to_dict(orient='records')
            return result
        else:
            return ("Not Found")
    except:
        return ("Not Found")
예제 #29
0
def export_one_object_same_event(list_label, list_object, list_rel,
                                 list_name_event, limit, conditions, follow):
    # # SQL Select
    test1 = ""
    for x in range(len(list_object)):
        if x == 0:
            test1 += "n.name =~ '.*" + list_object[x] + ".*'"
        else:
            test1 += " or n.name =~ '.*" + list_object[x] + ".*'"
    test2 = ""
    for x in range(len(list_name_event)):
        if x == 0:
            test2 += "p.name =~ '.*" + list_name_event[x] + ".*'"
        else:
            test2 += " or p.name =~ '.*" + list_name_event[x] + ".*'"
    test3 = ""
    for x in range(len(list_label)):
        if x == 0:
            test3 += "n:" + list_label[x]
        else:
            test3 += " or n:" + list_label[x]
    cypher = f"""Match (n)-[r]-(p:Event) where ({test3}) and (type(r) in {list_rel}) and ({test1}) and ({test2})"""
    if len(conditions) != 0:
        cypher += f""" and (datetime(p.date_time) >= datetime('{conditions.get("from_date")}') and datetime(p.date_time) <= datetime('{conditions.get("to_date")}'))"""
    if follow == 1:
        cypher += f""" call apoc.path.subgraphAll(n, {{maxLevel:{limit}}}) yield nodes, relationships return collect(distinct nodes) as node, collect(distinct relationships) as relationship"""
    else:
        cypher += f""" call apoc.path.subgraphAll(p, {{maxLevel:{limit}}}) yield nodes, relationships return collect(distinct nodes) as node, collect(distinct relationships) as relationship"""
    pattern = f"""CALL apoc.export.json.query("{cypher}","query.json",{{}})"""
    json_load = """WITH 'query.json' AS url CALL apoc.load.json(url) YIELD value return value.node as nodes, value.relationship as relationships"""
    try:
        graph = neo4j_connect()
        graph.run(pattern)
        query_json = graph.run(json_load).to_data_frame()
        result = query_json.to_dict(orient='records')
        print(pattern)
        return result, 200
    except:
        return ("Not Found"), 201
예제 #30
0
def find_personel_group_with_key(key):
    graph = neo4j_connect()
    personel_group = graph.nodes.match("Personel_Group").where(
        "_.name = '{name}'".format(name=key)).first()
    graph.exists(personel_group)
    return personel_group