1

我不确定我使用的术语是否正确,因此请随时在必要时进行更正。我(认为)我有 JSON 对象,我试图将其转换为元素数组。

我在 Ruby 中使用 Neography 来查询 Neo4j 数据库,当我收到返回的结果时,我需要它们看起来像这样:

["apple","orange","pear"]

但是,它们看起来像这样:

[["apple"],["orange"],["pear"]]

我用来创建它的 Ruby 是:

cypher = "MATCH (n:Person) WHERE n.name =~ '(?i).*#{term}.*' RETURN n.name"
results = neo.execute_query(cypher)["data"].to_json
puts results
results

我读过这里(如何从 JSON 中删除方括号)来尝试解析 JSON,并获取第一个元素。

cypher = "MATCH (n:Person) WHERE n.name =~ '(?i).*#{term}.*' RETURN n.name"
results = neo.execute_query(cypher)["data"].to_json  
results = JSON.parse(results)
puts results
results.to_s # deals with Sinatra not being able to display a hash?

但是得到了相同的双括号结果。

4

2 回答 2

1

我建议研究 Neo4j.rb 项目(neo4j-coreneo4jgems)。全面披露:我是维护者之一;)。和neo4j-core你一起做:

neo4j_session = Neo4j::Session.open(:server_db, 'http://neo4j:password@localhost:7474')
cypher = "MATCH (n:Person) WHERE n.name =~ '(?i).*#{term}.*' RETURN n.name AS name"
results = neo4j_session.query(cypher).map(&:name)

但是,您通常应该使用参数来防止注入攻击:

cypher = "MATCH (n:Person) WHERE n.name =~ {regex} RETURN n.name AS name"
results = neo4j_session.query(cypher, regex: "(?i).*#{term}.*").map(&:name)

您还可以使用QueryAPI 为您生成参数并将 Ruby 正则表达式转换为 Cypher 语法:

results = neo4j_session.query.match(n: :Person).where(n: {name: /#{term}/i}).pluck('n.name')

如果您ActiveNodeneo4jgem 中使用它会更简单:

class Person
  include Neo4j::ActiveNode

  property :name, type: String
end

Person.where(name: /#{term}/i).pluck(:name)

您甚至可以在Person模型上创建一个搜索方法来为您执行此操作:

class Person
  include Neo4j::ActiveNode

  property :name, type: String

  def search(term)
    all.where(name: /#{term}/i)
  end
end

Person.search(term).pluck(:name)
于 2016-02-17T03:33:25.790 回答
0

这个

cypher = "MATCH (n:Person) WHERE n.name =~ '(?i).*#{term}.*' RETURN n.name"
results = neo.execute_query(cypher)["data"].flatten

应该管用

于 2016-02-16T20:06:45.110 回答