如何从图中获取所有关系类型的等同数据子集?

huangapple go评论56阅读模式
英文:

Neo4j How to get equal subset of data for all relationship types from a graph?

问题

我使用以下查询来获取所有节点ID及其对应的关系类型,但我只需要每种关系类型的前100条记录,我使用了LIMIT子句,但它没有起作用。

MATCH (s)-[r]->(t)
WHERE type(r) IN ['LIVES_IN', 'FROM', 'STUDIES']
RETURN toString(id(s)) as source, toString(id(t)) AS target, type(r) as type

如何使用Cypher查询获取每种关系类型的前100条记录,提前谢谢。

英文:

I use below query to get all node ID's and their corresponding relationship types, but I need only 100 records for each relationship types, I used LIMIT clause, but it didn't work.

MATCH (s)-[r]->(t)
WHERE type(r) IN ['LIVES_IN', 'FROM', 'STUDIES']
RETURN toString(id(s)) as source, toString(id(t)) AS target, type(r) as type

How can I get 100 records for each type of relationship using the cypher query, thanks in advance.

答案1

得分: 1

你可以使用 APOC 函数 apoc.agg.slice 来高效地仅获取每个 type 的前 100 个结果(而无需先获取每个 type 的所有结果):

MATCH (s)-[r]->(t)
WHERE TYPE(r) IN ['NEXT', 'BEGIN', 'END']
RETURN TYPE(r) AS type, apoc.agg.slice({source: TOSTRING(ID(s)), target: TOSTRING(ID(t))}, 0, 100) AS res

上述查询为每个 type 返回一行,以及包含 100 个 source 和目标 values 的列表。

要将每个结果单独返回在不同的行中:

MATCH (s)-[r]->(t)
WHERE TYPE(r) IN ['NEXT', 'BEGIN', 'END']
WITH TYPE(r) AS type, apoc.agg.slice({source: TOSTRING(ID(s)), target: TOSTRING(ID(t))}, 0, 100) AS res
UNWIND res AS row
RETURN type, row.source AS source, row.target AS target
英文:

You can use the APOC function apoc.agg.slice to efficiently get just the first 100 results for each type (without having to get all the results for each type first):

MATCH (s)-[r]->(t)
WHERE TYPE(r) IN ['NEXT', 'BEGIN', 'END']
RETURN TYPE(r) AS type, apoc.agg.slice({source: TOSTRING(ID(s)), target: TOSTRING(ID(t))}, 0, 100) AS res

The abover query returns a row for each type, along with a list of 100 source and target values.

To get every result on a separate row:

MATCH (s)-[r]->(t)
WHERE TYPE(r) IN ['NEXT', 'BEGIN', 'END']
WITH TYPE(r) AS type, apoc.agg.slice({source: TOSTRING(ID(s)), target: TOSTRING(ID(t))}, 0, 100) AS res
UNWIND res AS row
RETURN type, row.source AS source, row.target AS target

huangapple
  • 本文由 发表于 2023年6月15日 18:30:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76481609.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定