]> git.openstreetmap.org Git - nominatim.git/blob - utils/export.php
README: tiny markdown syntax error
[nominatim.git] / utils / export.php
1 <?php
2     // Script to extract structured city and street data
3     // from a running nominatim instance as CSV data
4
5
6     require_once(CONST_BasePath.'/lib/init-cmd.php');
7     require_once(CONST_BasePath.'/lib/ParameterParser.php');
8     ini_set('memory_limit', '800M');
9
10     $aCMDOptions = array(
11                     'Export addresses as CSV file from a Nominatim database',
12                     array('help', 'h', 0, 1, 0, 0, false, 'Show Help'),
13                     array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'),
14                     array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'),
15
16                     array('output-type', '', 0, 1, 1, 1, 'str', 'Type of places to output (see below)'),
17                     array('output-format', '', 0, 1, 1, 1, 'str', 'Column mapping (see below)'),
18                     array('output-all-postcodes', '', 0, 1, 0, 0, 'bool', 'List all postcodes for address instead of just the most likely one'),
19                     array('language', '', 0, 1, 1, 1, 'str', 'Preferred language for output (local name, if omitted)'),
20                     array('restrict-to-country', '', 0, 1, 1, 1, 'str', 'Export only objects within country (country code)'),
21                     array('restrict-to-osm-node', '', 0, 1, 1, 1, 'int', 'Export only objects that are children of this OSM node'),
22                     array('restrict-to-osm-way', '', 0, 1, 1, 1, 'int', 'Export only objects that are children of this OSM way'),
23                     array('restrict-to-osm-relation', '', 0, 1, 1, 1, 'int', 'Export only objects that are children of this OSM relation'),
24                     "\nAddress ranks: continent, country, state, county, city, suburb, street, path",
25                     'Additional output types: postcode, placeid (placeid for each object)',
26                     "\noutput-format must be a semicolon-separated list of address ranks. Multiple ranks",
27                     'can be merged into one column by simply using a comma-separated list.',
28                     "\nDefault output-type: street",
29         'Default output format: street;suburb;city;county;state;country'
30                    );
31     getCmdOpt($_SERVER['argv'], $aCMDOptions, $aCMDResult, true, true);
32
33     $aRankmap = array(
34                  'continent' => 1,
35                  'country' => 4,
36                  'state' => 8,
37                  'county' => 12,
38                  'city' => 16,
39                  'suburb' => 20,
40                  'street' => 26,
41                  'path' => 27
42                 );
43
44     $oDB =& getDB();
45
46     if (isset($aCMDResult['output-type'])) {
47         if (!isset($aRankmap[$aCMDResult['output-type']])) fail('unknown output-type: '.$aCMDResult['output-type']);
48         $iOutputRank = $aRankmap[$aCMDResult['output-type']];
49     } else {
50         $iOutputRank = $aRankmap['street'];
51     }
52
53
54     // Preferred language
55     $oParams = new Nominatim\ParameterParser();
56     if (!isset($aCMDResult['language'])) $aCMDResult['language'] = 'xx';
57     $aLangPrefOrder = $oParams->getPreferredLanguages($aCMDResult['language']);
58     $sLanguagePrefArraySQL = 'ARRAY['.join(',', array_map('getDBQuoted', $aLangPrefOrder)).']';
59
60     // output formatting: build up a lookup table that maps address ranks to columns
61     $aColumnMapping = array();
62     $iNumCol = 0;
63     if (!isset($aCMDResult['output-format'])) $aCMDResult['output-format'] = 'street;suburb;city;county;state;country';
64     foreach (preg_split('/\s*;\s*/', $aCMDResult['output-format']) as $sColumn) {
65         $bHasData = false;
66         foreach (preg_split('/\s*,\s*/', $sColumn) as $sRank) {
67             if ($sRank == 'postcode' || $sRank == 'placeid') {
68                 $aColumnMapping[$sRank] = $iNumCol;
69                 $bHasData = true;
70             } elseif (isset($aRankmap[$sRank])) {
71                 $iRank = $aRankmap[$sRank];
72                 if ($iRank <= $iOutputRank) {
73                     $aColumnMapping[(string)$iRank] = $iNumCol;
74                     $bHasData = true;
75                 }
76             }
77         }
78         if ($bHasData) $iNumCol++;
79     }
80
81     // build the query for objects
82     $sPlacexSQL = 'select min(place_id) as place_id, ';
83     $sPlacexSQL .= 'array_agg(place_id) as place_ids, ';
84     $sPlacexSQL .= 'country_code as cc, ';
85     $sPlacexSQL .= 'postcode, ';
86     // get the address places excluding postcodes
87     $sPlacexSQL .= 'array(select address_place_id from place_addressline a';
88     $sPlacexSQL .= ' where a.place_id = placex.place_id and isaddress';
89     $sPlacexSQL .= '  and address_place_id != placex.place_id';
90     $sPlacexSQL .= '  and not cached_rank_address in (5,11)';
91     $sPlacexSQL .= '  and cached_rank_address > 2 order by cached_rank_address)';
92     $sPlacexSQL .= ' as address';
93     $sPlacexSQL .= ' from placex where name is not null and linked_place_id is null';
94
95     $sPlacexSQL .= ' and rank_address = '.$iOutputRank;
96
97     if (isset($aCMDResult['restrict-to-country'])) {
98         $sPlacexSQL .= ' and country_code = '.getDBQuoted($aCMDResult['restrict-to-country']);
99     }
100
101     // restriction to parent place id
102     $sParentId = false;
103     $sOsmType = false;
104
105     if (isset($aCMDResult['restrict-to-osm-node'])) {
106         $sOsmType = 'N';
107         $sOsmId = $aCMDResult['restrict-to-osm-node'];
108     }
109     if (isset($aCMDResult['restrict-to-osm-way'])) {
110         $sOsmType = 'W';
111         $sOsmId = $aCMDResult['restrict-to-osm-way'];
112     }
113     if (isset($aCMDResult['restrict-to-osm-relation'])) {
114         $sOsmType = 'R';
115         $sOsmId = $aCMDResult['restrict-to-osm-relation'];
116     }
117     if ($sOsmType) {
118         $sSQL = 'select place_id from placex where';
119         $sSQL .= ' osm_type = '.getDBQuoted($sOsmType);
120         $sSQL .= ' and osm_id = '.$sOsmId;
121         $sParentId = $oDB->getOne($sSQL);
122         if (PEAR::isError($sParentId)) fail(pg_last_error($oDB->connection));
123         if (!$sParentId) fail('Could not find place '.$sOsmType.' '.$sOsmId);
124     }
125     if ($sParentId) {
126         $sPlacexSQL .= ' and place_id in (select place_id from place_addressline where address_place_id = '.$sParentId.' and isaddress)';
127     }
128
129     $sPlacexSQL .= " group by name->'name', address, postcode, country_code, placex.place_id";
130
131     // Iterate over placeids
132     // to get further hierarchical information
133     //var_dump($sPlacexSQL);
134     $aRes =& $oDB->query($sPlacexSQL);
135     if (PEAR::isError($aRes)) fail(pg_last_error($oDB->connection));
136     $fOutstream = fopen('php://output', 'w');
137     while ($aRes->fetchInto($aRow)) {
138     //var_dump($aRow);
139         $iPlaceID = $aRow['place_id'];
140         $sSQL = "select rank_address,get_name_by_language(name,$sLanguagePrefArraySQL) as localname from get_addressdata($iPlaceID, -1)";
141         $sSQL .= ' WHERE isaddress';
142         $sSQL .= ' order by rank_address desc,isaddress desc';
143         $aAddressLines = $oDB->getAll($sSQL);
144         if (PEAR::IsError($aAddressLines)) fail(pg_last_error($oDB->connection));
145
146
147         $aOutput = array_fill(0, $iNumCol, '');
148         // output address parts
149         foreach ($aAddressLines as $aAddress) {
150             if (isset($aColumnMapping[$aAddress['rank_address']])) {
151                 $aOutput[$aColumnMapping[$aAddress['rank_address']]] = $aAddress['localname'];
152             }
153         }
154         // output postcode
155         if (isset($aColumnMapping['postcode'])) {
156             if ($aCMDResult['output-all-postcodes']) {
157                 $sSQL = 'select array_agg(px.postcode) from placex px join place_addressline pa ';
158                 $sSQL .= 'on px.place_id = pa.address_place_id ';
159                 $sSQL .= 'where pa.cached_rank_address in (5,11) ';
160                 $sSQL .= 'and pa.place_id in (select place_id from place_addressline where address_place_id in ('.substr($aRow['place_ids'], 1, -1).')) ';
161                 $sSQL .= 'group by postcode order by count(*) desc limit 1';
162                 $sRes = $oDB->getOne($sSQL);
163                 if (PEAR::IsError($sRes)) fail(pg_last_error($oDB->connection));
164                 $aOutput[$aColumnMapping['postcode']] = substr($sRes, 1, -1);
165             } else {
166                 $aOutput[$aColumnMapping['postcode']] = $aRow['postcode'];
167             }
168         }
169         if (isset($aColumnMapping['placeid'])) {
170             $aOutput[$aColumnMapping['placeid']] = substr($aRow['place_ids'], 1, -1);
171         }
172         fputcsv($fOutstream, $aOutput);
173     }
174     fclose($fOutstream);