how to match only one relationship between two nodes

纵饮孤独 提交于 2019-12-23 19:03:55

问题


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 ")

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

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)

how to fixed it??


回答1:


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

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)

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.

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)


来源:https://stackoverflow.com/questions/32389657/how-to-match-only-one-relationship-between-two-nodes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!