【问题标题】:Performance issue on parsing JSON and storing data to database解析 JSON 并将数据存储到数据库的性能问题
【发布时间】:2018-09-20 05:56:49
【问题描述】:

我正在尝试构建一个将草图转换为幻灯片的网络应用程序。幻灯片上对象的位置和类别将由如下 JSON 给出:

[
  {
    "attachment": "https://s3-us-west-2.amazonaws.com/some_picture.jpg",
    "response": {
      "annotations": [
        {
          "width": 72,
          "height": 20,
          "left": 24,
          "top": 180,
          "label": "text"
        },
        {
          "width": 96,
          "height": 19,
          "left": 26,
          "top": 212,
          "label": "picture"
        }
      ]
    }
  }
]

我使用 each 循环遍历 JSON 文件中的对象,然后将它们存储到 Neo4j 数据库中。

def save_detection_to_db(detection_json)
  detection_json.each do |single_picture|
    annotations = single_picture["response"]["annotations"]
    annotations.each do |single_annotation|
      label = single_annotation["label"]
      determine_node_label(label).create(width: single_annotation["width"], 
                                         height: single_annotation["height"],
                                         top: single_annotation["top"],
                                         left: single_annotation["left"],
                                         category: single_annotation["label"])
    end
  end
end

# determine_node_label("text") #=> Text
# determine_node_label("picture") #=> Picture

这样我可以在 0.6 秒内存储大约 100 个对象。但鉴于此应用程序旨在供许多人使用以生成幻灯片,它不会完成这项工作。我假设每个循环都不是一个好方法。我应该尝试哪些其他方法?任何建议将不胜感激。

【问题讨论】:

    标签: ruby-on-rails ruby database algorithm neo4j


    【解决方案1】:

    你可以试试:

    def save_detection_to_db(detection_json)
      detection_json.each do |single_picture|
        annotations = single_picture["response"]["annotations"].group_by{|x| x["label"]}
        annotations.each do |k, values|
          klass = determine_node_label(k)
          values.each do |value|
             value["category"] = value.delete("label")
             klass.create(value)
          end 
        end
    end
    

    在上面的代码中,我们不是为每条记录寻找节点,group_by 将节点分组并只为它们寻找,它会减少更多的循环事物和每个val。

    我对 neo4jr 没有任何了解,如果您在 neo4j 中有任何批量插入,只需获取值并从那里插入即可。

    value["category"] = value.delete("label")
    

    意思是:

    在循环中我们会有一个值为:

    {"width"=>72, "height"=>20, "left"=>24, "top"=>180, "label"=>"text"}
    

    在 DB 中,我们有“类别”属性,我们没有“标签”,这就是原因,我使用代码 sn-p 将“标签”键替换为“类别”。

    【讨论】:

    • 这很有帮助!但是你能解释一下value["category"] = value.delete("label")吗?
    • value["category"] = value.delete("label") 表示:在循环中我们将有一个值是:{"width"=>72, "height"=>20, "left"=>24, "top"=>180, "label"=>"text"} 在 DB 我们有 "category" 属性,我们没有 "label",这就是原因,我正在替换一个 " label”键和“Category”由代码 sn-p 使用。帖子中更新了相同的解释。
    【解决方案2】:

    尝试在 neo4j 中执行 batch insert。有很多例子说明如何做到这一点here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-22
      • 2020-10-04
      • 1970-01-01
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多