使用Postgres在docker中上传csv文件

时间:2018-02-07 18:18:52

标签: postgresql docker

我有一个非传统的问题。我在Postgres建立了一个数据库

$ docker=# CREATE TABLE cities ( docker(# name varchar(80), docker(# location point docker(# );

使用以下命令在db中创建了一个表:

var SVGMorpheus = (function(){....code...})())

但是,我无法将csv上传到我创建的表中。你能告诉我怎么做吗? (我使用Docker Command窗口来执行此操作) 提前谢谢。

1 个答案:

答案 0 :(得分:0)

以下是使用容器内的psql将CSV中的lat / lon点复制到cities表的示例。

# Sample CSV data
echo "somecity",45,-45 > cities.csv

# Create database
docker run --name postgres -p 15432:5432 -d postgres

# Create cities table and a temp table for loading point coordinates
# Uses host network to access database published on port 15432 of the host
docker run --rm --network=host postgres psql -h localhost -p 15432 -U postgres -c '
  CREATE TABLE temp (
    name varchar(80),
    latitude numeric(12,8),
    longitude numeric(12,8)
  );
  CREATE TABLE cities (
    name varchar(80),
    location point
  );'

# \copy data from file (mounted by volume)
docker run --rm --network=host -v `pwd`:/data postgres \
  psql -h localhost -p 15432 -U postgres -c \
    "\\copy temp FROM '/data/cities.csv' WITH csv"

# Insert into cities creating point from coordinates
docker run --rm --network=host postgres psql -h localhost -p 15432 -U postgres -c "
  INSERT INTO cities (name, location)
  SELECT name, point(temp.latitude,temp.longitude) 
  FROM temp;
  DROP TABLE temp"

# Show the point
docker run --rm --network=host postgres psql -h localhost -p 15432 -U postgres -c \
  "SELECT * FROM cities;"

最后一个命令输出:

  name   | location
----------+----------
 somecity | (45,-45)
(1 row)