5 require_once(CONST_BasePath.'/lib/SpecialSearchOperator.php');
6 require_once(CONST_BasePath.'/lib/SearchContext.php');
7 require_once(CONST_BasePath.'/lib/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 this might be a full address search.
92 * @return bool True if the search contains name, address and housenumber.
94 public function looksLikeFullAddress()
96 return (!empty($this->aName))
97 && (!empty($this->aAddress) || $this->sCountryCode)
98 && preg_match('/[0-9]+/', $this->sHouseNumber);
102 * Check if any operator is set.
104 * @return bool True, if this is a special search operation.
106 public function hasOperator()
108 return $this->iOperator != Operator::NONE;
112 * Extract key/value pairs from a query.
114 * Key/value pairs are recognised if they are of the form [<key>=<value>].
115 * If multiple terms of this kind are found then all terms are removed
116 * but only the first is used for search.
118 * @param string $sQuery Original query string.
120 * @return string The query string with the special search patterns removed.
122 public function extractKeyValuePairs($sQuery)
124 // Search for terms of kind [<key>=<value>].
126 '/\\[([\\w_]*)=([\\w_]*)\\]/',
132 foreach ($aSpecialTermsRaw as $aTerm) {
133 $sQuery = str_replace($aTerm[0], ' ', $sQuery);
134 if (!$this->hasOperator()) {
135 $this->setPoiSearch(Operator::TYPE, $aTerm[1], $aTerm[2]);
143 * Check if the combination of parameters is sensible.
145 * @return bool True, if the search looks valid.
147 public function isValidSearch()
149 if (empty($this->aName)) {
150 if ($this->sHouseNumber) {
153 if (!$this->sClass && !$this->sCountryCode) {
161 /////////// Search building functions
165 * Derive new searches by adding a full term to the existing search.
167 * @param object $oSearchTerm Description of the token.
168 * @param bool $bHasPartial True if there are also tokens of partial terms
169 * with the same name.
170 * @param string $sPhraseType Type of phrase the token is contained in.
171 * @param bool $bFirstToken True if the token is at the beginning of the
173 * @param bool $bFirstPhrase True if the token is in the first phrase of
175 * @param bool $bLastToken True if the token is at the end of the query.
177 * @return SearchDescription[] List of derived search descriptions.
179 public function extendWithFullTerm($oSearchTerm, $bHasPartial, $sPhraseType, $bFirstToken, $bFirstPhrase, $bLastToken)
181 $aNewSearches = array();
183 if (($sPhraseType == '' || $sPhraseType == 'country')
184 && is_a($oSearchTerm, '\Nominatim\Token\Country')
186 if (!$this->sCountryCode) {
187 $oSearch = clone $this;
188 $oSearch->iSearchRank++;
189 $oSearch->sCountryCode = $oSearchTerm->sCountryCode;
190 // Country is almost always at the end of the string
191 // - increase score for finding it anywhere else (optimisation)
193 $oSearch->iSearchRank += 5;
195 $aNewSearches[] = $oSearch;
197 } elseif (($sPhraseType == '' || $sPhraseType == 'postalcode')
198 && is_a($oSearchTerm, '\Nominatim\Token\Postcode')
200 if (!$this->sPostcode) {
201 // If we have structured search or this is the first term,
202 // make the postcode the primary search element.
203 if ($this->iOperator == Operator::NONE && $bFirstToken) {
204 $oSearch = clone $this;
205 $oSearch->iSearchRank++;
206 $oSearch->iOperator = Operator::POSTCODE;
207 $oSearch->aAddress = array_merge($this->aAddress, $this->aName);
209 array($oSearchTerm->iId => $oSearchTerm->sPostcode);
210 $aNewSearches[] = $oSearch;
213 // If we have a structured search or this is not the first term,
214 // add the postcode as an addendum.
215 if ($this->iOperator != Operator::POSTCODE
216 && ($sPhraseType == 'postalcode' || !empty($this->aName))
218 $oSearch = clone $this;
219 $oSearch->iSearchRank++;
220 if (strlen($oSearchTerm->sPostcode) < 4) {
221 $oSearch->iSearchRank += 4 - strlen($oSearchTerm->sPostcode);
223 $oSearch->sPostcode = $oSearchTerm->sPostcode;
224 $aNewSearches[] = $oSearch;
227 } elseif (($sPhraseType == '' || $sPhraseType == 'street')
228 && is_a($oSearchTerm, '\Nominatim\Token\HouseNumber')
230 if (!$this->sHouseNumber && $this->iOperator != Operator::POSTCODE) {
231 $oSearch = clone $this;
232 $oSearch->iSearchRank++;
233 $oSearch->sHouseNumber = $oSearchTerm->sToken;
234 // sanity check: if the housenumber is not mainly made
235 // up of numbers, add a penalty
236 if (preg_match('/\\d/', $oSearch->sHouseNumber) === 0
237 || preg_match_all('/[^0-9]/', $oSearch->sHouseNumber, $aMatches) > 2) {
238 $oSearch->iSearchRank++;
240 if (empty($oSearchTerm->iId)) {
241 $oSearch->iSearchRank++;
243 // also must not appear in the middle of the address
244 if (!empty($this->aAddress)
245 || (!empty($this->aAddressNonSearch))
248 $oSearch->iSearchRank++;
250 $aNewSearches[] = $oSearch;
251 // Housenumbers may appear in the name when the place has its own
253 if ($oSearchTerm->iId !== null
254 && ($this->iNamePhrase >= 0 || empty($this->aName))
255 && empty($this->aAddress)
257 $oSearch = clone $this;
258 $oSearch->iSearchRank++;
259 $oSearch->aAddress = $this->aName;
260 $oSearch->aName = array($oSearchTerm->iId => $oSearchTerm->iId);
261 $aNewSearches[] = $oSearch;
264 } elseif ($sPhraseType == ''
265 && is_a($oSearchTerm, '\Nominatim\Token\SpecialTerm')
267 if ($this->iOperator == Operator::NONE) {
268 $oSearch = clone $this;
269 $oSearch->iSearchRank++;
271 $iOp = $oSearchTerm->iOperator;
272 if ($iOp == Operator::NONE) {
273 if (!empty($this->aName) || $this->oContext->isBoundedSearch()) {
274 $iOp = Operator::NAME;
276 $iOp = Operator::NEAR;
278 $oSearch->iSearchRank += 2;
281 $oSearch->setPoiSearch(
283 $oSearchTerm->sClass,
286 $aNewSearches[] = $oSearch;
288 } elseif ($sPhraseType != 'country'
289 && is_a($oSearchTerm, '\Nominatim\Token\Word')
291 $iWordID = $oSearchTerm->iId;
292 // Full words can only be a name if they appear at the beginning
293 // of the phrase. In structured search the name must forcably in
294 // the first phrase. In unstructured search it may be in a later
295 // phrase when the first phrase is a house number.
296 if (!empty($this->aName) || !($bFirstPhrase || $sPhraseType == '')) {
297 if (($sPhraseType == '' || !$bFirstPhrase) && !$bHasPartial) {
298 $oSearch = clone $this;
299 $oSearch->iSearchRank += 3 * $oSearchTerm->iTermCount;
300 $oSearch->aAddress[$iWordID] = $iWordID;
301 $aNewSearches[] = $oSearch;
304 $oSearch = clone $this;
305 $oSearch->iSearchRank++;
306 $oSearch->aName = array($iWordID => $iWordID);
307 if (CONST_Search_NameOnlySearchFrequencyThreshold) {
308 $oSearch->bRareName =
309 $oSearchTerm->iSearchNameCount
310 < CONST_Search_NameOnlySearchFrequencyThreshold;
312 $aNewSearches[] = $oSearch;
316 return $aNewSearches;
320 * Derive new searches by adding a partial term to the existing search.
322 * @param string $sToken Term for the token.
323 * @param object $oSearchTerm Description of the token.
324 * @param bool $bStructuredPhrases True if the search is structured.
325 * @param integer $iPhrase Number of the phrase the token is in.
326 * @param array[] $aFullTokens List of full term tokens with the
329 * @return SearchDescription[] List of derived search descriptions.
331 public function extendWithPartialTerm($sToken, $oSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
333 // Only allow name terms.
334 if (!(is_a($oSearchTerm, '\Nominatim\Token\Word'))) {
338 $aNewSearches = array();
339 $iWordID = $oSearchTerm->iId;
341 if ((!$bStructuredPhrases || $iPhrase > 0)
342 && (!empty($this->aName))
343 && strpos($sToken, ' ') === false
345 if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
346 $oSearch = clone $this;
347 $oSearch->iSearchRank += $oSearchTerm->iTermCount;
348 if (empty($this->aName)) {
349 $oSearch->iSearchRank++;
351 if (preg_match('#^[0-9]+$#', $sToken)) {
352 $oSearch->iSearchRank++;
354 $oSearch->aAddress[$iWordID] = $iWordID;
355 $aNewSearches[] = $oSearch;
357 $oSearch = clone $this;
358 $oSearch->iSearchRank++;
359 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
360 if (!empty($aFullTokens)) {
361 $oSearch->iSearchRank++;
363 $aNewSearches[] = $oSearch;
365 // revert to the token version?
366 foreach ($aFullTokens as $oSearchTermToken) {
367 if (is_a($oSearchTermToken, '\Nominatim\Token\Word')) {
368 $oSearch = clone $this;
369 $oSearch->iSearchRank += 3;
370 $oSearch->aAddress[$oSearchTermToken->iId]
371 = $oSearchTermToken->iId;
372 $aNewSearches[] = $oSearch;
378 if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
379 && (empty($this->aName) || $this->iNamePhrase == $iPhrase)
381 $oSearch = clone $this;
382 $oSearch->iSearchRank += 2;
383 if (empty($this->aName)) {
384 $oSearch->iSearchRank += 1;
386 if (preg_match('#^[0-9]+$#', $sToken)) {
387 $oSearch->iSearchRank += 2;
389 if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
390 if (empty($this->aName)
391 && CONST_Search_NameOnlySearchFrequencyThreshold
393 $oSearch->bRareName =
394 $oSearchTerm->iSearchNameCount
395 < CONST_Search_NameOnlySearchFrequencyThreshold;
397 $oSearch->bRareName = false;
399 $oSearch->aName[$iWordID] = $iWordID;
401 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
403 $oSearch->iNamePhrase = $iPhrase;
404 $aNewSearches[] = $oSearch;
407 return $aNewSearches;
410 /////////// Query functions
414 * Query database for places that match this search.
416 * @param object $oDB Nominatim::DB instance to use.
417 * @param integer $iMinRank Minimum address rank to restrict search to.
418 * @param integer $iMaxRank Maximum address rank to restrict search to.
419 * @param integer $iLimit Maximum number of results.
421 * @return mixed[] An array with two fields: IDs contains the list of
422 * matching place IDs and houseNumber the houseNumber
423 * if appicable or -1 if not.
425 public function query(&$oDB, $iMinRank, $iMaxRank, $iLimit)
430 if ($this->sCountryCode
431 && empty($this->aName)
434 && !$this->oContext->hasNearPoint()
436 // Just looking for a country - look it up
437 if (4 >= $iMinRank && 4 <= $iMaxRank) {
438 $aResults = $this->queryCountry($oDB);
440 } elseif (empty($this->aName) && empty($this->aAddress)) {
441 // Neither name nor address? Then we must be
442 // looking for a POI in a geographic area.
443 if ($this->oContext->isBoundedSearch()) {
444 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
446 } elseif ($this->iOperator == Operator::POSTCODE) {
447 // looking for postcode
448 $aResults = $this->queryPostcode($oDB, $iLimit);
451 // First search for places according to name and address.
452 $aResults = $this->queryNamedPlace(
459 // Now search for housenumber, if housenumber provided. Can be zero.
460 if (($this->sHouseNumber || $this->sHouseNumber === '0') && !empty($aResults)) {
461 // Downgrade the rank of the street results, they are missing
463 foreach ($aResults as $oRes) {
464 $oRes->iResultRank++;
467 $aHnResults = $this->queryHouseNumber($oDB, $aResults);
469 if (!empty($aHnResults)) {
470 foreach ($aHnResults as $oRes) {
471 $aResults[$oRes->iId] = $oRes;
476 // finally get POIs if requested
477 if ($this->sClass && !empty($aResults)) {
478 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
482 Debug::printDebugTable('Place IDs', $aResults);
484 if (!empty($aResults) && $this->sPostcode) {
485 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
487 $sSQL = 'SELECT place_id FROM placex';
488 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
489 $sSQL .= " AND postcode != '".$this->sPostcode."'";
490 Debug::printSQL($sSQL);
491 $aFilteredPlaceIDs = $oDB->getCol($sSQL);
492 if ($aFilteredPlaceIDs) {
493 foreach ($aFilteredPlaceIDs as $iPlaceId) {
494 $aResults[$iPlaceId]->iResultRank++;
504 private function queryCountry(&$oDB)
506 $sSQL = 'SELECT place_id FROM placex ';
507 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
508 $sSQL .= ' AND rank_search = 4';
509 if ($this->oContext->bViewboxBounded) {
510 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
512 $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
514 Debug::printSQL($sSQL);
516 $iPlaceId = $oDB->getOne($sSQL);
520 $aResults[$iPlaceId] = new Result($iPlaceId);
526 private function queryNearbyPoi(&$oDB, $iLimit)
528 if (!$this->sClass) {
532 $aDBResults = array();
533 $sPoiTable = $this->poiTable();
535 if ($oDB->tableExists($sPoiTable)) {
536 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
537 if ($this->oContext->sqlCountryList) {
538 $sSQL .= ' JOIN placex USING (place_id)';
540 if ($this->oContext->hasNearPoint()) {
541 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
542 } elseif ($this->oContext->bViewboxBounded) {
543 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
545 if ($this->oContext->sqlCountryList) {
546 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
548 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
549 if ($this->oContext->sqlViewboxCentre) {
550 $sSQL .= ' ORDER BY ST_Distance(';
551 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
552 } elseif ($this->oContext->hasNearPoint()) {
553 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
555 $sSQL .= " LIMIT $iLimit";
556 Debug::printSQL($sSQL);
557 $aDBResults = $oDB->getCol($sSQL);
560 if ($this->oContext->hasNearPoint()) {
561 $sSQL = 'SELECT place_id FROM placex WHERE ';
562 $sSQL .= 'class = :class and type = :type';
563 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
564 $sSQL .= ' AND linked_place_id is null';
565 if ($this->oContext->sqlCountryList) {
566 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
568 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
569 $sSQL .= " LIMIT $iLimit";
570 Debug::printSQL($sSQL);
571 $aDBResults = $oDB->getCol(
573 array(':class' => $this->sClass, ':type' => $this->sType)
578 foreach ($aDBResults as $iPlaceId) {
579 $aResults[$iPlaceId] = new Result($iPlaceId);
585 private function queryPostcode(&$oDB, $iLimit)
587 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
589 if (!empty($this->aAddress)) {
590 $sSQL .= ', search_name s ';
591 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
592 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
593 $sSQL .= ' @> '.$oDB->getArraySQL($this->aAddress).' AND ';
598 $sSQL .= "p.postcode = '".reset($this->aName)."'";
599 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
600 if ($this->oContext->bViewboxBounded) {
601 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
603 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
604 $sSQL .= " LIMIT $iLimit";
606 Debug::printSQL($sSQL);
609 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
610 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
616 private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
621 // Sort by existence of the requested house number but only if not
622 // too many results are expected for the street, i.e. if the result
623 // will be narrowed down by an address. Remeber that with ordering
624 // every single result has to be checked.
625 if ($this->sHouseNumber && (!empty($this->aAddress) || $this->sPostcode)) {
626 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
628 $aOrder[0] .= 'EXISTS(';
629 $aOrder[0] .= ' SELECT place_id';
630 $aOrder[0] .= ' FROM placex';
631 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
632 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
633 $aOrder[0] .= ' LIMIT 1';
635 // also housenumbers from interpolation lines table are needed
636 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
637 $iHouseNumber = intval($this->sHouseNumber);
638 $aOrder[0] .= 'OR EXISTS(';
639 $aOrder[0] .= ' SELECT place_id ';
640 $aOrder[0] .= ' FROM location_property_osmline ';
641 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
642 $aOrder[0] .= ' AND startnumber is not NULL';
643 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
644 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
645 $aOrder[0] .= ' LIMIT 1';
648 $aOrder[0] .= ') DESC';
651 if (!empty($this->aName)) {
652 $aTerms[] = 'name_vector @> '.$oDB->getArraySQL($this->aName);
654 if (!empty($this->aAddress)) {
655 // For infrequent name terms disable index usage for address
656 if ($this->bRareName) {
657 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.$oDB->getArraySQL($this->aAddress);
659 $aTerms[] = 'nameaddress_vector @> '.$oDB->getArraySQL($this->aAddress);
663 $sCountryTerm = $this->countryCodeSQL('country_code');
665 $aTerms[] = $sCountryTerm;
668 if ($this->sHouseNumber) {
669 $aTerms[] = 'address_rank between 16 and 30';
670 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
671 if ($iMinAddressRank > 0) {
672 $aTerms[] = "((address_rank between $iMinAddressRank and $iMaxAddressRank) or (search_rank between $iMinAddressRank and $iMaxAddressRank))";
676 if ($this->oContext->hasNearPoint()) {
677 $aTerms[] = $this->oContext->withinSQL('centroid');
678 $aOrder[] = $this->oContext->distanceSQL('centroid');
679 } elseif ($this->sPostcode) {
680 if (empty($this->aAddress)) {
681 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
683 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
687 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
689 $aTerms[] = $sExcludeSQL;
692 if ($this->oContext->bViewboxBounded) {
693 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
696 if ($this->oContext->hasNearPoint()) {
697 $aOrder[] = $this->oContext->distanceSQL('centroid');
700 if ($this->sHouseNumber) {
701 $sImportanceSQL = '- abs(26 - address_rank) + 3';
703 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
705 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
706 $aOrder[] = "$sImportanceSQL DESC";
708 $aFullNameAddress = $this->oContext->getFullNameTerms();
709 if (!empty($aFullNameAddress)) {
710 $sExactMatchSQL = ' ( ';
711 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
712 $sExactMatchSQL .= ' SELECT unnest('.$oDB->getArraySQL($aFullNameAddress).')';
713 $sExactMatchSQL .= ' INTERSECT ';
714 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
715 $sExactMatchSQL .= ' ) s';
716 $sExactMatchSQL .= ') as exactmatch';
717 $aOrder[] = 'exactmatch DESC';
719 $sExactMatchSQL = '0::int as exactmatch';
722 if ($this->sHouseNumber || $this->sClass) {
728 if (!empty($aTerms)) {
729 $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
730 $sSQL .= ' FROM search_name';
731 $sSQL .= ' WHERE '.join(' and ', $aTerms);
732 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
733 $sSQL .= ' LIMIT '.$iLimit;
735 Debug::printSQL($sSQL);
737 $aDBResults = $oDB->getAll($sSQL, null, 'Could not get places for search terms.');
739 foreach ($aDBResults as $aResult) {
740 $oResult = new Result($aResult['place_id']);
741 $oResult->iExactMatches = $aResult['exactmatch'];
742 $aResults[$aResult['place_id']] = $oResult;
749 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
752 $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
758 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
759 $sSQL = 'SELECT place_id FROM placex ';
760 $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
761 $sSQL .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
762 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
764 Debug::printSQL($sSQL);
766 // XXX should inherit the exactMatches from its parent
767 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
768 $aResults[$iPlaceId] = new Result($iPlaceId);
771 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
772 $iHousenumber = intval($this->sHouseNumber);
773 if ($bIsIntHouseNumber && empty($aResults)) {
774 // if nothing found, search in the interpolation line table
775 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
776 $sSQL .= ' WHERE startnumber is not NULL';
777 $sSQL .= ' AND parent_place_id in ('.$sPlaceIDs.') AND (';
778 if ($iHousenumber % 2 == 0) {
779 // If housenumber is even, look for housenumber in streets
780 // with interpolationtype even or all.
781 $sSQL .= "interpolationtype='even'";
783 // Else look for housenumber with interpolationtype odd or all.
784 $sSQL .= "interpolationtype='odd'";
786 $sSQL .= " or interpolationtype='all') and ";
787 $sSQL .= $iHousenumber.'>=startnumber and ';
788 $sSQL .= $iHousenumber.'<=endnumber';
789 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
791 Debug::printSQL($sSQL);
793 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
794 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
795 $oResult->iHouseNumber = $iHousenumber;
796 $aResults[$iPlaceId] = $oResult;
800 // If nothing found try the aux fallback table
801 if (CONST_Use_Aux_Location_data && empty($aResults)) {
802 $sSQL = 'SELECT place_id FROM location_property_aux';
803 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
804 $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
805 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
807 Debug::printSQL($sSQL);
809 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
810 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
814 // If nothing found then search in Tiger data (location_property_tiger)
815 if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && empty($aResults)) {
816 $sSQL = 'SELECT place_id FROM location_property_tiger';
817 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
818 if ($iHousenumber % 2 == 0) {
819 $sSQL .= "interpolationtype='even'";
821 $sSQL .= "interpolationtype='odd'";
823 $sSQL .= " or interpolationtype='all') and ";
824 $sSQL .= $iHousenumber.'>=startnumber and ';
825 $sSQL .= $iHousenumber.'<=endnumber';
826 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
828 Debug::printSQL($sSQL);
830 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
831 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
832 $oResult->iHouseNumber = $iHousenumber;
833 $aResults[$iPlaceId] = $oResult;
841 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
844 $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
850 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
851 // If they were searching for a named class (i.e. 'Kings Head pub')
852 // then we might have an extra match
853 $sSQL = 'SELECT place_id FROM placex ';
854 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
855 $sSQL .= " AND class='".$this->sClass."' ";
856 $sSQL .= " AND type='".$this->sType."'";
857 $sSQL .= ' AND linked_place_id is null';
858 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
859 $sSQL .= ' ORDER BY rank_search ASC ';
860 $sSQL .= " LIMIT $iLimit";
862 Debug::printSQL($sSQL);
864 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
865 $aResults[$iPlaceId] = new Result($iPlaceId);
869 // NEAR and IN are handled the same
870 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
871 $sClassTable = $this->poiTable();
872 $bCacheTable = $oDB->tableExists($sClassTable);
874 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
875 Debug::printSQL($sSQL);
876 $iMaxRank = (int) $oDB->getOne($sSQL);
878 // For state / country level searches the normal radius search doesn't work very well
880 if ($iMaxRank < 9 && $bCacheTable) {
881 // Try and get a polygon to search in instead
882 $sSQL = 'SELECT geometry FROM placex';
883 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
884 $sSQL .= " AND rank_search < $iMaxRank + 5";
885 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
886 $sSQL .= ' ORDER BY rank_search ASC ';
888 Debug::printSQL($sSQL);
889 $sPlaceGeom = $oDB->getOne($sSQL);
896 $sSQL = 'SELECT place_id FROM placex';
897 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
898 Debug::printSQL($sSQL);
899 $aPlaceIDs = $oDB->getCol($sSQL);
900 $sPlaceIDs = join(',', $aPlaceIDs);
903 if ($sPlaceIDs || $sPlaceGeom) {
906 // More efficient - can make the range bigger
910 if ($this->oContext->hasNearPoint()) {
911 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
912 } elseif ($sPlaceIDs) {
913 $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
914 } elseif ($sPlaceGeom) {
915 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
918 $sSQL = 'SELECT distinct i.place_id';
920 $sSQL .= ', i.order_term';
922 $sSQL .= ' from (SELECT l.place_id';
924 $sSQL .= ','.$sOrderBySQL.' as order_term';
926 $sSQL .= ' from '.$sClassTable.' as l';
929 $sSQL .= ',placex as f WHERE ';
930 $sSQL .= "f.place_id in ($sPlaceIDs) ";
931 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
932 } elseif ($sPlaceGeom) {
933 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
936 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
937 $sSQL .= 'limit 300) i ';
939 $sSQL .= 'order by order_term asc';
941 $sSQL .= " limit $iLimit";
943 Debug::printSQL($sSQL);
945 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
946 $aResults[$iPlaceId] = new Result($iPlaceId);
949 if ($this->oContext->hasNearPoint()) {
950 $fRange = $this->oContext->nearRadius();
954 if ($this->oContext->hasNearPoint()) {
955 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
957 $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
960 $sSQL = 'SELECT distinct l.place_id';
962 $sSQL .= ','.$sOrderBySQL.' as orderterm';
964 $sSQL .= ' FROM placex as l, placex as f';
965 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
966 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
967 $sSQL .= " AND l.class='".$this->sClass."'";
968 $sSQL .= " AND l.type='".$this->sType."'";
969 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
971 $sSQL .= 'ORDER BY orderterm ASC';
973 $sSQL .= " limit $iLimit";
975 Debug::printSQL($sSQL);
977 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
978 $aResults[$iPlaceId] = new Result($iPlaceId);
987 private function poiTable()
989 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
992 private function countryCodeSQL($sVar)
994 if ($this->sCountryCode) {
995 return $sVar.' = \''.$this->sCountryCode."'";
997 if ($this->oContext->sqlCountryList) {
998 return $sVar.' in '.$this->oContext->sqlCountryList;
1004 /////////// Sort functions
1007 public static function bySearchRank($a, $b)
1009 if ($a->iSearchRank == $b->iSearchRank) {
1010 return $a->iOperator + strlen($a->sHouseNumber)
1011 - $b->iOperator - strlen($b->sHouseNumber);
1014 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
1017 //////////// Debugging functions
1020 public function debugInfo()
1023 'Search rank' => $this->iSearchRank,
1024 'Country code' => $this->sCountryCode,
1025 'Name terms' => $this->aName,
1026 'Name terms (stop words)' => $this->aNameNonSearch,
1027 'Address terms' => $this->aAddress,
1028 'Address terms (stop words)' => $this->aAddressNonSearch,
1029 'Address terms (full words)' => $this->aFullNameAddress,
1030 'Special search' => $this->iOperator,
1031 'Class' => $this->sClass,
1032 'Type' => $this->sType,
1033 'House number' => $this->sHouseNumber,
1034 'Postcode' => $this->sPostcode
1038 public function dumpAsHtmlTableRow(&$aWordIDs)
1040 $kf = function ($k) use (&$aWordIDs) {
1041 return $aWordIDs[$k];
1045 echo "<td>$this->iSearchRank</td>";
1046 echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
1047 echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
1048 echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
1049 echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1050 echo '<td>'.$this->sCountryCode.'</td>';
1051 echo '<td>'.Operator::toString($this->iOperator).'</td>';
1052 echo '<td>'.$this->sClass.'</td>';
1053 echo '<td>'.$this->sType.'</td>';
1054 echo '<td>'.$this->sPostcode.'</td>';
1055 echo '<td>'.$this->sHouseNumber.'</td>';