6 * Operators describing special searches.
8 abstract final class Operator
10 /// No operator selected.
12 /// Search for POI of the given type.
14 /// Search for POIs near the given place.
16 /// Search for POIS in the given place.
18 /// Search for POIS named as given.
20 /// Search for postcodes.
25 * Description of a single interpretation of a search query.
27 class SearchDescription
29 /// Ranking how well the description fits the query.
30 private $iSearchRank = 0;
31 /// Country code of country the result must belong to.
32 private $sCountryCode = '';
33 /// List of word ids making up the name of the object.
34 private $aName = array();
35 /// List of word ids making up the address of the object.
36 private $aAddress = array();
37 /// Subset of word ids of full words making up the address.
38 private $aFullNameAddress = array();
39 /// List of word ids that appear in the name but should be ignored.
40 private $aNameNonSearch = array();
41 /// List of word ids that appear in the address but should be ignored.
42 private $aAddressNonSearch = array();
43 /// Kind of search for special searches, see Nominatim::Operator.
44 private $iOperator = Operator::NONE;
45 /// Class of special feature to search for.
47 /// Type of special feature to search for.
49 /// Housenumber of the object.
50 private $sHouseNumber = '';
51 /// Postcode for the object.
52 private $sPostcode = '';
53 /// Geographic search area.
54 private $oNearPoint = false;
56 // Temporary values used while creating the search description.
58 /// Index of phrase currently processed
59 private $iNamePhrase = -1;
61 public function getRank()
63 return $this->iSearchRank;
66 public function getPostCode()
68 return $this->sPostcode;
72 * Set the geographic search radius.
74 public function setNear(&$oNearPoint)
76 $this->oNearPoint = $oNearPoint;
79 public function setPoiSearch($iOperator, $sClass, $sType)
81 $this->iOperator = $iOperator;
82 $this->sClass = $sClass;
83 $this->sType = $sType;
87 * Check if name or address for the search are specified.
89 public function isNamedSearch()
91 return sizeof($this->aName) > 0 || sizeof($this->aAddress) > 0;
95 * Check if only a country is requested.
97 public function isCountrySearch()
99 return $this->sCountryCode && sizeof($this->aName) == 0
100 && !$this->iOperator && !$this->oNear;
104 * Check if a search near a geographic location is requested.
106 public function isNearSearch()
108 return (bool) $this->oNear;
111 public function isPoiSearch()
113 return (bool) $this->sClass;
116 public function looksLikeFullAddress()
118 return sizeof($this->aName)
119 && (sizeof($this->aAddress || $this->sCountryCode))
120 && preg_match('/[0-9]+/', $this->sHouseNumber);
123 public function isOperator($iType)
125 return $this->iOperator == $iType;
128 public function hasHouseNumber()
130 return (bool) $this->sHouseNumber;
133 public function poiTable()
135 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
138 public function addressArraySQL()
140 return 'ARRAY['.join(',', $this->aAddress).']';
142 public function nameArraySQL()
144 return 'ARRAY['.join(',', $this->aName).']';
147 public function countryCodeSQL($sVar, $sCountryList)
149 if ($this->sCountryCode) {
150 return $sVar.' = \''.$this->sCountryCode."'";
153 return $sVar.' in ('.$this->sCountryCode.')';
159 public function hasOperator()
161 return $this->iOperator != Operator::NONE;
165 * Extract special terms from the query, amend the search
166 * and return the shortended query.
168 * Only the first special term found will be used but all will
169 * be removed from the query.
171 public function extractKeyValuePairs($sQuery)
173 // Search for terms of kind [<key>=<value>].
175 '/\\[([\\w_]*)=([\\w_]*)\\]/',
181 foreach ($aSpecialTermsRaw as $aTerm) {
182 $sQuery = str_replace($aTerm[0], ' ', $sQuery);
183 if (!$this->hasOperator()) {
184 $this->setPoiSearch(Operator::TYPE, $aTerm[1], $aTerm[2]);
191 public function queryCountry(&$oDB, $sViewboxSQL)
193 $sSQL = 'SELECT place_id FROM placex ';
194 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
195 $sSQL .= ' AND rank_search = 4';
197 $sSQL .= " AND ST_Intersects($sViewboxSQL, geometry)";
199 $sSQL .= " ORDER BY st_area(geometry) DESC LIMIT 1";
201 if (CONST_Debug) var_dump($sSQL);
203 return chksql($oDB->getCol($sSQL));
206 public function queryNearbyPoi(&$oDB, $sCountryList, $sViewboxSQL, $sViewboxCentreSQL, $sExcludeSQL, $iLimit)
208 if (!$this->sClass) {
212 $sPoiTable = $this->poiTable();
214 $sSQL = 'SELECT count(*) FROM pg_tables WHERE tablename = \''.$sPoiTable."'";
215 if (chksql($oDB->getOne($sSQL))) {
216 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
218 $sSQL .= ' JOIN placex USING (place_id)';
220 if ($this->oNearPoint) {
221 $sSQL .= ' WHERE '.$this->oNearPoint->withinSQL('ct.centroid');
223 $sSQL .= " WHERE ST_Contains($sViewboxSQL, ct.centroid)";
226 $sSQL .= " AND country_code in ($sCountryList)";
229 $sSQL .= ' AND place_id not in ('.$sExcludeSQL.')';
231 if ($sViewboxCentreSQL) {
232 $sSQL .= " ORDER BY ST_Distance($sViewboxCentreSQL, ct.centroid) ASC";
233 } elseif ($this->oNearPoint) {
234 $sSQL .= ' ORDER BY '.$this->oNearPoint->distanceSQL('ct.centroid').' ASC';
236 $sSQL .= " limit $iLimit";
237 if (CONST_Debug) var_dump($sSQL);
238 return chksql($this->oDB->getCol($sSQL));
241 if ($this->oNearPoint) {
242 $sSQL = 'SELECT place_id FROM placex WHERE ';
243 $sSQL .= 'class=\''.$this->sClass."' and type='".$this->sType."'";
244 $sSQL .= ' AND '.$this->oNearPoint->withinSQL('geometry');
245 $sSQL .= ' AND linked_place_id is null';
247 $sSQL .= " AND country_code in ($sCountryList)";
249 $sSQL .= ' ORDER BY '.$this->oNearPoint->distanceSQL('centroid')." ASC";
250 $sSQL .= " LIMIT $iLimit";
251 if (CONST_Debug) var_dump($sSQL);
252 return chksql($this->oDB->getCol($sSQL));
258 public function queryPostcode(&$oDB, $sCountryList, $iLimit)
260 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
262 if (sizeof($this->aAddress)) {
263 $sSQL .= ', search_name s ';
264 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
265 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
266 $sSQL .= ' @> '.$this->addressArraySQL().' AND ';
271 $sSQL .= "p.postcode = '".pg_escape_string(reset($this->$aName))."'";
272 $sCountryTerm = $this->countryCodeSQL('p.country_code', $sCountryList);
274 $sSQL .= ' AND '.$sCountyTerm;
276 $sSQL .= " LIMIT $iLimit";
278 if (CONST_Debug) var_dump($sSQL);
280 return chksql($this->oDB->getCol($sSQL));
283 public function queryNamedPlace(&$oDB, $aWordFrequencyScores, $sCountryList, $iMinAddressRank, $iMaxAddressRank, $sExcludeSQL, $sViewboxSmall, $sViewboxLarge, $iLimit)
288 if ($this->sHouseNumber && sizeof($this->aAddress)) {
289 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
291 $aOrder[0] .= 'EXISTS(';
292 $aOrder[0] .= ' SELECT place_id';
293 $aOrder[0] .= ' FROM placex';
294 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
295 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
296 $aOrder[0] .= ' LIMIT 1';
298 // also housenumbers from interpolation lines table are needed
299 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
300 $iHouseNumber = intval($this->sHouseNumber);
301 $aOrder[0] .= 'OR EXISTS(';
302 $aOrder[0] .= ' SELECT place_id ';
303 $aOrder[0] .= ' FROM location_property_osmline ';
304 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
305 $aOrder[0] .= ' AND startnumber is not NULL';
306 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
307 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
308 $aOrder[0] .= ' LIMIT 1';
311 $aOrder[0] .= ') DESC';
314 if (sizeof($this->aName)) {
315 $aTerms[] = 'name_vector @> '.$this->nameArraySQL();
317 if (sizeof($this->aAddress)) {
318 // For infrequent name terms disable index usage for address
319 if (CONST_Search_NameOnlySearchFrequencyThreshold
320 && sizeof($this->aName) == 1
321 && $aWordFrequencyScores[$this->aName[reset($this->aName)]]
322 < CONST_Search_NameOnlySearchFrequencyThreshold
324 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.$this->addressArraySQL();
326 $aTerms[] = 'nameaddress_vector @> '.$this->addressArraySQL();
330 $sCountryTerm = $this->countryCodeSQL('p.country_code', $sCountryList);
332 $aTerms[] = $sCountryTerm;
335 if ($this->sHouseNumber) {
336 $aTerms[] = "address_rank between 16 and 27";
337 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
338 if ($iMinAddressRank > 0) {
339 $aTerms[] = "address_rank >= ".$iMinAddressRank;
341 if ($iMaxAddressRank < 30) {
342 $aTerms[] = "address_rank <= ".$iMaxAddressRank;
346 if ($this->oNearPoint) {
347 $aTerms[] = $this->oNearPoint->withinSQL('centroid');
348 $aOrder[] = $this->oNearPoint->distanceSQL('centroid');
349 } elseif ($this->sPostcode) {
350 if (!sizeof($this->aAddress)) {
351 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
353 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
358 $aTerms = 'place_id not in ('.$sExcludeSQL.')';
361 if ($sViewboxSmall) {
362 $aTerms[] = 'centroid && '.$sViewboxSmall;
365 if ($this->oNearPoint) {
366 $aOrder[] = $this->oNearPoint->distanceSQL('centroid');
369 if ($this->sHouseNumber) {
370 $sImportanceSQL = '- abs(26 - address_rank) + 3';
372 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75-(search_rank::float/40) ELSE importance END)';
374 if ($sViewboxSmall) {
375 $sImportanceSQL .= " * CASE WHEN ST_Contains($sViewboxSmall, centroid) THEN 1 ELSE 0.5 END";
377 if ($sViewboxLarge) {
378 $sImportanceSQL .= " * CASE WHEN ST_Contains($sViewboxLarge, centroid) THEN 1 ELSE 0.5 END";
380 $aOrder[] = "$sImportanceSQL DESC";
382 if (sizeof($this->aFullNameAddress)) {
383 $sExactMatchSQL = ' ( ';
384 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
385 $sExactMatchSQL .= ' SELECT unnest(ARRAY['.join($this->aFullNameAddress, ",").']) ';
386 $sExactMatchSQL .= ' INTERSECT ';
387 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
388 $sExactMatchSQL .= ' ) s';
389 $sExactMatchSQL .= ') as exactmatch';
390 $aOrder[] = 'exactmatch DESC';
392 $sExactMatchSQL = '0::int as exactmatch';
395 if ($this->sHouseNumber || $this->sClass) {
399 if (sizeof($aTerms)) {
400 $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
401 $sSQL .= ' FROM search_name';
402 $sSQL .= ' WHERE '.join(' and ', $aTerms);
403 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
404 $sSQL .= ' LIMIT '.$iLimit;
406 if (CONST_Debug) var_dump($sSQL);
409 $this->oDB->getAll($sSQL),
410 "Could not get places for search terms."
418 public function queryHouseNumber(&$oDB, $aRoadPlaceIDs, $sExcludeSQL, $iLimit)
420 $sPlaceIDs = join(',', $aRoadPlaceIDs);
422 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
423 $sSQL = 'SELECT place_id FROM placex ';
424 $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
425 $sSQL .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
427 $sSQL .= ' AND place_id not in ('.$sExcludeSQL.')';
429 $sSQL .= " LIMIT $iLimit";
431 if (CONST_Debug) var_dump($sSQL);
433 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
435 if (sizeof($aPlaceIDs)) {
436 return array('aPlaceIDs' => $aPlaceIDs, 'iHouseNumber' => -1);
439 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
440 $iHousenumber = intval($this->sHouseNumber);
441 if ($bIsIntHouseNumber) {
442 // if nothing found, search in the interpolation line table
443 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
444 $sSQL .= ' WHERE startnumber is not NULL';
445 $sSQL .= ' AND parent_place_id in ('.$sPlaceIDs.') AND (';
446 if ($iHousenumber % 2 == 0) {
447 // If housenumber is even, look for housenumber in streets
448 // with interpolationtype even or all.
449 $sSQL .= "interpolationtype='even'";
451 // Else look for housenumber with interpolationtype odd or all.
452 $sSQL .= "interpolationtype='odd'";
454 $sSQL .= " or interpolationtype='all') and ";
455 $sSQL .= $iHousenumber.">=startnumber and ";
456 $sSQL .= $iHousenumber."<=endnumber";
459 $sSQL .= ' AND place_id not in ('.$sExcludeSQL.')';
461 $sSQL .= " limit $iLimit";
463 if (CONST_Debug) var_dump($sSQL);
465 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
467 if (sizeof($aPlaceIDs)) {
468 return array('aPlaceIDs' => $aPlaceIDs, 'iHouseNumber' => $iHousenumber);
472 // If nothing found try the aux fallback table
473 if (CONST_Use_Aux_Location_data) {
474 $sSQL = 'SELECT place_id FROM location_property_aux';
475 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
476 $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
478 $sSQL .= " AND place_id not in ($sExcludeSQL)";
480 $sSQL .= " limit $iLimit";
482 if (CONST_Debug) var_dump($sSQL);
484 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
486 if (sizeof($aPlaceIDs)) {
487 return array('aPlaceIDs' => $aPlaceIDs, 'iHouseNumber' => -1);
491 // If nothing found then search in Tiger data (location_property_tiger)
492 if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber) {
493 $sSQL = 'SELECT distinct place_id FROM location_property_tiger';
494 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
495 if ($iHousenumber % 2 == 0) {
496 $sSQL .= "interpolationtype='even'";
498 $sSQL .= "interpolationtype='odd'";
500 $sSQL .= " or interpolationtype='all') and ";
501 $sSQL .= $iHousenumber.">=startnumber and ";
502 $sSQL .= $iHousenumber."<=endnumber";
505 $sSQL .= ' AND place_id not in ('.$sExcludeSQL.')';
507 $sSQL .= " limit $iLimit";
509 if (CONST_Debug) var_dump($sSQL);
511 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
513 if (sizeof($aPlaceIDs)) {
514 return array('aPlaceIDs' => $aPlaceIDs, 'iHouseNumber' => $iHousenumber);
522 public function queryPoiByOperator(&$oDB, $aParentIDs, $sExcludeSQL, $iLimit)
524 $sPlaceIDs = join(',', $aParentIDs);
525 $aClassPlaceIDs = array();
527 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
528 // If they were searching for a named class (i.e. 'Kings Head pub')
529 // then we might have an extra match
530 $sSQL = 'SELECT place_id FROM placex ';
531 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
532 $sSQL .= " AND class='".$this->sClass."' ";
533 $sSQL .= " AND type='".$this->sType."'";
534 $sSQL .= " AND linked_place_id is null";
535 $sSQL .= " ORDER BY rank_search ASC ";
536 $sSQL .= " LIMIT $iLimit";
538 if (CONST_Debug) var_dump($sSQL);
540 $aClassPlaceIDs = chksql($this->oDB->getCol($sSQL));
543 // NEAR and IN are handled the same
544 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
545 $sClassTable = $this->poiTable();
546 $sSQL = "SELECT count(*) FROM pg_tables WHERE tablename = '$sClassTable'";
547 $bCacheTable = (bool) chksql($this->oDB->getOne($sSQL));
549 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
550 if (CONST_Debug) var_dump($sSQL);
551 $iMaxRank = (int)chksql($this->oDB->getOne($sSQL));
553 // For state / country level searches the normal radius search doesn't work very well
555 if ($iMaxRank < 9 && $bCacheTable) {
556 // Try and get a polygon to search in instead
557 $sSQL = 'SELECT geometry FROM placex';
558 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
559 $sSQL .= " AND rank_search < $iMaxRank + 5";
560 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
561 $sSQL .= " ORDER BY rank_search ASC ";
563 if (CONST_Debug) var_dump($sSQL);
564 $sPlaceGeom = chksql($this->oDB->getOne($sSQL));
571 $sSQL = 'SELECT place_id FROM placex';
572 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
573 if (CONST_Debug) var_dump($sSQL);
574 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
575 $sPlaceIDs = join(',', $aPlaceIDs);
578 if ($sPlaceIDs || $sPlaceGeom) {
581 // More efficient - can make the range bigger
585 if ($this->oNearPoint) {
586 $sOrderBySQL = $this->oNearPoint->distanceSQL('l.centroid');
587 } elseif ($sPlaceIDs) {
588 $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
589 } elseif ($sPlaceGeom) {
590 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
593 $sSQL = 'SELECT distinct i.place_id';
595 $sSQL .= ', i.order_term';
597 $sSQL .= ' from (SELECT l.place_id';
599 $sSQL .= ','.$sOrderBySQL.' as order_term';
601 $sSQL .= ' from '.$sClassTable.' as l';
604 $sSQL .= ",placex as f WHERE ";
605 $sSQL .= "f.place_id in ($sPlaceIDs) ";
606 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
607 } elseif ($sPlaceGeom) {
608 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
612 $sSQL .= ' AND l.place_id not in ('.$sExcludeSQL.')';
614 $sSQL .= 'limit 300) i ';
616 $sSQL .= 'order by order_term asc';
618 $sSQL .= " limit $iLimit";
620 if (CONST_Debug) var_dump($sSQL);
622 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
624 if ($this->oNearPoint) {
625 $fRange = $this->oNearPoint->radius();
629 if ($this->oNearPoint) {
630 $sOrderBySQL = $this->oNearPoint->distanceSQL('l.geometry');
632 $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
635 $sSQL = 'SELECT distinct l.place_id';
637 $sSQL .= ','.$sOrderBySQL.' as orderterm';
639 $sSQL .= ' FROM placex as l, placex as f';
640 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
641 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
642 $sSQL .= " AND l.class='".$this->sClass."'";
643 $sSQL .= " AND l.type='".$this->sType."'";
645 $sSQL .= " AND l.place_id not in (".$sExcludeSQL.")";
648 $sSQL .= "ORDER BY orderterm ASC";
650 $sSQL .= " limit $iLimit";
652 if (CONST_Debug) var_dump($sSQL);
654 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
659 return $aClassPlaceIDs;