コード例 #1
0
def clean_database():

    # with neo4j.BatchTransaction() as tx:
    statements = [
        'MATCH (n)', 'WITH n', 'LIMIT {limit}', 'OPTIONAL MATCH (n)-[r]-(x)',
        'DELETE r, n'
    ]

    query = neo4j.Query('\n'.join(statements),
                        [neo4j.Parameter('limit', 10000)])

    tx = neo4j.Transaction()
    while tx.execute(query):
        tx = neo4j.Transaction()

    tx.execute(query)
    tx.commit()

    statements = ['MATCH (n)', 'WITH n', 'LIMIT {limit}', 'DELETE n']

    query = neo4j.Query('\n'.join(statements),
                        [neo4j.Parameter('limit', 10000)])

    tx = neo4j.Transaction()
    while tx.execute(query):
        tx = neo4j.Transaction()
    tx.commit()
コード例 #2
0
def one():

    # find the top 20 people that took more than 1 flight between Jan & Jun 2014, to any destination.
    # Order results by number of flights to each country

    msg = PATTERNS[1]

    print(msg)

    statements = [
        'MATCH (person :`Person`)-[:TOOK]->(flight :`Flight`)-[:TO]-(:`City`)-[:IN]->(country :`Country`)',
        'WHERE flight.timestamp >= {{startDate}} AND flight.timestamp < {{endDate}}',
        'WITH person.name AS person, COUNT(flight) AS n, country.name AS destination',
        'WHERE n > {{count}}',
        'RETURN person, n, destination',
        'ORDER BY n DESC',
        'LIMIT {{limit}}'
    ]

    statement = '\n'.join(statements).format()

    print(statement)

    start_date = datetime.datetime(2014, 1, 1)
    end_date = datetime.datetime(2014, 6, 30)

    params = [
        neo4j.Parameter('startDate', start_date.timestamp()),
        neo4j.Parameter('endDate',  end_date.timestamp()),
        neo4j.Parameter('count',  1),
        neo4j.Parameter('limit',  20)
    ]

    query = neo4j.Query(statement, params)

    start = time.time()*1000

    with neo4j.Transaction() as tx:

        rs = tx.execute(query)

        if rs:
            print('\t', ['Person', 'No. Flights', 'Destination'])
            for row in rs:
                print('\t', row)
        else:
            print('\t', 'No matching patterns found')

    end = time.time()*1000

    print('Took {0:.2f}ms'.format(end-start))
コード例 #3
0
def four():

    # among the people that called the representative, find those that have flown in or out of
    # one of enterprise XYZ offices in Japan, or the UK
    msg = PATTERNS[4]

    print(msg)

    statements = [
        'MATCH (poi :`Person`)<-[:REGISTERED_TO]-(poiPhone :`PhoneNumber`)-[call :CONTACTED]->'
        '(repPhone :`PhoneNumber` {{number: {{repNumber}}}})',
        'WHERE call.weekday = {{weekday}}',
        'WITH poi, COUNT(call) AS numberOfCalls',
        'MATCH (poi)-[:TOOK]->(flight :`Flight`)-[:TO]-(:`City`)-[:IN]->(country :`Country`)',
        'WHERE country.name IN {{countries}} AND flight.timestamp >= {{startDate}} AND flight.timestamp < {{endDate}}',
        'RETURN poi.name as subjectName, poi.id AS ID, COUNT(flight) AS flights, country.name AS country'
    ]

    statement = '\n'.join(statements).format()

    print(statement)

    query = neo4j.Query(
        statement,
        [
            neo4j.Parameter('repNumber', '+911-123-987-468'),
            neo4j.Parameter('weekday', 2),
            neo4j.Parameter('countries', ['Japan', 'UK']),
            neo4j.Parameter('startDate', datetime.datetime(2014, 1, 1).timestamp()),
            neo4j.Parameter('endDate', datetime.datetime(2014, 12, 31).timestamp())
        ]
    )

    start = time.time()*1000

    with neo4j.Transaction() as tx:

        rs = tx.execute(query)

        if rs:
            print('\t', ['Name', 'ID', 'No. of Flights'])
            for row in rs:
                print('\t', row)
        else:
            print('\t', 'No matching patterns found')

    end = time.time()*1000

    print('Took {0:.2f}ms'.format(end-start))
