Neo4j: Assign unique values to all nodes matching query

邮差的信 提交于 2019-12-06 21:48:37

Got it! Found http://java.dzone.com/articles/neo4j-cypher-creating, which provided a method for doing this, and http://jexp.de/blog/2014/03/quickly-create-a-100k-neo4j-graph-data-model-with-cypher-only/ pointed out the range function. My first draft of the Ruby code that performs this looks like this:

def add_ids_to(model)
  label = model.mapped_label_name
  property = model.primary_key
  total = 1

  until total == 0
    total = Neo4j::Session.query("MATCH (n:`#{label}`) WHERE NOT has(n.#{property}) RETURN COUNT(n) as ids").first.ids
    return if total == 0
    to_set = total > 900 ? 900 : total
    new_ids = [].tap do |ids_array|
                to_set.times { ids_array.push "'#{new_id_for(model)}'" }
              end
    Neo4j::Session.query("MATCH (n:`#{label}`) WHERE NOT has(n.#{property})
      with COLLECT(n) as nodes, [#{new_ids.join(',')}] as ids
      FOREACH(i in range(0,#{to_set - 1})| 
        FOREACH(node in [nodes[i]]|
          SET node.#{property} = ids[i]))
      RETURN distinct(true)
      limit #{to_set}")
  end
end

I think that's all pretty readable. Regarding the queries themselves, I'm using Neo4j.rb and neo4j-core, but I'm skipping the Cypher DSL in this case. I'm limiting each query to a max of 900 nodes because that was the highest I could reliably go without running out of memory. Tune for your JVM heap size.

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