如何仅匹配两个节点之间的一种关系 [英] how to match only one relationship between two nodes

查看:72
本文介绍了如何仅匹配两个节点之间的一种关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用neo4j graph db,它在Ruby on Rails中使用, 例如: 我在tom和jerry之间有3个关系,他们合作建造了3个房子,现在我只想匹配3个房子中的1个;如何编写查询代码? 我已经试过了:这是我的代码:

i am using neo4j graph db ,it used in Ruby on Rails , for example: i have 3 relationship between tom and jerry ,they cooperated to build 3 houses, and now i just want to match 1 of 3 ;how to write the query code???
i have tried this: this is my code:

Neo4j::Session
             .query("MATCH (s1:Scholar)<-[r:COOPERATE]-(s2:Scholar) WHERE s1.id = #{@scholar.id}  RETURN  DISTINCT r ")

结果是s1和s2之间的所有关系都建立了

and the result is all relationship between s1 and s2 were founded

我只需要s1和s2之间的一种关系(我想在我的数据库中找到所有关系,但是我只需要每2个节点之间一个关系)

i just need 1 of relationship between s1 and s2 (i want to find all relationship in my db ,but i just need one between every 2 nodes)

如何解决?

推荐答案

每个相关节点仅获得一种关系:

To get only one relationship for each related node:

MATCH (s1:Scholar)<-[r:COOPERATE]-(s2:Scholar) WHERE s1.id = {s1_id} RETURN s2, collect(r)[0] AS r

请注意,我使用的参数更安全(如果数据来自用户),并允许Neo4j缓存您的查询.要在neo4j-core gem中使用参数:

Note that I'm using parameters which are more secure (if the data is coming from a user) and allow Neo4j to cache your query. To use parameters in the neo4j-core gem:

session.query("MATCH (s1:Scholar)<-[r:COOPERATE]-(s2:Scholar) WHERE s1.id = {s1_id} RETURN s2, collect(r)[0]", s1_id: @scholar.id).map(&:r)

还有一个查询构建API,如下所示:

There is also a query building API which would look like this:

session.query
  .match('(s1:Scholar)<-[r:COOPERATE]-(s2:Scholar)')
  .where(s1: {id: @scholar.id})
  .return('s2, collect(r)[0] AS r')
  .map(&:r)

请注意,这将为您使用参数.

Note that this will use parameters for you.

此外,如果您使用neo4j gem中的ActiveNode模块(而不是进行原始查询),则可以执行类似的操作;

Also if you use the ActiveNode module from the neo4j gem (as opposed to making raw queries) you could do something like;

class Scholar
  include Neo4j::ActiveNode
  id_property :id

  has_many :in, :cooporates_with, type: :COOPERATE, model_class: :Scholar
end

Scholar.find(@scholar.id).cooporates_with(:s2, :r).return('s2, collect(r)[0] AS r').map(&:r)

这篇关于如何仅匹配两个节点之间的一种关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