[英]How to limit subnodes from each nodes Neo4j Cypher
我是Neo4j的新手,我有以下情況
在上圖中表示具有標簽user
的節點,其具有具有標簽shops
子節點。 這些子節點中的每一個都具有帶有標簽items
子節點。 每個節點items
具有屬性size
,並且項節點按每個節點shops
的size
屬性按降序排列,如圖中所示。
我想從每個shops
獲得兩個大小小於或等於17
items
節點。 怎么做? 我試過了,但它不按我需要的方式工作
這是我嘗試過的
match (a:user{id:20000})-[:follows]-(b:shops)
with b
match (b)-[:next*]->(c:items)
where c.size<=17
return b
limit 2
注意 -這些shops
節點可以有數千個items
節點。 那么如何在不遍歷所有數千個items
節點的情況下找到所需的節點。 請提前幫助,謝謝。
現在Cypher不能很好地處理這個案例,我可能會為此做一個基於java的非托管擴展。
它看起來像這樣:
public List<Node> findItems(Node shop, int size, int count) {
List<Node> results=new ArrayList<>(count);
Node item = shop.getSingleRelationship(OUTGOING, "next").getEndNode();
while (item.getProperty("size") > size && results.size() < count) {
if (item.getProperty("size") <= size) result.add(item);
item = item.getSingleRelationship(OUTGOING, "next").getEndNode();
}
return result;
}
List<Node> results=new ArrayList<>(count*10);
for (Relationship rel = user.getRelationships(OUTGOING,"follows")) {
Node shop = rel.getEndNode();
results.addAll(findItems(shop,size,count));
}
您可以通過根據大小對它們進行分組來避免遍歷每個商店的所有商品。 在這種方法中,您的圖形看起來像這樣
(:User)-[:follows]-(:Shop)-[:sells]-(:Category {size: 17})-[:next]-(:Item)
然后,您可以找到每個商店使用的兩件商品
match (a:User {id: 20000})-[:follows]-(s:Shop)-[:sells]-(c:Category)
where c.size <= 17
with *
match p = (c)-[:next*0..2]-()
with s, collect(tail(nodes(p))) AS allCatItems
return s, reduce(shopItems=allCatItems[..0], catItems in allCatItems | shopItems + catItems)[..2]
shopItems=allCatItems[..0]
是一種類型檢查問題的解決方法,這實際上將shopItems初始化為一個空的節點集合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.