Skip to content

Instantly share code, notes, and snippets.

@polozhevets
Last active June 17, 2020 13:04
Show Gist options
  • Save polozhevets/8a8fbc42f0cf549ba72afaf9c03e1724 to your computer and use it in GitHub Desktop.
Save polozhevets/8a8fbc42f0cf549ba72afaf9c03e1724 to your computer and use it in GitHub Desktop.
Asynchronous wrapper for Official Neo4j driver for Python
# Neo4j async
from neo4j import GraphDatabase
from neo4j.exceptions import ServiceUnavailable
import logging
import asyncio
NEO4J_HOST = 'localhost'
NEO4J_USER = 'neo4j'
NEO4J_PASS = 'neo4j'
class AsyncNeo4j:
_driver = None
@classmethod
async def get_driver(cls):
if cls._driver is None:
while cls._driver is None:
try:
cls._driver = GraphDatabase.driver("bolt://{}".format(NEO4J_HOST), auth=(NEO4J_USER, NEO4J_PASS))
except ServiceUnavailable as e:
logging.error(str(e))
logging.info("Neo4j: Reconnecting...")
await asyncio.sleep(10)
return cls._driver
@classmethod
async def run(cls, statement, *args, **kwargs):
"""Run a statement asynchronously using the event loop's default thread
pool executor.
"""
driver = await cls.get_driver()
def run():
with driver.session() as session:
result = session.run(statement, *args, **kwargs)
return result
loop = asyncio.get_event_loop()
# Passing None uses the default executor
return await loop.run_in_executor(None, run)
# Example usage:
session = AsyncNeo4j()
results = await session.run(
"""
MATCH path=shortestPath((n1:user{name:{name}})-[*0..]->(n2:book))
RETURN n2
""", name='charlie'
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment