query.py 1.0 KB

12345678910111213141516171819202122232425262728
  1. class AsyncNeo4jQuery:
  2. def __init__(self, neo4j):
  3. self.neo4j = neo4j
  4. async def close(self):
  5. await self.neo4j.close()
  6. async def get_document_by_id(self, doc_id: str):
  7. query = """
  8. MATCH (d:Document {doc_id: $doc_id})
  9. OPTIONAL MATCH (d)-[:HAS_CHUNK]->(c:Chunk)
  10. RETURN d, collect(c) as chunks
  11. """
  12. async with self.neo4j.session() as session:
  13. result = await session.run(query, doc_id=doc_id)
  14. return [
  15. record.data() for record in await result.consume().records
  16. ] # 注意 result 需要 async 迭代
  17. async def search_chunks_by_topic(self, topic: str):
  18. query = """
  19. MATCH (c:Chunk {topic: $topic})
  20. OPTIONAL MATCH (c)-[:HAS_ENTITY]->(e:Entity)
  21. RETURN c, collect(e.name) as entities
  22. """
  23. async with self.neo4j.session() as session:
  24. result = await session.run(query, topic=topic)
  25. return [record.data() async for record in result]