Query attributes with colon : inbetween with ogr2ogr and PostGIS - postgis

I'm running a PostGIS Database filled by osm2pgsql. The address-keys are stored for example as
"addr:street"
The objective is to store those geometries as GeoPackage by ogr2ogr. The script looks like this
ogr2ogr -f "GPKG" address_point.gpkg PG:"host=**** dbname=**** user=**** password=****" -sql "select addr:housenumber","addr:housename","addr:flats","addr:conscriptionnumber","addr:street","addr:place","addr:postcode","addr:city","addr:country","addr:full","addr:hamlet","addr:suburb","addr:subdistrict","addr:district","addr:province","addr:state","addr:interpolation","addr:interpolation","addr:inclusion","addr:door","addr:unit","addr:floor","addr:block",way from planet_osm_point"
ogr2ogr returns an error because of the colon in each attribute.
I think, the query fails because of " which is to suppose to wrap the query for ogr2ogr.
When I use ' as following:
ogr2ogr -f "GPKG" address_point.gpkg PG:"host=**** dbname=**** user=**** password=****" -sql "select 'addr:housenumber','addr:housename','addr:flats','addr:conscriptionnumber','addr:street','addr:place','addr:postcode','addr:city','addr:country','addr:full','addr:hamlet','addr:suburb','addr:subdistrict','addr:district','addr:province','addr:state','addr:interpolation','addr:interpolation','addr:inclusion','addr:door','addr:unit','addr:floor','addr:block',way from planet_osm_point"
the query fails, too.
Is there a way to solve this problem?

You need to escape the double quotes around the field names
ogr2ogr [...] -sql "select \"addr:housenumber\",\"addr:housename\" from planet_osm_point"
Or you can use single quotes for the entire SQL string
ogr2ogr [...] -sql 'select "addr:housenumber","addr:housename" from planet_osm_point'

Related

Can I download only the desired portion of data in the form of a csv file from the Agensgraph?

I am using Agensgraph. I want to download the data I want in the form of a csv file through the cypher syntax. Please tell me what to do.
I could use this query to get the data I wanted in the csv file.
agens -d Database_name -c "CREATE TEMP TABLE File_name AS select * from(Cypher_sql) t1 ;" -c "COPY File_name TO 'File_directory/File_name.csv' DELIMITER '|' "

ogr2ogr does not create tables

