我正在从事一项研究项目,该项目要求我处理包含 500,000 多条记录的大型 csv 文件(~2-5 GB)。这些文件包含有关政府契约(Contract)的信息(来自 USASpending.gov)。到目前为止,我一直在使用 PHP 或 Python 脚本逐行攻击文件,解析它们,然后将信息插入到相关表中。解析适度复杂。对于每条记录,脚本检查指定的实体是否已经在数据库中(使用字符串和正则表达式匹配的组合);如果不是,它首先将实体添加到实体表中,然后继续解析记录的其余部分并将信息插入到适当的表中。实体列表超过 100,000。
以下是尝试将每条记录与任何现有实体进行匹配的基本函数(类的一部分):
private function _getOrg($data)
{
// if name of organization is null, skip it
if($data[44] == '') return null;
// use each of the possible names to check if organization exists
$names = array($data[44],$data[45],$data[46],$data[47]);
// cycle through the names
foreach($names as $name) {
// check to see if there is actually an entry here
if($name != '') {
if(($org_id = $this->_parseOrg($name)) != null) {
$this->update_org_meta($org_id,$data); // updates some information of existing entity based on record
return $org_id;
}
}
}
return $this->_addOrg($data);
}
private function _parseOrg($name)
{
// check to see if it matches any org names
// db class function, performs simple "like" match
$this->db->where('org_name',$name,'like');
$result = $this->db->get('orgs');
if(mysql_num_rows($result) == 1) {
$row = mysql_fetch_object($result);
return $row->org_id;
}
// check to see if matches any org aliases
$this->db->where('org_alias_name',$name,'like');
$result = $this->db->get('orgs_aliases');
if(mysql_num_rows($result) == 1) {
$row = mysql_fetch_object($result);
return $row->org_id;
}
return null; // no matches, have to add new entity
}
_addOrg 函数将新实体的信息插入到数据库中,希望它能匹配后续记录。
问题是:我只能让这些脚本每小时解析大约 10,000 条记录,考虑到大小,这意味着每个文件需要几天的时间。我的数据库的结构方式需要为每条记录更新几个不同的表,因为我正在编译多个外部数据集。因此,每条记录更新两个表,每个新实体更新三个表。我担心这会在 MySQL 服务器和我的脚本之间增加太多滞后时间。
这是我的问题:有没有办法将文本文件导入临时 MySQL 表,然后使用内部 MySQL 函数(或 PHP/Python 包装器)加速处理?
我在带有本地 MySQL 服务器的 Mac OS 10.6 上运行它。
最佳答案
使用load data infile 将文件加载到临时/暂存表中,然后使用存储过程 处理数据 - 时间不应超过 1-2 分钟最完整地加载和处理数据。
您可能还会发现我感兴趣的其他一些答案:
Optimal MySQL settings for queries that deliver large amounts of data?
MySQL and NoSQL: Help me to choose the right one
How to avoid "Using temporary" in many-to-many queries?
60 million entries, select entries from a certain month. How to optimize database?
有趣的介绍:
http://www.mysqlperformanceblog.com/2011/03/18/video-the-innodb-storage-engine-for-mysql/
示例代码(可能对你有用)
truncate table staging;
start transaction;
load data infile 'your_data.dat'
into table staging
fields terminated by ',' optionally enclosed by '"'
lines terminated by '\n'
(
org_name
...
)
set
org_name = nullif(org_name,'');
commit;
drop procedure if exists process_staging_data;
delimiter #
create procedure process_staging_data()
begin
insert ignore into organisations (org_name) select distinct org_name from staging;
update...
etc..
-- or use a cursor if you have to ??
end#
delimiter ;
call process_staging_data();
希望对你有帮助
关于php - 在 MySQL 中导入和处理文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5971965/