0

这是我当前从 CSV 导入的 rake 任务,我可以重写它以导入和删除前两列/使用空格作为分隔符将数据连接到一个 latlon 列吗?

require 'csv'

desc "Import public library data from csv file"

task :import => [:environment] do
  namespace :import_incidents_csv do
    task :create_incidents => :environment do
      ActiveRecord::Base.connection.execute "COPY PublicLibraryBranchLocations          (DistrictNumber, DistrictName, LibrarySystem, Type, Branch, Phone, Email, Website, PhysicalAddress, City, Province, PostalCode, Latitude, Longitude) FROM '/home/mgmacri/data/PublicLibraryBranchLocations.csv' DELIMITER ',' CSV;"
    end
  end
end
4

1 回答 1

2

COPY 本身无法做到这一点,但您可以在导入之前更改 CSV。

一种方法是复制到一个临时表,然后使用类似这样的东西来导入:

INSERT INTO PublicLibraryBranchLocations(DistrictNumber, DistrictName, LibrarySystem, Type, Branch, Phone, Email, Website, PhysicalAddress, City, Province, PostalCode, LatLon) 
SELECT DistrictNumber, DistrictName, LibrarySystem, Type, Branch, Phone, Email, Website, PhysicalAddress, City, Province, PostalCode, Latitude ||' '|| Longitude
FROM TEMP_PublicLibraryBranchLocations;

如您所见, end 有一个串联Latitude ||' '|| Longitude

另一种方法是使用file_fdw创建一个 FOREIGN TABLE ,因此您可以直接将 CSV 文件读取为一个表(可能称为PublicLibraryBranchLocations_FDW_CSV),而无需导入该表并将该表中的数据导入到PublicLibraryBranchLocations使用类似的东西:

INSERT INTO PublicLibraryBranchLocations(DistrictNumber, DistrictName, LibrarySystem, Type, Branch, Phone, Email, Website, PhysicalAddress, City, Province, PostalCode, LatLon) 
SELECT DistrictNumber, DistrictName, LibrarySystem, Type, Branch, Phone, Email, Website, PhysicalAddress, City, Province, PostalCode, Latitude ||' '|| Longitude
FROM PublicLibraryBranchLocations_FDW_CSV;
于 2013-04-13T20:25:04.040 回答