2 Main work horse for indexing (computing addresses) the database.
4 # pylint: disable=C0111
10 from .progress import ProgressLogger
11 from ..db.async_connection import DBConnection
13 LOG = logging.getLogger()
16 """ Returns SQL commands for indexing one rank within the placex table.
19 def __init__(self, rank):
23 return "rank {}".format(self.rank)
25 def sql_count_objects(self):
26 return """SELECT count(*) FROM placex
27 WHERE rank_address = {} and indexed_status > 0
30 def sql_get_objects(self):
31 return """SELECT place_id FROM placex
32 WHERE indexed_status > 0 and rank_address = {}
33 ORDER BY geometry_sector""".format(self.rank)
36 def sql_index_place(ids):
37 return "UPDATE placex SET indexed_status = 0 WHERE place_id IN ({})"\
38 .format(','.join((str(i) for i in ids)))
41 class InterpolationRunner:
42 """ Returns SQL commands for indexing the address interpolation table
43 location_property_osmline.
48 return "interpolation lines (location_property_osmline)"
51 def sql_count_objects():
52 return """SELECT count(*) FROM location_property_osmline
53 WHERE indexed_status > 0"""
56 def sql_get_objects():
57 return """SELECT place_id FROM location_property_osmline
58 WHERE indexed_status > 0
59 ORDER BY geometry_sector"""
62 def sql_index_place(ids):
63 return """UPDATE location_property_osmline
64 SET indexed_status = 0 WHERE place_id IN ({})"""\
65 .format(','.join((str(i) for i in ids)))
68 """ Returns SQL commands for indexing the administrative boundaries
72 def __init__(self, rank):
76 return "boundaries rank {}".format(self.rank)
78 def sql_count_objects(self):
79 return """SELECT count(*) FROM placex
80 WHERE indexed_status > 0
82 AND class = 'boundary' and type = 'administrative'""".format(self.rank)
84 def sql_get_objects(self):
85 return """SELECT place_id FROM placex
86 WHERE indexed_status > 0 and rank_search = {}
87 and class = 'boundary' and type = 'administrative'
88 ORDER BY partition, admin_level""".format(self.rank)
91 def sql_index_place(ids):
92 return "UPDATE placex SET indexed_status = 0 WHERE place_id IN ({})"\
93 .format(','.join((str(i) for i in ids)))
96 """ Main indexing routine.
99 def __init__(self, dsn, num_threads):
100 self.conn = psycopg2.connect(dsn)
101 self.threads = [DBConnection(dsn) for _ in range(num_threads)]
103 def index_boundaries(self, minrank, maxrank):
104 LOG.warning("Starting indexing boundaries using %s threads",
107 for rank in range(max(minrank, 5), min(maxrank, 26)):
108 self.index(BoundaryRunner(rank))
110 def index_by_rank(self, minrank, maxrank):
111 """ Run classic indexing by rank.
113 maxrank = min(maxrank, 30)
114 LOG.warning("Starting indexing rank (%i to %i) using %i threads",
115 minrank, maxrank, len(self.threads))
117 for rank in range(max(1, minrank), maxrank):
118 self.index(RankRunner(rank))
121 self.index(RankRunner(0))
122 self.index(InterpolationRunner(), 20)
123 self.index(RankRunner(30), 20)
125 self.index(RankRunner(maxrank))
127 def index(self, obj, batch=1):
128 """ Index a single rank or table. `obj` describes the SQL to use
129 for indexing. `batch` describes the number of objects that
130 should be processed with a single SQL statement
132 LOG.warning("Starting %s (using batch size %s)", obj.name(), batch)
134 cur = self.conn.cursor()
135 cur.execute(obj.sql_count_objects())
137 total_tuples = cur.fetchone()[0]
138 LOG.debug("Total number of rows: %i", total_tuples)
142 progress = ProgressLogger(obj.name(), total_tuples)
145 cur = self.conn.cursor(name='places')
146 cur.execute(obj.sql_get_objects())
148 next_thread = self.find_free_thread()
150 places = [p[0] for p in cur.fetchmany(batch)]
154 LOG.debug("Processing places: %s", str(places))
155 thread = next(next_thread)
157 thread.perform(obj.sql_index_place(places))
158 progress.add(len(places))
162 for thread in self.threads:
167 def find_free_thread(self):
168 """ Generator that returns the next connection that is free for
180 # refresh the connections occasionaly to avoid potential
181 # memory leaks in Postgresql.
182 if command_stat > 100000:
183 for thread in self.threads:
184 while not thread.is_done():
190 ready, _, _ = select.select(self.threads, [], [])
192 assert False, "Unreachable code"