im trying to import some shapes to SQL using ogr2ogr command following this guide https://alastaira.wordpress.com/ogr2ogr-patterns-for-sql-server/
Im using this command:
ogr2ogr -overwrite -f MSSQLSpatial [connection string] [shapefile]
-nln "shape3" -nlt GEOMETRY
and getting this error:
ERROR 1: INSERT command for new feature failed.
[Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'dbo.shape3'.
ERROR 1: Unable to write feature 0 from layer tl_2010_06_zcta510.
ERROR 1: Terminating translation prematurely after failed translation of layer tl_2010_06_zcta510 (use -skipfailures to skip errors)
The command does not create the table and the inserts fails.
I tried to create the table first and using the command to insert on it:
ogr2ogr -f "MSSQLSpatial" [connection string] [shapefile] -a_srs
"ESPG:4269" -lco "GEOM_TYPE=geography" -lco "GEOM_NAME=area" -nln
"shapes3"
It works fine exept that it does not load the GEOGRAPHY colum (area), it remains NULL.
Im using the file provided in the guide and the user in the connection string is the admin so it is not a permission problem.
Thank you all in advance.
Solved it adding -lco UPLOAD_GEOM_FORMAT=wkt to the command, its related to some geometry formating.
UPLOAD_GEOM_FORMAT: (From GDAL 2.0.0) Specify the geometry format (wkb
or wkt) when creating or modifying features. The default is wkb.
https://www.gdal.org/drv_mssqlspatial.html

SQL Server FOR XML coming out in hex / ascii-binary

I am trying to get the XML Schema for a table from our SQL Server database.
If I write this in a SQL Server Management Studio:
SELECT *
FROM trNLSConsignment
FOR XML AUTO
It outputs XML in the result, which starts something like:
<trNLSConsignment NLSConsignmentId="1" NoiNLSAnimalTypeId="2" AgeFrom="12"
With a column header of:
XML_F52E2B61-18A1-11d1-B105-00805F49916B
Similarly if I want the actual schema and do:
SELECT TOP 0 *
FROM trNLSConsignment
FOR XML AUTO, XMLSCHEMA
The result in the results is correct, which starts something like:
<xsd:schema targetNamespace="urn:schemas-microsoft-com:sql:SqlRowSet3" xmlns:schema="urn:schemas-microsoft-com:sql:SqlRowSet3" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:sqltypes="http://schemas.microsoft.com/sqlserver/2004/sqltypes" elementFormDefault="qualified">
With a column header of:
XML_F52E2B61-18A1-11d1-B105-00805F49916B
But in both cases the result is truncated.
So I turned to sqlcmd and wrote a PowerShell script:
$DB = "TRACE"
$CMDBASE="sqlcmd -d $DB"
$OUTFILE="./output.txt"
iex "$CMDBASE -i schema2_script.sql -o $OUTFILE -u"
With the .._script.sql being one of the above.
However the results are in hex, output as ASCII. In the case of the XMLSCHEMA query, the output in the text file starts as:
0x44104E004C00530043006F006E007300690067006E006D0065006
With a 'column header' of:
XML_F52E2B61-18A1-11d1-B105-00805F49916B
How do I get the output to be XML ASCII Text (UTF-* is fine).
The table itself has no Binary columns.
I tried FOR XML RAW, BINARY BASE64 from https://learn.microsoft.com/en-us/sql/relational-databases/xml/example-retrieving-binary-data thinking that might help but doesn't (as not dealing with binary data per-se).
sqlcmd doesn't mention anything about binary or hex and as you can see, I supplied the -u command to output as UTF-8 thinking that might help. With / without makes no difference.
Does anyone know what i can do to get ASCII(-like) output?
I have two solutions:
The first is to the problem of the output in Management Studio being truncted - click on the results link to see the full results
And specifically for my question, to get a usable (ie. XML) output, use the TYPE directive:
select * FROM trNLSConsignment FOR XML RAW, TYPE, XMLSCHEMA
https://learn.microsoft.com/en-us/sql/relational-databases/xml/type-directive-in-for-xml-queries
Oh, and add a -y 0 arg to have variable length output (otherwise it truncates).
...
iex "$CMDBASE -i schema2_script.sql -o $OUTFILE -u -y 0"
OR if you use Powershell's Invoke-Sqlcmd with an Out-File then add a -width x argument with some value for the width of a line.
Invoke-Sqlcmd -Database $DB -MaxCharLength 99999 -query $queryString |
Out-File -FilePath "$initialOutFile" -width 99999

How to create a stored procedure that generates a CSV file from SQL Server

I want to generate a .CSV file based on data in a datatable. I know this question has been asked before, but I can't find any examples of how to specify what the separator should be.
For example if I have a table and a query like this, this is what I want the output to be:
MyTable:
Id - Int Key
NickName- NvarChar
REALName - NvarChar
Number - NvarChar
Updated - bit
Query:
SELECT *
FROM MyTable
WHERE Updated = 1
Output:
I want my output to use | as the field separator. So the output in the CSV file will look something like this:
Id|NickName|REALName|Number|Updated
1|NickNameHere|RealNameHere|0798548558|1
2|NickNameHere2|RealNameHere2|079948558|1
and so on.
The following query generate CSV data with '|' separator
select 'Id|NickName|REALName|Number|Updated'
union all
select
cast (Id as nvarchar) + '|'
+ NickName + '|'
+ RealNameHere + '|'
+ Number + '|'
+ cast (Updated as nvarchar)
from MyTable
WHERE Updated = 1
Saving output results to TextFile:
Method 1: from within SSMS
From ssms menu: query -> results to -> results to file
Method 2: using Powershell Invoke-SqlCmd
Invoke-SqlCmd -Query "your query" | Export-Csv "path\to\csvfile"
Method 3: using SqlCmd command line tool:
sqlcmd -q "your query" -o "path\to\csvfile" -S server -P password -d database

How do I output the results of a HiveQL query to CSV?

we would like to put the results of a Hive query to a CSV file. I thought the command should look like this:
insert overwrite directory '/home/output.csv' select books from table;
When I run it, it says it completeld successfully but I can never find the file. How do I find this file or should I be extracting the data in a different way?
Although it is possible to use INSERT OVERWRITE to get data out of Hive, it might not be the best method for your particular case. First let me explain what INSERT OVERWRITE does, then I'll describe the method I use to get tsv files from Hive tables.
According to the manual, your query will store the data in a directory in HDFS. The format will not be csv.
Data written to the filesystem is serialized as text with columns separated by ^A and rows separated by newlines. If any of the columns are not of primitive type, then those columns are serialized to JSON format.
A slight modification (adding the LOCAL keyword) will store the data in a local directory.
INSERT OVERWRITE LOCAL DIRECTORY '/home/lvermeer/temp' select books from table;
When I run a similar query, here's what the output looks like.
[lvermeer#hadoop temp]$ ll
total 4
-rwxr-xr-x 1 lvermeer users 811 Aug 9 09:21 000000_0
[lvermeer#hadoop temp]$ head 000000_0
"row1""col1"1234"col3"1234FALSE
"row2""col1"5678"col3"5678TRUE
Personally, I usually run my query directly through Hive on the command line for this kind of thing, and pipe it into the local file like so:
hive -e 'select books from table' > /home/lvermeer/temp.tsv
That gives me a tab-separated file that I can use. Hope that is useful for you as well.
Based on this patch-3682, I suspect a better solution is available when using Hive 0.11, but I am unable to test this myself. The new syntax should allow the following.
INSERT OVERWRITE LOCAL DIRECTORY '/home/lvermeer/temp'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
select books from table;
If you want a CSV file then you can modify Lukas' solutions as follows (assuming you are on a linux box):
hive -e 'select books from table' | sed 's/[[:space:]]\+/,/g' > /home/lvermeer/temp.csv
This is most csv friendly way I found to output the results of HiveQL.
You don't need any grep or sed commands to format the data, instead hive supports it, just need to add extra tag of outputformat.
hive --outputformat=csv2 -e 'select * from <table_name> limit 20' > /path/toStore/data/results.csv
You should use CREATE TABLE AS SELECT (CTAS) statement to create a directory in HDFS with the files containing the results of the query. After that you will have to export those files from HDFS to your regular disk and merge them into a single file.
You also might have to do some trickery to convert the files from '\001' - delimited to CSV. You could use a custom CSV SerDe or postprocess the extracted file.
You can use INSERT … DIRECTORY …, as in this example:
INSERT OVERWRITE LOCAL DIRECTORY '/tmp/ca_employees'
SELECT name, salary, address
FROM employees
WHERE se.state = 'CA';
OVERWRITE and LOCAL have the same interpretations as before and paths are interpreted following the usual rules. One or more files will be written to /tmp/ca_employees, depending on the number of reducers invoked.
If you are using HUE this is fairly simple as well. Simply go to the Hive editor in HUE, execute your hive query, then save the result file locally as XLS or CSV, or you can save the result file to HDFS.
I was looking for a similar solution, but the ones mentioned here would not work. My data had all variations of whitespace (space, newline, tab) chars and commas.
To make the column data tsv safe, I replaced all \t chars in the column data with a space, and executed python code on the commandline to generate a csv file, as shown below:
hive -e 'tab_replaced_hql_query' | python -c 'exec("import sys;import csv;reader = csv.reader(sys.stdin, dialect=csv.excel_tab);writer = csv.writer(sys.stdout, dialect=csv.excel)\nfor row in reader: writer.writerow(row)")'
This created a perfectly valid csv. Hope this helps those who come looking for this solution.
You can use hive string function CONCAT_WS( string delimiter, string str1, string str2...strn )
for ex:
hive -e 'select CONCAT_WS(',',cola,colb,colc...,coln) from Mytable' > /home/user/Mycsv.csv
I had a similar issue and this is how I was able to address it.
Step 1 - Loaded the data from Hive table into another table as follows
DROP TABLE IF EXISTS TestHiveTableCSV;
CREATE TABLE TestHiveTableCSV
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n' AS
SELECT Column List FROM TestHiveTable;
Step 2 - Copied the blob from Hive warehouse to the new location with appropriate extension
Start-AzureStorageBlobCopy
-DestContext $destContext
-SrcContainer "Source Container"
-SrcBlob "hive/warehouse/TestHiveTableCSV/000000_0"
-DestContainer "Destination Container"
-DestBlob "CSV/TestHiveTable.csv"
hive --outputformat=csv2 -e "select * from yourtable" > my_file.csv
or
hive --outputformat=csv2 -e "select * from yourtable" > [your_path]/file_name.csv
For tsv, just change csv to tsv in the above queries and run your queries
The default separator is "^A". In python language, it is "\x01".
When I want to change the delimiter, I use SQL like:
SELECT col1, delimiter, col2, delimiter, col3, ..., FROM table
Then, regard delimiter+"^A" as a new delimiter.
I tried various options, but this would be one of the simplest solution for Python Pandas:
hive -e 'select books from table' | grep "|" ' > temp.csv
df=pd.read_csv("temp.csv",sep='|')
You can also use tr "|" "," to convert "|" to ","
Similar to Ray's answer above, Hive View 2.0 in Hortonworks Data Platform also allows you to run a Hive query and then save the output as csv.
In case you are doing it from Windows you can use Python script hivehoney to extract table data to local CSV file.
It will:
Login to bastion host.
pbrun.
kinit.
beeline (with your query).
Save echo from beeline to a file on Windows.
Execute it like this:
set PROXY_HOST=your_bastion_host
set SERVICE_USER=you_func_user
set LINUX_USER=your_SOID
set LINUX_PWD=your_pwd
python hh.py --query_file=query.sql
Just to cover more following steps after kicking off the query:
INSERT OVERWRITE LOCAL DIRECTORY '/home/lvermeer/temp'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
select books from table;
In my case, the generated data under temp folder is in deflate format,
and it looks like this:
$ ls
000000_0.deflate
000001_0.deflate
000002_0.deflate
000003_0.deflate
000004_0.deflate
000005_0.deflate
000006_0.deflate
000007_0.deflate
Here's the command to unzip the deflate files and put everything into one csv file:
hadoop fs -text "file:///home/lvermeer/temp/*" > /home/lvermeer/result.csv
I may be late to this one, but would help with the answer:
echo "COL_NAME1|COL_NAME2|COL_NAME3|COL_NAME4" > SAMPLE_Data.csv
hive -e '
select distinct concat(COL_1, "|",
COL_2, "|",
COL_3, "|",
COL_4)
from table_Name where clause if required;' >> SAMPLE_Data.csv
This shell command prints the output format in csv to output.txt without the column headers.
$ hive --outputformat=csv2 -f 'hivedatascript.hql' --hiveconf hive.cli.print.header=false > output.txt
Use the command:
hive -e "use [database_name]; select * from [table_name] LIMIT 10;" > /path/to/file/my_file_name.csv
I had a huge dataset whose details I was trying to organize and determine the types of attacks and the numbers of each type. An example that I used on my practice that worked (and had a little more details) goes something like this:
hive -e "use DataAnalysis;
select attack_cat,
case when attack_cat == 'Backdoor' then 'Backdoors'
when length(attack_cat) == 0 then 'Normal'
when attack_cat == 'Backdoors' then 'Backdoors'
when attack_cat == 'Fuzzers' then 'Fuzzers'
when attack_cat == 'Generic' then 'Generic'
when attack_cat == 'Reconnaissance' then 'Reconnaissance'
when attack_cat == 'Shellcode' then 'Shellcode'
when attack_cat == 'Worms' then 'Worms'
when attack_cat == 'Analysis' then 'Analysis'
when attack_cat == 'DoS' then 'DoS'
when attack_cat == 'Exploits' then 'Exploits'
when trim(attack_cat) == 'Fuzzers' then 'Fuzzers'
when trim(attack_cat) == 'Shellcode' then 'Shellcode'
when trim(attack_cat) == 'Reconnaissance' then 'Reconnaissance' end,
count(*) from actualattacks group by attack_cat;">/root/data/output/results2.csv

Resources