2 #-----------------------------------------------------------------------------
3 # nominatim - [description]
4 #-----------------------------------------------------------------------------
6 # Indexing tool for the Nominatim database.
8 # Based on C version by Brian Quinion
10 # This program is free software; you can redistribute it and/or
11 # modify it under the terms of the GNU General Public License
12 # as published by the Free Software Foundation; either version 2
13 # of the License, or (at your option) any later version.
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with this program; if not, write to the Free Software
22 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 #-----------------------------------------------------------------------------
25 from argparse import ArgumentParser, RawDescriptionHelpFormatter, ArgumentTypeError
30 from datetime import datetime
32 from psycopg2.extras import wait_select
35 log = logging.getLogger()
37 def make_connection(options, asynchronous=False):
38 return psycopg2.connect(dbname=options.dbname, user=options.user,
39 password=options.password, host=options.host,
40 port=options.port, async_=asynchronous)
42 class IndexingThread(object):
44 def __init__(self, thread_num, options):
45 log.debug("Creating thread {}".format(thread_num))
46 self.thread_num = thread_num
47 self.conn = make_connection(options, asynchronous=True)
50 self.cursor = self.conn.cursor()
51 self.perform("SET lc_messages TO 'C'")
54 self.current_query = None
57 wait_select(self.conn)
58 self.current_query = None
60 def perform(self, sql, args=None):
61 self.current_query = sql
62 self.cursor.execute(sql, args)
65 if self.current_query is None:
69 if self.conn.poll() == psycopg2.extensions.POLL_OK:
70 self.current_query = None
72 except psycopg2.extensions.TransactionRollbackError as e:
74 raise RuntimeError("Postgres exception has no error code")
75 if e.pgcode == '40P01':
76 log.info("Deadlock detected, retry.")
77 self.cursor.execute(sql)
83 class Indexer(object):
85 def __init__(self, options):
86 self.options = options
87 self.conn = make_connection(options)
90 self.poll = select.poll()
91 for i in range(options.threads):
92 t = IndexingThread(i, options)
93 self.threads.append(t)
94 self.poll.register(t.conn.fileno(), select.EPOLLIN)
98 log.info("Starting indexing rank ({} to {}) using {} threads".format(
99 self.options.minrank, self.options.maxrank,
100 self.options.threads))
102 for rank in range(self.options.minrank, 30):
103 self.index(RankRunner(rank))
105 if self.options.maxrank >= 30:
106 self.index(InterpolationRunner())
107 self.index(RankRunner(30))
109 def index(self, obj):
110 log.info("Starting {}".format(obj.name()))
112 cur = self.conn.cursor(name="main")
113 cur.execute(obj.sql_index_sectors())
118 log.debug("Total number of rows; {}".format(total_tuples))
120 cur.scroll(0, mode='absolute')
123 rank_start_time = datetime.now()
127 # Should we do the remaining ones together?
128 do_all = total_tuples - done_tuples < len(self.threads) * 1000
130 pcur = self.conn.cursor(name='places')
133 pcur.execute(obj.sql_nosector_places())
135 pcur.execute(obj.sql_sector_places(), (sector, ))
139 log.debug("Processing place {}".format(place_id))
140 thread = self.find_free_thread()
142 thread.perform(obj.sql_index_place(), (place_id,))
152 for t in self.threads:
155 rank_end_time = datetime.now()
156 diff_seconds = (rank_end_time-rank_start_time).total_seconds()
158 log.info("Done {} in {} @ {} per second - FINISHED {}\n".format(
159 done_tuples, int(diff_seconds),
160 done_tuples/diff_seconds, obj.name()))
162 def find_free_thread(self):
164 for t in self.threads:
170 assert(False, "Unreachable code")
172 class RankRunner(object):
174 def __init__(self, rank):
178 return "rank {}".format(self.rank)
180 def sql_index_sectors(self):
181 return """SELECT geometry_sector, count(*) FROM placex
182 WHERE rank_search = {} and indexed_status > 0
183 GROUP BY geometry_sector
184 ORDER BY geometry_sector""".format(self.rank)
186 def sql_nosector_places(self):
187 return """SELECT place_id FROM placex
188 WHERE indexed_status > 0 and rank_search = {}
189 ORDER BY geometry_sector""".format(self.rank)
191 def sql_sector_places(self):
192 return """SELECT place_id FROM placex
193 WHERE indexed_status > 0 and geometry_sector = %s
194 ORDER BY geometry_sector"""
196 def sql_index_place(self):
197 return "UPDATE placex SET indexed_status = 0 WHERE place_id = %s"
200 class InterpolationRunner(object):
203 return "interpolation lines (location_property_osmline)"
205 def sql_index_sectors(self):
206 return """SELECT geometry_sector, count(*) FROM location_property_osmline
207 WHERE indexed_status > 0
208 GROUP BY geometry_sector
209 ORDER BY geometry_sector"""
211 def sql_nosector_places(self):
212 return """SELECT place_id FROM location_property_osmline
213 WHERE indexed_status > 0
214 ORDER BY geometry_sector"""
216 def sql_sector_places(self):
217 return """SELECT place_id FROM location_property_osmline
218 WHERE indexed_status > 0 and geometry_sector = %s
219 ORDER BY geometry_sector"""
221 def sql_index_place(self):
222 return """UPDATE location_property_osmline
223 SET indexed_status = 0 WHERE place_id = %s"""
226 def nominatim_arg_parser():
227 """ Setup the command-line parser for the tool.
230 return re.sub("\s\s+" , " ", s)
232 p = ArgumentParser(description=__doc__,
233 formatter_class=RawDescriptionHelpFormatter)
235 p.add_argument('-d', '--database',
236 dest='dbname', action='store', default='nominatim',
237 help='Name of the PostgreSQL database to connect to.')
238 p.add_argument('-U', '--username',
239 dest='user', action='store',
240 help='PostgreSQL user name.')
241 p.add_argument('-W', '--password',
242 dest='password_prompt', action='store_true',
243 help='Force password prompt.')
244 p.add_argument('-H', '--host',
245 dest='host', action='store',
246 help='PostgreSQL server hostname or socket location.')
247 p.add_argument('-P', '--port',
248 dest='port', action='store',
249 help='PostgreSQL server port')
250 p.add_argument('-r', '--minrank',
251 dest='minrank', type=int, metavar='RANK', default=0,
252 help='Minimum/starting rank.')
253 p.add_argument('-R', '--maxrank',
254 dest='maxrank', type=int, metavar='RANK', default=30,
255 help='Maximum/finishing rank.')
256 p.add_argument('-t', '--threads',
257 dest='threads', type=int, metavar='NUM', default=1,
258 help='Number of threads to create for indexing.')
259 p.add_argument('-v', '--verbose',
260 dest='loglevel', action='count', default=0,
261 help='Increase verbosity')
265 if __name__ == '__main__':
266 logging.basicConfig(stream=sys.stderr, format='%(levelname)s: %(message)s')
268 options = nominatim_arg_parser().parse_args(sys.argv[1:])
270 log.setLevel(max(3 - options.loglevel, 0) * 10)
272 options.password = None
273 if options.password_prompt:
274 password = getpass.getpass("Database password: ")
275 options.password = password
277 Indexer(options).run()