使用SaxMachine解析大文件似乎将整个文件加载到内存中

jak*_*ils 5 ruby xml sax large-files nokogiri

我有一个1.6GB的xml文件,当我用Sax Machine解析它时,它似乎不是流式传输或以块的形式吃掉文件 - 而是它似乎将整个文件加载到内存中(或者可能在某处存在内存泄漏) ?)因为我的红宝石过程爬上了2.5gb的ram.我不知道它在哪里停止增长,因为我的内存不足.

在较小的文件(50mb)上,它似乎也在加载整个文件.我的任务迭代xml文件中的记录并将每个记录保存到数据库.它需要大约30秒的"空闲",然后数据库查询突然开始执行.

我认为SAX应该允许你使用这样的大文件,而不会将整个内容加载到内存中.

有什么我可以忽略的吗?

非常感谢

更新以添加代码示例

class FeedImporter

  class FeedListing
    include ::SAXMachine

    element :id
    element :title
    element :description
    element :url

    def to_hash
      {}.tap do |hash|
        self.class.column_names.each do |key|
          hash[key] = send(key)
        end
      end
    end
  end

  class Feed
    include ::SAXMachine
    elements :listing, :as => :listings, :class => FeedListing
  end

  def perform
    open('~/feeds/large_feed.xml') do |file|

      # I think that SAXMachine is trying to load All of the listing elements into this one ruby object.
      puts 'Parsing'
      feed = Feed.parse(file)

      # We are now iterating over each of the listing elements, but they have been "parsed" from the feed already.
      puts 'Importing'
      feed.listings.each do |listing|
        Listing.import(listing.to_hash)
      end

    end
  end

end
Run Code Online (Sandbox Code Playgroud)

如您所见,我不关心<listings>Feed中的元素.我只想要每个<listing>元素的属性.

输出如下所示:

Parsing
... wait forever
Importing (actually, I don't ever see this on the big file (1.6gb) because too much memory is used :(
Run Code Online (Sandbox Code Playgroud)

Gre*_*ber 2

我分叉了 sax-machine,以便它使用恒定内存:https://github.com/gregwebs/sax-machine

好消息:有一位新的维护者计划合并我的更改。我自己和新维护者已经使用我的分叉一年了,没有出现任何问题。