Created
January 12, 2018 16:20
-
-
Save hoavt-54/4ad48f57c7614f7616d0ebda4d9798c6 to your computer and use it in GitHub Desktop.
An example of using Neo4j
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
install python connection driver | |
pip install neo4j-driver | |
""" | |
from neo4j.v1 import GraphDatabase, basic_auth | |
""" | |
The database connection class | |
1. To connect to a Neo4jDB, supply an uri where the database is running, and auth info | |
2. | |
""" | |
class DatabaseConn(object): | |
def __init__(self, uri, user, password): | |
self._driver = GraphDatabase.driver(uri, auth=basic_auth(user, password)) | |
def close(self): | |
self._driver.close() | |
""" | |
Save a Twitter user, for now only save name and id | |
""" | |
def store_user(self, user): | |
with self._driver.session() as session: | |
result = session.run("" | |
"CREATE (a:TwitterUser {name:$name, id:$tw_id}) " | |
#"MERGE (a:TwitterUser {name:$name, id:$tw_id}) " | |
"RETURN a ", | |
tw_id=user.get('id'), name=user.get('screen_name')) | |
return result.single()[0] | |
""" | |
Creat a follow connection between follower_id, person_id | |
Retrieve users by ids and creat a relation named FOLLOWS between them | |
""" | |
def creat_follow_conn(self, follower_id, person_id): | |
with self._driver.session() as session: | |
result = session.run("MATCH (a:TwitterUser),(b:TwitterUser) WHERE a.id = $f_id AND b.id = $p_id " | |
"MERGE (a)-[:FOLLOWS]->(b) ", | |
f_id=follower_id, p_id=person_id) | |
""" | |
Method to convert a json file into a Twitter user object | |
""" | |
def json2object(filename): | |
with open(filename, 'r') as f: | |
data = json.loads(json.load(f)) | |
return data | |
if __name__ == '__main__': | |
import glob, json | |
#creat the database connection | |
conn = DatabaseConn('bolt://localhost:7687', "neo4j", "neo4j") | |
#insert info for Donald Trump, should replace later by his full info. For now, only id and name | |
donald = json.loads('{"id":"12345", "screen_name":"Donald Trump"}') | |
conn.store_user(donald) | |
#store 10 users and creat their relations with Trump | |
count=0 | |
for follower_js_file in glob.glob('followers/*.json'): | |
follower = json2object(follower_js_file) | |
conn.store_user(follower) | |
conn.creat_follow_conn(follower['id'],donald['id']) | |
count +=1 | |
if count> 10 : break | |
71,0-1 Bot |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment