简体   繁体   English

Neo4j:匹配随机节点时,with子句中rand()和rand()的区别

[英]Neo4j: Difference between rand() and rand() in with clause when matching random nodes

I found here that i can select random nodes from neo4j using next queries:我在这里发现我可以使用下一个查询从 neo4j 随机节点 select :

  1. MATCH (a:Person) RETURN a ORDER BY rand() limit 10
  2. MATCH (a:Person) with a, rand() as rnd RETURN a ORDER BY rnd limit 10

Both queries seems to do the same thing but when I try to match random nodes that are in relationship with a given node then I have different results:两个查询似乎都做同样的事情,但是当我尝试匹配与给定节点相关的随机节点时,我会得到不同的结果:

The next query will return always the same nodes (nodes are not randomly selected)下一个查询将始终返回相同的节点(节点不是随机选择的)

MATCH (p:Person{user_id: '1'})-[r:REVIEW]->(m:Movie)
return m order by rand() limit 10

...but when I use rand() in a with clause I get indeed random nodes: ...但是当我在 with 子句中使用 rand() 时,我确实得到了随机节点:

MATCH (p:Person{user_id: '1'})-[r:REVIEW]->(m:Movie)
with m, rand() as rnd
return m order by rnd limit 10

Any idea why rand() behave different in a with clause in the second query but in the first not?知道为什么 rand() 在第二个查询中的 with 子句中表现不同,但在第一个查询中却没有?

It's important to understand that using rand() in the ORDER BY like this isn't doing what you think it's doing.重要的是要了解像这样在 ORDER BY 中使用 rand() 并没有做你认为它正在做的事情。 It's not picking a random number per row, it's ordering by a single number.它不是每行选择一个随机数,而是按一个数字排序。

It's similar to a query like:它类似于如下查询:

MATCH (p:Person)
RETURN p
ORDER BY 5

Feel free to switch up the number.随意切换号码。 In any case, it doesn't change the ordering because ordering every row, when the same number is used, doesn't change the ordering.在任何情况下,它都不会改变顺序,因为在使用相同数字时对每一行进行排序不会改变顺序。

But when you project out a random number in a WITH clause per row, then you're no longer ordering by a single number for all rows, but by a variable which is different per row.但是,当您在每行的 WITH 子句中投影出一个随机数时,您不再按所有行的单个数字排序,而是按每行不同的变量排序。

Your assumption is not correct.你的假设是不正确的。 I always get a randomized order by using below query when running it in Neoj Desktop.在 Neoj Desktop 中运行时,我总是使用以下查询获得随机顺序。

MATCH (p:Person{name: 'Jessica Thompson'})-[r:REVIEWED]->(m:Movie)
return m order by rand() limit 10

If your data has only 5 records in it, then adding a limit 10 will ALWAYS return 5 records.如果您的数据中只有 5 条记录,那么添加限制 10 将始终返回 5 条记录。 Put a limit of 2 then you will see it is "randomized"限制为 2 然后你会看到它是“随机的”

MATCH (p:Person{name: 'Jessica Thompson'})-[r:REVIEWED]->(m:Movie)
return m order by rand() limit 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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