如何在图数据库中找到最受欢迎的产品?

时间:2021-01-15 12:11:01

标签: neo4j cypher

我有一个使用 Neo4j 制作的具有以下架构的图形数据库。

MATCH (customer{customerid})-[:made]->(purchased{Invoiceno, invoicedate})-[:includes{quantity, invoiceamount}]->(product{stockcode, unitprice})

我想要最受欢迎的产品,即客户购买最多的产品,但我只能按数量获得购买最多的产品。

MATCH (a:customer)-[r1:MADE]->(b:purchase)-[r2:includes]->(c:product)
WITH SUM(r2.quantity) AS totalquantity, c.stockcode AS productcode
RETURN productcode, totalquantity  ORDER BY totalquantity DESC LIMIT 1

这就是结果。

╒═════════════╤═══════════════╕
│"productcode"│"totalquantity"│
╞═════════════╪═══════════════╡
│"84077"      │3552           │
└─────────────┴───────────────┘

那么,如何根据大多数客户的购买量获得最受欢迎的产品?

1 个答案:

答案 0 :(得分:1)

如果一次购买可以包含多次相同的产品,则您需要遍历来自客户的完整路径并只返回路径计数:

MATCH (a:customer)-[r1:MADE]->(b:purchase)-[r2:includes]->(c:product)
RETURN c.id, count(*) AS score
ORDER BY score DESC
LIMIT 1

如果产品只能包含在一次购买中,那么您只需返回产品的 degree 以建立 includes 关系:

MATCH (c:product)
RETURN c.id, size((c)<-[:includes]-()) AS score
ORDER BY score DESC
LIMIT 1