コード例 #4
0
def five():

    msg = PATTERNS[5]

    print(msg)

    statements = [
        'MATCH (poi :`Person`)<-[:REGISTERED_TO]-(poiPhone :`PhoneNumber`)-[call :CONTACTED]->'
        '(repPhone :`PhoneNumber` {{number: {{repNumber}}}})',
        'WHERE call.weekday = {{weekday}}',
        'WITH poi, COUNT(call) AS numberOfCalls',
        'MATCH (poi)-[:TOOK]->(flight :`Flight`)-[:TO]-(:`City`)-[:IN]->(country :`Country`)'
        'WHERE country.name IN {{countries}} AND flight.timestamp >= {{startDate}} AND flight.timestamp < {{endDate}}',
        'WITH poi',
        'MATCH (poi)-[employment :EMPLOYEE_AT]->(company: `Company` {{name: {{companyName}} }})',
        'WHERE employment.since < {{activitiesStartPeriod}} OR employment.until > {{activitiesStartPeriod}}',
        'WITH DISTINCT employment, poi, company',
        'RETURN poi.name as subjectName, poi.id AS ID, employment.since AS since, employment.until AS until'
    ]

    statement = '\n'.join(statements).format()

    print(statement)

    query = neo4j.Query(
        statement,
        [
            neo4j.Parameter('repNumber', '+911-123-987-468'),
            neo4j.Parameter('weekday', 2),
            neo4j.Parameter('countries', ['Japan', 'UK']),
            neo4j.Parameter('companyName', 'WT Enterprises'),
            neo4j.Parameter('startDate', datetime.datetime(2014, 1, 1).timestamp()),
            neo4j.Parameter('endDate', datetime.datetime(2014, 12, 31).timestamp()),
            neo4j.Parameter('activitiesStartPeriod', datetime.datetime(2014, 1, 1).timestamp())
        ]
    )

    start = time.time()*1000

    with neo4j.Transaction() as tx:

        rs = tx.execute(query)

        if rs:
            print('\t', ['Name', 'ID', 'Since', 'Until'])
            for row in rs:
                print(
                    '\t',
                    [
                        row[0], row[1],
                        datetime.datetime.fromtimestamp(row[2]).strftime('%Y-%m-%d'),
                        datetime.datetime.fromtimestamp(row[3]).strftime('%Y-%m-%d')
                    ]
                )
        else:
            print('\t', 'No matching patterns found')

    end = time.time()*1000

    print('Took {0:.2f}ms'.format(end-start))
コード例 #5
0
    def cypher(self):

        statements = [
            'MERGE (country1 :`Country` {{ name:{{co1}} }})',
            'MERGE (country2 :`Country` {{ name:{{co2}} }})',
            'MERGE (city1 :`City` {{ name:{{ci1}} }})',
            'MERGE (city2 :`City` {{ name:{{ci2}} }})',
            'MERGE (city1)-[:IN]->(country1)',
            'MERGE (city2)-[:IN]->(country2)',
            'MERGE (person :`Person` {{id: {{personId}} }})',
            'MERGE (flight :`Flight` {{number: {{flightNo}} }})'
            'SET flight.timestamp = {{timestamp}}',
            'MERGE (flight)-[:FROM]->(city1)', 'MERGE (flight)-[:TO]->(city2)',
            'MERGE (person)-[:TOOK]->(flight)'
        ]

        statement = '\n'.join(statements).format()

        params = [
            neo4j.Parameter('co1', self.departure['country']),
            neo4j.Parameter('co2', self.destination['country']),
            neo4j.Parameter('ci1', self.departure['city']),
            neo4j.Parameter('ci2', self.destination['city']),
            neo4j.Parameter('flightNo', self.number),
            neo4j.Parameter('personId', self.person),
            neo4j.Parameter('timestamp', self.timestamp)
        ]

        return neo4j.Query(statement, params)
コード例 #6
0
    def cypher(self):

        statements = [
            'MERGE (person :`Person` {{ id: {{personId}} }})',
            'MERGE (company :`Company` {{ name:{{companyName}} }})',
            'CREATE (person)-[emp :EMPLOYEE_AT]->(company)',
            'SET emp.since = {{since}}', 'SET emp.until = {{until}}'
        ]

        statement = '\n'.join(statements).format()

        params = [
            neo4j.Parameter('personId', self.person),
            neo4j.Parameter('companyName', self.company),
            neo4j.Parameter('since', self.since),
            neo4j.Parameter('until', self.until),
        ]

        return neo4j.Query(statement, params)
