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??
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.