You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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 like as 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 passing average=self.Average and 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 (assuming monthly is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:25:39