コード例 #7
0
    def cypher(self):

        statements = [
            'MERGE (p :`Person` {{id: {{personId}} }})',
            'SET p.name = {{name}}', 'SET p.sex = {{sex}}',
            'MERGE (n :`PhoneNumber` {{number: {{number}} }})',
            'MERGE (n)-[:REGISTERED_TO]->(p)'
        ]

        statement = '\n'.join(statements).format()

        params = [
            neo4j.Parameter('personId', self.id),
            neo4j.Parameter('name', self.name),
            neo4j.Parameter('sex', self.sex),
            neo4j.Parameter('number', self.number)
        ]

        return neo4j.Query(statement, params)
コード例 #8
0
def three():

    # find a phone number that has made calls on between 6pm and 10pm to the representative
    msg = PATTERNS[3]
    print(msg)

    statements = [
        'MATCH (poi)<-[:REGISTERED_TO]-(poiPhone :`PhoneNumber`)-[call :CONTACTED]->'
        '(repPhone :`PhoneNumber` {{number: {{repNumber}}}})',
        'WHERE call.weekday = {{weekday}}',
        'RETURN poi.name AS subjectName, COUNT(call) AS numberOfCalls'
    ]
    #  AND call.hour >= {{startInterval}} AND call.hour <= {{endInterval}}

    statement = '\n'.join(statements).format()

    print(statement)

    query = neo4j.Query(
        statement,
        [
            neo4j.Parameter('repNumber', '+911-123-987-468'),
            neo4j.Parameter('weekday', 2)
        ]
    )

    start = time.time()*1000

    with neo4j.Transaction() as tx:

        rs = tx.execute(query)

        if rs:
            print('\t', ['Subject\'s Name', 'No. Calls'])
            for row in rs:
                print('\t', row)
        else:
            print('\t', 'No matching patterns found')

    end = time.time()*1000

    print('Took {0:.2f}ms'.format(end-start))
コード例 #9
0
    def cypher(self):

        statements = [
            'MERGE (n1 :`PhoneNumber` {{ number: {{number1}} }})',
            'MERGE (n2 :`PhoneNumber` {{ number: {{number2}} }})',
            'CREATE (n1)-[r :CONTACTED]->(n2)', 'SET r.weekday = {{weekday}}',
            'SET r.hour = {{hour}}', 'SET r.timestamp = {{timestamp}}'
        ]

        statement = '\n'.join(statements).format()

        params = [
            neo4j.Parameter('number1', self.source),
            neo4j.Parameter('number2', self.target),
            neo4j.Parameter('weekday', self.weekday),
            neo4j.Parameter('hour', self.hour),
            neo4j.Parameter('timestamp', self.timestamp)
        ]

        return neo4j.Query(statement, params)
コード例 #10
0
def two():

    # find people that took more than 1 flight to any destination each month, for the past ~8 months
    msg = PATTERNS[2]
    print(msg)

    statements = [
        'MATCH (person :`Person`)-[:TOOK]->(flight :`Flight`)-[:TO]-(:`City`)-[:IN]->(country :`Country`)',
        'WHERE flight.timestamp >= {{startDate}} AND flight.timestamp < {{endDate}}',
        'WITH person.name AS person, COUNT(flight) AS n, country.name AS destination',
        'WHERE n > {{count}}',
        'RETURN person, n, destination'
    ]

    statement = '\n'.join(statements).format()

    print(statement)

    queries = []
    start_date = datetime.datetime(2014, 8, 1)
    end_date = datetime.datetime(2014, 8, 31)

    for i in reversed(range(0, 8)):

        params = [
            neo4j.Parameter('startDate', (start_date - datetime.timedelta(days=30*i)).timestamp()),
            neo4j.Parameter('endDate',  (end_date - datetime.timedelta(days=30*i)).timestamp()),
            neo4j.Parameter('count', 1)
        ]

        query = neo4j.Query(statement, params)
        queries.append(query)

    start = time.time()*1000

    with neo4j.BatchTransaction() as tx:

        for query in queries:
            tx.append(query)

        resultsets = tx.execute()

        for rs, query in zip(resultsets, queries):

            print(
                'Between',
                datetime.datetime.fromtimestamp(query.params[0].value).strftime('%Y-%m-%d'),
                'and',
                datetime.datetime.fromtimestamp(query.params[1].value).strftime('%Y-%m-%d'),
            )

            if rs:
                print('\t', ['Person', 'No. Flights', 'Destination'])
                for row in rs:
                    print('\t', row)
            else:
                print('\t', 'No matching patterns found')

    end = time.time()*1000

    print('Took {0:.2f}ms'.format(end-start))