繁体   English   中英

如何限制每个节点Neo4j Cypher的子节点

[英]How to limit subnodes from each nodes Neo4j Cypher

我是Neo4j的新手,我有以下情况

在此输入图像描述

在上图中表示具有标签user的节点,其具有具有标签shops子节点。 这些子节点中的每一个都具有带有标签items子节点。 每个节点items具有属性size ,并且项节点按每个节点shopssize属性按降序排列,如图中所示。

我想从每个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM