Neo4jrb - Cypher查询

时间:2016-07-08 22:19:15

标签: ruby-on-rails neo4j neo4j.rb

我有一个像这个问题的数据库:

Neo4j - Finding the Shortest Path between two nodes based on relationship property

CREATE (some_point_1:Point {title:'Some Point 1'})
CREATE (some_point_2:Point {title:'Some Point 2'})
CREATE (some_point_3:Point {title:'Some Point 3'})
CREATE (some_point_4:Point {title:'Some Point 4'})
CREATE (some_point_5:Point {title:'Some Point 5'})
CREATE (some_point_6:Point {title:'Some Point 6'})

CREATE (some_point_1)-[:distance {value:100}]->(some_point_2)
CREATE (some_point_2)-[:distance {value:150}]->(some_point_4)
CREATE (some_point_1)-[:distance {value:200}]->(some_point_3)
CREATE (some_point_3)-[:distance {value:300}]->(some_point_4)
CREATE (some_point_2)-[:distance {value:500}]->(some_point_5)
CREATE (some_point_4)-[:distance {value:300}]->(some_point_5)
CREATE (some_point_5)-[:distance {value:300}]->(some_point_6)
CREATE (some_point_6)-[:distance {value:300}]->(some_point_1)

现在我尝试执行这样的查询:(来自Rails应用程序)

MATCH (start:Point {title: 'Some Point 1'}), (end:Point {title: 'Some Point 5'})
MATCH p=(start)-[:distance*]->(end)
WITH p,reduce(s = 0, r IN rels(p) | s + r.value) AS dist
RETURN p, dist ORDER BY dist DESC

我尝试使用active model wrapper进行类似的查询,但它无效:(

有没有办法从neo4jrb或neo4j-core执行纯粹的Cypher查询?

3 个答案:

答案 0 :(得分:1)

是的,如果你想通过neo4j-core gem(你在使用neo4j宝石时仍然需要),你可以直接轻松地做Cypher。

例如:n = Neo4j::Session.query("MATCH (n) RETURN n").first(假设您已将应用程序配置为与Neo4j服务器通信)。

如果您使用的是neo4j gem,则需要在应用程序中使用相应的ActiveNode(以及可能的ActiveRel)模型,以便您可以进行查询。对于Neo4j,这个gem几乎是标准ActiveModel的好包装:)

您有关于如何:https://github.com/neo4jrb/neo4j-core/wiki/Queries的更多信息 您也可以从QueryProxy链移动到Neo4j::Core::Query。见https://github.com/neo4jrb/neo4j/wiki/Search-and-Match#detailed-querying

答案 1 :(得分:0)

MATCH(开始:点{标题:'某些点1'}),(结束:点{标题:'某些点5'}) MATCH p =(开始) - [:距离*] - >(结束) WITH p,reduce(s = 0,r IN rels(p)| s + r.value)AS dist 返回p,dist ORDER BY dist DESC

吉列尔莫是完全正确的,但我想我会试着用一些代码:

Point.where(title: 'Some Point 1').connected(:end, :rels, rel_length: :any).where(title: 'Some Point 5')
   .query.with(:p, dist: 'reduce(s = 0, r IN :rels | s + r.value)')
   .return(:p, :dist)
   .order(disc: :desc)

这将为您提供Enumerable,您可以迭代或致电to_a。或者您可以直接返回二维数组:

   .order(disc: :desc)
   .pluck(:p, :dist)

这假定为吉列尔莫所说的ActiveNode模型。喜欢的东西;

class Point
  include Neo4j::ActiveNode
  property :title

  has_many :out, :connected, type: :distance, model_class: :Point
end

关联的名称可能是你想要的,也可能不是你想要的,我猜对了。

答案 2 :(得分:0)

吉列尔莫是完全正确的,但我想我会试着用一些代码:

Point.where(title: 'Some Point 1').connected(:end, :rels, rel_length: :any).where(title: 'Some Point 5')
   .query.with(:p, dist: 'reduce(s = 0, r IN :rels | s + r.value)')
   .return(:p, :dist)
   .order(disc: :desc)

这将为您提供Enumerable,您可以迭代或致电to_a。或者您可以直接返回二维数组:

   .order(disc: :desc)
   .pluck(:p, :dist)

这假定为吉列尔莫所说的ActiveNode模型。喜欢的东西;

class Point
  include Neo4j::ActiveNode
  property :title

  has_many :out, :connected, type: :distance, model_class: :Point
end

关联的名称可能是你想要的,也可能不是你想要的,我猜对了。