使用Py2neo从Neo4j查询低于平均价格数据遇阻求助
Let's break down the issues in your code and fix them step by step:
1. Cypher Query Mistakes
Your original query has two critical problems:
- Invalid variable syntax: Writing
as {Average}isn't valid Cypher—variables don't use curly braces. You just need plain variable names likeas average. - Missing filtering logic: Your query only calculates the average price but doesn't filter for prices that sit below this average. That's why you're not getting the "cheap" results you're looking for.
2. Python Code Errors
- Broken return syntax:
return cheap = graph.run(...)is invalid Python—you can't assign a variable directly inside a return statement. - Unnecessary parameter passing: Your query doesn't define any parameters (like
$average), so passingaverage=self.Averageand other arguments will throw an error because Neo4j can't find matching placeholders.
Fixed Code Implementation
Here's the corrected version of your cheap method, with a proper Cypher query that actually fetches prices below the global average:
def cheap(self): query = ''' // First calculate the global average monthly price across all Price nodes MATCH (p:Price) WITH avg(toFloat(p.monthly)) AS global_avg // Then find all Price nodes linked to Services that cost less than this average MATCH (p:Price)-[:COSTS]-(s:Service) WHERE toFloat(p.monthly) < global_avg RETURN toFloat(p.monthly) AS price, p.currency AS currency, s.service_name AS service ''' # Execute the query and convert results to a list of dictionaries for easy use result = graph.run(query) return [record.data() for record in result]
Optional: Grouped Average (Per Currency/Service)
If you want to calculate averages per currency or per service instead of a global average (e.g., find cheap prices relative to their currency's average), adjust the Cypher query like this:
// Calculate average price per currency MATCH (p:Price)-[:COSTS]-(s:Service) WITH p.currency AS currency, avg(toFloat(p.monthly)) AS group_avg // Find prices in that currency below the group average MATCH (p:Price)-[:COSTS]-(s:Service) WHERE p.currency = currency AND toFloat(p.monthly) < group_avg RETURN toFloat(p.monthly) AS price, currency, s.service_name AS service
Key Notes
- Always use
toFloat(p.monthly)to ensure your price values are treated as numbers for comparison/average calculations (assumingmonthlyis stored as a string in your database). - The
[record.data() for record in result]converts Neo4j's result object into a list of dictionaries, which is much easier to work with in Python.
内容的提问来源于stack exchange,提问作者Zeqo
相关产品推荐
相关产品推荐

