5 require_once(CONST_LibDir.'/SpecialSearchOperator.php');
6 require_once(CONST_LibDir.'/SearchContext.php');
7 require_once(CONST_LibDir.'/Result.php');
10 * Description of a single interpretation of a search query.
12 class SearchDescription
14 /// Ranking how well the description fits the query.
15 private $iSearchRank = 0;
16 /// Country code of country the result must belong to.
17 private $sCountryCode = '';
18 /// List of word ids making up the name of the object.
19 private $aName = array();
20 /// True if the name is rare enough to force index use on name.
21 private $bRareName = false;
22 /// List of word ids making up the address of the object.
23 private $aAddress = array();
24 /// List of word ids that appear in the name but should be ignored.
25 private $aNameNonSearch = array();
26 /// List of word ids that appear in the address but should be ignored.
27 private $aAddressNonSearch = array();
28 /// Kind of search for special searches, see Nominatim::Operator.
29 private $iOperator = Operator::NONE;
30 /// Class of special feature to search for.
32 /// Type of special feature to search for.
34 /// Housenumber of the object.
35 private $sHouseNumber = '';
36 /// Postcode for the object.
37 private $sPostcode = '';
38 /// Global search constraints.
41 // Temporary values used while creating the search description.
43 /// Index of phrase currently processed.
44 private $iNamePhrase = -1;
47 * Create an empty search description.
49 * @param object $oContext Global context to use. Will be inherited by
50 * all derived search objects.
52 public function __construct($oContext)
54 $this->oContext = $oContext;
58 * Get current search rank.
60 * The higher the search rank the lower the likelihood that the
61 * search is a correct interpretation of the search query.
63 * @return integer Search rank.
65 public function getRank()
67 return $this->iSearchRank;
71 * Make this search a POI search.
73 * In a POI search, objects are not (only) searched by their name
74 * but also by the primary OSM key/value pair (class and type in Nominatim).
76 * @param integer $iOperator Type of POI search
77 * @param string $sClass Class (or OSM tag key) of POI.
78 * @param string $sType Type (or OSM tag value) of POI.
82 public function setPoiSearch($iOperator, $sClass, $sType)
84 $this->iOperator = $iOperator;
85 $this->sClass = $sClass;
86 $this->sType = $sType;
90 * Check if any operator is set.
92 * @return bool True, if this is a special search operation.
94 public function hasOperator()
96 return $this->iOperator != Operator::NONE;
100 * Extract key/value pairs from a query.
102 * Key/value pairs are recognised if they are of the form [<key>=<value>].
103 * If multiple terms of this kind are found then all terms are removed
104 * but only the first is used for search.
106 * @param string $sQuery Original query string.
108 * @return string The query string with the special search patterns removed.
110 public function extractKeyValuePairs($sQuery)
112 // Search for terms of kind [<key>=<value>].
114 '/\\[([\\w_]*)=([\\w_]*)\\]/',
120 foreach ($aSpecialTermsRaw as $aTerm) {
121 $sQuery = str_replace($aTerm[0], ' ', $sQuery);
122 if (!$this->hasOperator()) {
123 $this->setPoiSearch(Operator::TYPE, $aTerm[1], $aTerm[2]);
131 * Check if the combination of parameters is sensible.
133 * @return bool True, if the search looks valid.
135 public function isValidSearch()
137 if (empty($this->aName)) {
138 if ($this->sHouseNumber) {
141 if (!$this->sClass && !$this->sCountryCode) {
149 /////////// Search building functions
153 * Derive new searches by adding a full term to the existing search.
155 * @param object $oSearchTerm Description of the token.
156 * @param bool $bHasPartial True if there are also tokens of partial terms
157 * with the same name.
158 * @param string $sPhraseType Type of phrase the token is contained in.
159 * @param bool $bFirstToken True if the token is at the beginning of the
161 * @param bool $bFirstPhrase True if the token is in the first phrase of
163 * @param bool $bLastToken True if the token is at the end of the query.
165 * @return SearchDescription[] List of derived search descriptions.
167 public function extendWithFullTerm($oSearchTerm, $bHasPartial, $sPhraseType, $bFirstToken, $bFirstPhrase, $bLastToken)
169 $aNewSearches = array();
171 if (($sPhraseType == '' || $sPhraseType == 'country')
172 && is_a($oSearchTerm, '\Nominatim\Token\Country')
174 if (!$this->sCountryCode) {
175 $oSearch = clone $this;
176 $oSearch->iSearchRank++;
177 $oSearch->sCountryCode = $oSearchTerm->sCountryCode;
178 // Country is almost always at the end of the string
179 // - increase score for finding it anywhere else (optimisation)
181 $oSearch->iSearchRank += 5;
183 $aNewSearches[] = $oSearch;
185 } elseif (($sPhraseType == '' || $sPhraseType == 'postalcode')
186 && is_a($oSearchTerm, '\Nominatim\Token\Postcode')
188 if (!$this->sPostcode) {
189 // If we have structured search or this is the first term,
190 // make the postcode the primary search element.
191 if ($this->iOperator == Operator::NONE && $bFirstToken) {
192 $oSearch = clone $this;
193 $oSearch->iSearchRank++;
194 $oSearch->iOperator = Operator::POSTCODE;
195 $oSearch->aAddress = array_merge($this->aAddress, $this->aName);
197 array($oSearchTerm->iId => $oSearchTerm->sPostcode);
198 $aNewSearches[] = $oSearch;
201 // If we have a structured search or this is not the first term,
202 // add the postcode as an addendum.
203 if ($this->iOperator != Operator::POSTCODE
204 && ($sPhraseType == 'postalcode' || !empty($this->aName))
206 $oSearch = clone $this;
207 $oSearch->iSearchRank++;
208 if (strlen($oSearchTerm->sPostcode) < 4) {
209 $oSearch->iSearchRank += 4 - strlen($oSearchTerm->sPostcode);
211 $oSearch->sPostcode = $oSearchTerm->sPostcode;
212 $aNewSearches[] = $oSearch;
215 } elseif (($sPhraseType == '' || $sPhraseType == 'street')
216 && is_a($oSearchTerm, '\Nominatim\Token\HouseNumber')
218 if (!$this->sHouseNumber && $this->iOperator != Operator::POSTCODE) {
219 $oSearch = clone $this;
220 $oSearch->iSearchRank++;
221 $oSearch->sHouseNumber = $oSearchTerm->sToken;
222 // sanity check: if the housenumber is not mainly made
223 // up of numbers, add a penalty
224 if (preg_match('/\\d/', $oSearch->sHouseNumber) === 0
225 || preg_match_all('/[^0-9]/', $oSearch->sHouseNumber, $aMatches) > 2) {
226 $oSearch->iSearchRank++;
228 if (empty($oSearchTerm->iId)) {
229 $oSearch->iSearchRank++;
231 // also must not appear in the middle of the address
232 if (!empty($this->aAddress)
233 || (!empty($this->aAddressNonSearch))
236 $oSearch->iSearchRank++;
238 $aNewSearches[] = $oSearch;
239 // Housenumbers may appear in the name when the place has its own
241 if ($oSearchTerm->iId !== null
242 && ($this->iNamePhrase >= 0 || empty($this->aName))
243 && empty($this->aAddress)
245 $oSearch = clone $this;
246 $oSearch->iSearchRank++;
247 $oSearch->aAddress = $this->aName;
248 $oSearch->bRareName = false;
249 $oSearch->aName = array($oSearchTerm->iId => $oSearchTerm->iId);
250 $aNewSearches[] = $oSearch;
253 } elseif ($sPhraseType == ''
254 && is_a($oSearchTerm, '\Nominatim\Token\SpecialTerm')
256 if ($this->iOperator == Operator::NONE) {
257 $oSearch = clone $this;
258 $oSearch->iSearchRank++;
260 $iOp = $oSearchTerm->iOperator;
261 if ($iOp == Operator::NONE) {
262 if (!empty($this->aName) || $this->oContext->isBoundedSearch()) {
263 $iOp = Operator::NAME;
265 $iOp = Operator::NEAR;
267 $oSearch->iSearchRank += 2;
270 $oSearch->setPoiSearch(
272 $oSearchTerm->sClass,
275 $aNewSearches[] = $oSearch;
277 } elseif ($sPhraseType != 'country'
278 && is_a($oSearchTerm, '\Nominatim\Token\Word')
280 $iWordID = $oSearchTerm->iId;
281 // Full words can only be a name if they appear at the beginning
282 // of the phrase. In structured search the name must forcably in
283 // the first phrase. In unstructured search it may be in a later
284 // phrase when the first phrase is a house number.
285 if (!empty($this->aName) || !($bFirstPhrase || $sPhraseType == '')) {
286 if (($sPhraseType == '' || !$bFirstPhrase) && !$bHasPartial) {
287 $oSearch = clone $this;
288 $oSearch->iSearchRank += 3 * $oSearchTerm->iTermCount;
289 $oSearch->aAddress[$iWordID] = $iWordID;
290 $aNewSearches[] = $oSearch;
292 } else if (empty($this->aNameNonSearch)) {
293 $oSearch = clone $this;
294 $oSearch->iSearchRank++;
295 $oSearch->aName = array($iWordID => $iWordID);
296 if (CONST_Search_NameOnlySearchFrequencyThreshold) {
297 $oSearch->bRareName =
298 $oSearchTerm->iSearchNameCount
299 < CONST_Search_NameOnlySearchFrequencyThreshold;
301 $aNewSearches[] = $oSearch;
305 return $aNewSearches;
309 * Derive new searches by adding a partial term to the existing search.
311 * @param string $sToken Term for the token.
312 * @param object $oSearchTerm Description of the token.
313 * @param bool $bStructuredPhrases True if the search is structured.
314 * @param integer $iPhrase Number of the phrase the token is in.
315 * @param array[] $aFullTokens List of full term tokens with the
318 * @return SearchDescription[] List of derived search descriptions.
320 public function extendWithPartialTerm($sToken, $oSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
322 // Only allow name terms.
323 if (!(is_a($oSearchTerm, '\Nominatim\Token\Word'))) {
327 $aNewSearches = array();
328 $iWordID = $oSearchTerm->iId;
330 if ((!$bStructuredPhrases || $iPhrase > 0)
331 && (!empty($this->aName))
333 $oSearch = clone $this;
334 $oSearch->iSearchRank++;
335 if (preg_match('#^[0-9 ]+$#', $sToken)) {
336 $oSearch->iSearchRank++;
338 if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
339 $oSearch->aAddress[$iWordID] = $iWordID;
341 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
342 if (!empty($aFullTokens)) {
343 $oSearch->iSearchRank++;
346 $aNewSearches[] = $oSearch;
349 if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
350 && ((empty($this->aName) && empty($this->aNameNonSearch)) || $this->iNamePhrase == $iPhrase)
352 $oSearch = clone $this;
353 $oSearch->iSearchRank++;
354 if (empty($this->aName) && empty($this->aNameNonSearch)) {
355 $oSearch->iSearchRank++;
357 if (preg_match('#^[0-9 ]+$#', $sToken)) {
358 $oSearch->iSearchRank++;
360 if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
361 if (empty($this->aName)
362 && CONST_Search_NameOnlySearchFrequencyThreshold
364 $oSearch->bRareName =
365 $oSearchTerm->iSearchNameCount
366 < CONST_Search_NameOnlySearchFrequencyThreshold;
368 $oSearch->bRareName = false;
370 $oSearch->aName[$iWordID] = $iWordID;
372 if (!empty($aFullTokens)) {
373 $oSearch->iSearchRank++;
375 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
377 $oSearch->iNamePhrase = $iPhrase;
378 $aNewSearches[] = $oSearch;
381 return $aNewSearches;
384 /////////// Query functions
388 * Query database for places that match this search.
390 * @param object $oDB Nominatim::DB instance to use.
391 * @param integer $iMinRank Minimum address rank to restrict search to.
392 * @param integer $iMaxRank Maximum address rank to restrict search to.
393 * @param integer $iLimit Maximum number of results.
395 * @return mixed[] An array with two fields: IDs contains the list of
396 * matching place IDs and houseNumber the houseNumber
397 * if appicable or -1 if not.
399 public function query(&$oDB, $iMinRank, $iMaxRank, $iLimit)
404 if ($this->sCountryCode
405 && empty($this->aName)
408 && !$this->oContext->hasNearPoint()
410 // Just looking for a country - look it up
411 if (4 >= $iMinRank && 4 <= $iMaxRank) {
412 $aResults = $this->queryCountry($oDB);
414 } elseif (empty($this->aName) && empty($this->aAddress)) {
415 // Neither name nor address? Then we must be
416 // looking for a POI in a geographic area.
417 if ($this->oContext->isBoundedSearch()) {
418 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
420 } elseif ($this->iOperator == Operator::POSTCODE) {
421 // looking for postcode
422 $aResults = $this->queryPostcode($oDB, $iLimit);
425 // First search for places according to name and address.
426 $aResults = $this->queryNamedPlace(
433 // Now search for housenumber, if housenumber provided. Can be zero.
434 if (($this->sHouseNumber || $this->sHouseNumber === '0') && !empty($aResults)) {
435 // Downgrade the rank of the street results, they are missing
437 foreach ($aResults as $oRes) {
438 if ($oRes->iAddressRank >= 26) {
439 $oRes->iResultRank++;
441 $oRes->iResultRank += 2;
445 $aHnResults = $this->queryHouseNumber($oDB, $aResults);
447 if (!empty($aHnResults)) {
448 foreach ($aHnResults as $oRes) {
449 $aResults[$oRes->iId] = $oRes;
454 // finally get POIs if requested
455 if ($this->sClass && !empty($aResults)) {
456 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
460 Debug::printDebugTable('Place IDs', $aResults);
462 if (!empty($aResults) && $this->sPostcode) {
463 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
465 $sSQL = 'SELECT place_id FROM placex';
466 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
467 $sSQL .= " AND postcode != '".$this->sPostcode."'";
468 Debug::printSQL($sSQL);
469 $aFilteredPlaceIDs = $oDB->getCol($sSQL);
470 if ($aFilteredPlaceIDs) {
471 foreach ($aFilteredPlaceIDs as $iPlaceId) {
472 $aResults[$iPlaceId]->iResultRank++;
482 private function queryCountry(&$oDB)
484 $sSQL = 'SELECT place_id FROM placex ';
485 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
486 $sSQL .= ' AND rank_search = 4';
487 if ($this->oContext->bViewboxBounded) {
488 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
490 $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
492 Debug::printSQL($sSQL);
494 $iPlaceId = $oDB->getOne($sSQL);
498 $aResults[$iPlaceId] = new Result($iPlaceId);
504 private function queryNearbyPoi(&$oDB, $iLimit)
506 if (!$this->sClass) {
510 $aDBResults = array();
511 $sPoiTable = $this->poiTable();
513 if ($oDB->tableExists($sPoiTable)) {
514 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
515 if ($this->oContext->sqlCountryList) {
516 $sSQL .= ' JOIN placex USING (place_id)';
518 if ($this->oContext->hasNearPoint()) {
519 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
520 } elseif ($this->oContext->bViewboxBounded) {
521 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
523 if ($this->oContext->sqlCountryList) {
524 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
526 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
527 if ($this->oContext->sqlViewboxCentre) {
528 $sSQL .= ' ORDER BY ST_Distance(';
529 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
530 } elseif ($this->oContext->hasNearPoint()) {
531 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
533 $sSQL .= " LIMIT $iLimit";
534 Debug::printSQL($sSQL);
535 $aDBResults = $oDB->getCol($sSQL);
538 if ($this->oContext->hasNearPoint()) {
539 $sSQL = 'SELECT place_id FROM placex WHERE ';
540 $sSQL .= 'class = :class and type = :type';
541 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
542 $sSQL .= ' AND linked_place_id is null';
543 if ($this->oContext->sqlCountryList) {
544 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
546 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
547 $sSQL .= " LIMIT $iLimit";
548 Debug::printSQL($sSQL);
549 $aDBResults = $oDB->getCol(
551 array(':class' => $this->sClass, ':type' => $this->sType)
556 foreach ($aDBResults as $iPlaceId) {
557 $aResults[$iPlaceId] = new Result($iPlaceId);
563 private function queryPostcode(&$oDB, $iLimit)
565 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
567 if (!empty($this->aAddress)) {
568 $sSQL .= ', search_name s ';
569 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
570 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
571 $sSQL .= ' @> '.$oDB->getArraySQL($this->aAddress).' AND ';
576 $sSQL .= "p.postcode = '".reset($this->aName)."'";
577 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
578 if ($this->oContext->bViewboxBounded) {
579 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
581 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
582 $sSQL .= " LIMIT $iLimit";
584 Debug::printSQL($sSQL);
587 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
588 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
594 private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
599 // Sort by existence of the requested house number but only if not
600 // too many results are expected for the street, i.e. if the result
601 // will be narrowed down by an address. Remeber that with ordering
602 // every single result has to be checked.
603 if ($this->sHouseNumber && (!empty($this->aAddress) || $this->sPostcode)) {
604 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
606 $aOrder[0] .= 'EXISTS(';
607 $aOrder[0] .= ' SELECT place_id';
608 $aOrder[0] .= ' FROM placex';
609 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
610 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
611 $aOrder[0] .= ' LIMIT 1';
613 // also housenumbers from interpolation lines table are needed
614 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
615 $iHouseNumber = intval($this->sHouseNumber);
616 $aOrder[0] .= 'OR EXISTS(';
617 $aOrder[0] .= ' SELECT place_id ';
618 $aOrder[0] .= ' FROM location_property_osmline ';
619 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
620 $aOrder[0] .= ' AND startnumber is not NULL';
621 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
622 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
623 $aOrder[0] .= ' LIMIT 1';
626 $aOrder[0] .= ') DESC';
629 if (!empty($this->aName)) {
630 $aTerms[] = 'name_vector @> '.$oDB->getArraySQL($this->aName);
632 if (!empty($this->aAddress)) {
633 // For infrequent name terms disable index usage for address
634 if ($this->bRareName) {
635 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.$oDB->getArraySQL($this->aAddress);
637 $aTerms[] = 'nameaddress_vector @> '.$oDB->getArraySQL($this->aAddress);
641 $sCountryTerm = $this->countryCodeSQL('country_code');
643 $aTerms[] = $sCountryTerm;
646 if ($this->sHouseNumber) {
647 $aTerms[] = 'address_rank between 16 and 30';
648 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
649 if ($iMinAddressRank > 0) {
650 $aTerms[] = "((address_rank between $iMinAddressRank and $iMaxAddressRank) or (search_rank between $iMinAddressRank and $iMaxAddressRank))";
654 if ($this->oContext->hasNearPoint()) {
655 $aTerms[] = $this->oContext->withinSQL('centroid');
656 $aOrder[] = $this->oContext->distanceSQL('centroid');
657 } elseif ($this->sPostcode) {
658 if (empty($this->aAddress)) {
659 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
661 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
665 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
667 $aTerms[] = $sExcludeSQL;
670 if ($this->oContext->bViewboxBounded) {
671 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
674 if ($this->oContext->hasNearPoint()) {
675 $aOrder[] = $this->oContext->distanceSQL('centroid');
678 if ($this->sHouseNumber) {
679 $sImportanceSQL = '- abs(26 - address_rank) + 3';
681 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
683 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
684 $aOrder[] = "$sImportanceSQL DESC";
686 $aFullNameAddress = $this->oContext->getFullNameTerms();
687 if (!empty($aFullNameAddress)) {
688 $sExactMatchSQL = ' ( ';
689 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
690 $sExactMatchSQL .= ' SELECT unnest('.$oDB->getArraySQL($aFullNameAddress).')';
691 $sExactMatchSQL .= ' INTERSECT ';
692 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
693 $sExactMatchSQL .= ' ) s';
694 $sExactMatchSQL .= ') as exactmatch';
695 $aOrder[] = 'exactmatch DESC';
697 $sExactMatchSQL = '0::int as exactmatch';
700 if ($this->sHouseNumber || $this->sClass) {
706 if (!empty($aTerms)) {
707 $sSQL = 'SELECT place_id, address_rank,'.$sExactMatchSQL;
708 $sSQL .= ' FROM search_name';
709 $sSQL .= ' WHERE '.join(' and ', $aTerms);
710 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
711 $sSQL .= ' LIMIT '.$iLimit;
713 Debug::printSQL($sSQL);
715 $aDBResults = $oDB->getAll($sSQL, null, 'Could not get places for search terms.');
717 foreach ($aDBResults as $aResult) {
718 $oResult = new Result($aResult['place_id']);
719 $oResult->iExactMatches = $aResult['exactmatch'];
720 $oResult->iAddressRank = $aResult['address_rank'];
721 $aResults[$aResult['place_id']] = $oResult;
728 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
731 $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
737 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
738 $sSQL = 'SELECT place_id FROM placex ';
739 $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
740 $sSQL .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
741 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
743 Debug::printSQL($sSQL);
745 // XXX should inherit the exactMatches from its parent
746 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
747 $aResults[$iPlaceId] = new Result($iPlaceId);
750 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
751 $iHousenumber = intval($this->sHouseNumber);
752 if ($bIsIntHouseNumber && empty($aResults)) {
753 // if nothing found, search in the interpolation line table
754 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
755 $sSQL .= ' WHERE startnumber is not NULL';
756 $sSQL .= ' AND parent_place_id in ('.$sPlaceIDs.') AND (';
757 if ($iHousenumber % 2 == 0) {
758 // If housenumber is even, look for housenumber in streets
759 // with interpolationtype even or all.
760 $sSQL .= "interpolationtype='even'";
762 // Else look for housenumber with interpolationtype odd or all.
763 $sSQL .= "interpolationtype='odd'";
765 $sSQL .= " or interpolationtype='all') and ";
766 $sSQL .= $iHousenumber.'>=startnumber and ';
767 $sSQL .= $iHousenumber.'<=endnumber';
768 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
770 Debug::printSQL($sSQL);
772 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
773 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
774 $oResult->iHouseNumber = $iHousenumber;
775 $aResults[$iPlaceId] = $oResult;
779 // If nothing found try the aux fallback table
780 if (CONST_Use_Aux_Location_data && empty($aResults)) {
781 $sSQL = 'SELECT place_id FROM location_property_aux';
782 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
783 $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
784 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
786 Debug::printSQL($sSQL);
788 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
789 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
793 // If nothing found then search in Tiger data (location_property_tiger)
794 if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && empty($aResults)) {
795 $sSQL = 'SELECT place_id FROM location_property_tiger';
796 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
797 if ($iHousenumber % 2 == 0) {
798 $sSQL .= "interpolationtype='even'";
800 $sSQL .= "interpolationtype='odd'";
802 $sSQL .= " or interpolationtype='all') and ";
803 $sSQL .= $iHousenumber.'>=startnumber and ';
804 $sSQL .= $iHousenumber.'<=endnumber';
805 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
807 Debug::printSQL($sSQL);
809 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
810 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
811 $oResult->iHouseNumber = $iHousenumber;
812 $aResults[$iPlaceId] = $oResult;
820 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
823 $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
829 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
830 // If they were searching for a named class (i.e. 'Kings Head pub')
831 // then we might have an extra match
832 $sSQL = 'SELECT place_id FROM placex ';
833 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
834 $sSQL .= " AND class='".$this->sClass."' ";
835 $sSQL .= " AND type='".$this->sType."'";
836 $sSQL .= ' AND linked_place_id is null';
837 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
838 $sSQL .= ' ORDER BY rank_search ASC ';
839 $sSQL .= " LIMIT $iLimit";
841 Debug::printSQL($sSQL);
843 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
844 $aResults[$iPlaceId] = new Result($iPlaceId);
848 // NEAR and IN are handled the same
849 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
850 $sClassTable = $this->poiTable();
851 $bCacheTable = $oDB->tableExists($sClassTable);
853 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
854 Debug::printSQL($sSQL);
855 $iMaxRank = (int) $oDB->getOne($sSQL);
857 // For state / country level searches the normal radius search doesn't work very well
859 if ($iMaxRank < 9 && $bCacheTable) {
860 // Try and get a polygon to search in instead
861 $sSQL = 'SELECT geometry FROM placex';
862 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
863 $sSQL .= " AND rank_search < $iMaxRank + 5";
864 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
865 $sSQL .= ' ORDER BY rank_search ASC ';
867 Debug::printSQL($sSQL);
868 $sPlaceGeom = $oDB->getOne($sSQL);
875 $sSQL = 'SELECT place_id FROM placex';
876 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
877 Debug::printSQL($sSQL);
878 $aPlaceIDs = $oDB->getCol($sSQL);
879 $sPlaceIDs = join(',', $aPlaceIDs);
882 if ($sPlaceIDs || $sPlaceGeom) {
885 // More efficient - can make the range bigger
889 if ($this->oContext->hasNearPoint()) {
890 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
891 } elseif ($sPlaceIDs) {
892 $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
893 } elseif ($sPlaceGeom) {
894 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
897 $sSQL = 'SELECT distinct i.place_id';
899 $sSQL .= ', i.order_term';
901 $sSQL .= ' from (SELECT l.place_id';
903 $sSQL .= ','.$sOrderBySQL.' as order_term';
905 $sSQL .= ' from '.$sClassTable.' as l';
908 $sSQL .= ',placex as f WHERE ';
909 $sSQL .= "f.place_id in ($sPlaceIDs) ";
910 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
911 } elseif ($sPlaceGeom) {
912 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
915 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
916 $sSQL .= 'limit 300) i ';
918 $sSQL .= 'order by order_term asc';
920 $sSQL .= " limit $iLimit";
922 Debug::printSQL($sSQL);
924 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
925 $aResults[$iPlaceId] = new Result($iPlaceId);
928 if ($this->oContext->hasNearPoint()) {
929 $fRange = $this->oContext->nearRadius();
933 if ($this->oContext->hasNearPoint()) {
934 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
936 $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
939 $sSQL = 'SELECT distinct l.place_id';
941 $sSQL .= ','.$sOrderBySQL.' as orderterm';
943 $sSQL .= ' FROM placex as l, placex as f';
944 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
945 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
946 $sSQL .= " AND l.class='".$this->sClass."'";
947 $sSQL .= " AND l.type='".$this->sType."'";
948 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
950 $sSQL .= 'ORDER BY orderterm ASC';
952 $sSQL .= " limit $iLimit";
954 Debug::printSQL($sSQL);
956 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
957 $aResults[$iPlaceId] = new Result($iPlaceId);
966 private function poiTable()
968 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
971 private function countryCodeSQL($sVar)
973 if ($this->sCountryCode) {
974 return $sVar.' = \''.$this->sCountryCode."'";
976 if ($this->oContext->sqlCountryList) {
977 return $sVar.' in '.$this->oContext->sqlCountryList;
983 /////////// Sort functions
986 public static function bySearchRank($a, $b)
988 if ($a->iSearchRank == $b->iSearchRank) {
989 return $a->iOperator + strlen($a->sHouseNumber)
990 - $b->iOperator - strlen($b->sHouseNumber);
993 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
996 //////////// Debugging functions
999 public function debugInfo()
1002 'Search rank' => $this->iSearchRank,
1003 'Country code' => $this->sCountryCode,
1004 'Name terms' => $this->aName,
1005 'Name terms (stop words)' => $this->aNameNonSearch,
1006 'Address terms' => $this->aAddress,
1007 'Address terms (stop words)' => $this->aAddressNonSearch,
1008 'Address terms (full words)' => $this->aFullNameAddress ?? '',
1009 'Special search' => $this->iOperator,
1010 'Class' => $this->sClass,
1011 'Type' => $this->sType,
1012 'House number' => $this->sHouseNumber,
1013 'Postcode' => $this->sPostcode
1017 public function dumpAsHtmlTableRow(&$aWordIDs)
1019 $kf = function ($k) use (&$aWordIDs) {
1020 return $aWordIDs[$k] ?? '['.$k.']';
1024 echo "<td>$this->iSearchRank</td>";
1025 echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
1026 echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
1027 echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
1028 echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1029 echo '<td>'.$this->sCountryCode.'</td>';
1030 echo '<td>'.Operator::toString($this->iOperator).'</td>';
1031 echo '<td>'.$this->sClass.'</td>';
1032 echo '<td>'.$this->sType.'</td>';
1033 echo '<td>'.$this->sPostcode.'</td>';
1034 echo '<td>'.$this->sHouseNumber.'</td>';