首页
/ Dawarich项目处理大型Google Takeout JSON文件导入的技术方案

Dawarich项目处理大型Google Takeout JSON文件导入的技术方案

2025-06-14 13:24:04作者:伍希望

在Dawarich项目中,用户经常需要导入从Google Takeout导出的位置历史数据(Records.json文件)。当这些JSON文件体积较大时(通常超过1GB),直接导入会遇到内存不足导致进程被终止的问题。本文将深入分析问题根源并提供多种有效的解决方案。

问题根源分析

当尝试导入大型Records.json文件时,系统会显示"Killed"错误并终止进程。这主要是由于:

  1. Ruby on Rails应用默认会尝试将整个JSON文件加载到内存中进行解析
  2. 处理海量位置数据时需要消耗大量内存资源
  3. 默认配置下的容器资源限制可能不足

解决方案一:手动分割JSON文件

最直接的解决方案是将大型JSON文件分割成多个小文件分批导入。以下是使用jq工具的分割脚本示例:

#!/bin/bash
input_file="Records.json"
output_prefix="smaller_array"
chunk_size=100000

total_elements=$(jq '.locations | length' $input_file)

for ((i=0; i<total_elements; i+=chunk_size)); do
    start_index=$i
    end_index=$(($i + $chunk_size - 1))
    output_file="${output_prefix}_$(($i / $chunk_size + 1)).json"
    jq "{locations: .locations[$start_index:$end_index + 1]}" $input_file > $output_file
done

分割完成后,可以批量导入分割后的文件:

for f in tmp/imports/*.json; do 
  bundle exec rake import:big_file["${f}",'your@email.com']; 
done

解决方案二:使用流式处理(推荐)

更优雅的解决方案是使用流式JSON处理器,这样可以避免将整个文件加载到内存中。以下是使用Node.js和JSONStream的实现示例:

const fs = require('fs');
const JSONStream = require('JSONStream');

let chunk = 0;
let locations = {0: []};
let chunkSize = 100000;
let processed = 0;

let readStream = fs.createReadStream("./Records.json");
let stream = readStream.pipe(JSONStream.parse("locations.*"));

stream.on("data", l => {
    processed++;
    if(locations[chunk].length < chunkSize) {
        return locations[chunk].push(l);
    }
    fs.promises.writeFile(`${chunk}_Records.json`, 
        JSON.stringify({locations: locations[chunk]}))
        .then(() => { delete locations[chunk] });
    chunk++;
    locations[chunk] = [l];
});

stream.on("end", () => {
    if(locations[chunk].length > 0) {
        fs.promises.writeFile(`${chunk}_Records.json`, 
            JSON.stringify({locations: locations[chunk]}))
            .then(() => console.log("处理完成"));
    } else {
        console.log("处理完成");
    }
});

性能优化建议

  1. 增加Sidekiq工作线程:在docker-compose.yml中调整BACKGROUND_PROCESSING_CONCURRENCY参数,建议设置为50-100
  2. 资源分配:确保Docker容器有足够的内存(至少8GB)和CPU资源
  3. 批量处理:导入完成后,系统会自动去重,不必担心重复导入问题

未来改进方向

Dawarich项目团队计划在未来版本中实现以下改进:

  1. 自动检测大文件并分割处理
  2. 内置流式JSON解析器
  3. 更友好的进度提示和错误处理

通过以上方法,用户可以成功导入大型位置历史数据集,充分利用Dawarich项目的所有功能。对于技术小白用户,建议从手动分割方案开始,逐步尝试更高级的流式处理方案。

登录后查看全文
热门项目推荐
相关项目推荐