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;
182 $oSearch->iNamePhrase = -1;
184 $aNewSearches[] = $oSearch;
186 } elseif (($sPhraseType == '' || $sPhraseType == 'postalcode')
187 && is_a($oSearchTerm, '\Nominatim\Token\Postcode')
189 if (!$this->sPostcode) {
190 // If we have structured search or this is the first term,
191 // make the postcode the primary search element.
192 if ($this->iOperator == Operator::NONE && $bFirstToken) {
193 $oSearch = clone $this;
194 $oSearch->iSearchRank++;
195 $oSearch->iOperator = Operator::POSTCODE;
196 $oSearch->aAddress = array_merge($this->aAddress, $this->aName);
198 array($oSearchTerm->iId => $oSearchTerm->sPostcode);
199 $aNewSearches[] = $oSearch;
202 // If we have a structured search or this is not the first term,
203 // add the postcode as an addendum.
204 if ($this->iOperator != Operator::POSTCODE
205 && ($sPhraseType == 'postalcode' || !empty($this->aName))
207 $oSearch = clone $this;
208 $oSearch->iSearchRank++;
209 $oSearch->iNamePhrase = -1;
210 if (strlen($oSearchTerm->sPostcode) < 4) {
211 $oSearch->iSearchRank += 4 - strlen($oSearchTerm->sPostcode);
213 $oSearch->sPostcode = $oSearchTerm->sPostcode;
214 $aNewSearches[] = $oSearch;
217 } elseif (($sPhraseType == '' || $sPhraseType == 'street')
218 && is_a($oSearchTerm, '\Nominatim\Token\HouseNumber')
220 if (!$this->sHouseNumber && $this->iOperator != Operator::POSTCODE) {
221 // sanity check: if the housenumber is not mainly made
222 // up of numbers, add a penalty
224 if (preg_match('/\\d/', $oSearchTerm->sToken) === 0
225 || preg_match_all('/[^0-9]/', $oSearchTerm->sToken, $aMatches) > 2) {
228 if ($this->iOperator != Operator::NONE) {
231 if (empty($oSearchTerm->iId)) {
234 // also must not appear in the middle of the address
235 if (!empty($this->aAddress)
236 || (!empty($this->aAddressNonSearch))
242 $oSearch = clone $this;
243 $oSearch->iSearchRank += $iSearchCost;
244 $oSearch->iNamePhrase = -1;
245 $oSearch->sHouseNumber = $oSearchTerm->sToken;
246 $aNewSearches[] = $oSearch;
247 // Housenumbers may appear in the name when the place has its own
249 if ($oSearchTerm->iId !== null
250 && ($this->iNamePhrase >= 0 || empty($this->aName))
251 && empty($this->aAddress)
253 $oSearch = clone $this;
254 $oSearch->iSearchRank += $iSearchCost;
255 $oSearch->aAddress = $this->aName;
256 $oSearch->bRareName = false;
257 $oSearch->aName = array($oSearchTerm->iId => $oSearchTerm->iId);
258 $aNewSearches[] = $oSearch;
261 } elseif ($sPhraseType == ''
262 && is_a($oSearchTerm, '\Nominatim\Token\SpecialTerm')
264 if ($this->iOperator == Operator::NONE) {
265 $oSearch = clone $this;
266 $oSearch->iSearchRank += 2;
267 $oSearch->iNamePhrase = -1;
269 $iOp = $oSearchTerm->iOperator;
270 if ($iOp == Operator::NONE) {
271 if (!empty($this->aName) || $this->oContext->isBoundedSearch()) {
272 $iOp = Operator::NAME;
274 $iOp = Operator::NEAR;
276 $oSearch->iSearchRank += 2;
277 } elseif (!$bFirstToken && !$bLastToken) {
278 $oSearch->iSearchRank += 2;
280 if ($this->sHouseNumber) {
281 $oSearch->iSearchRank++;
284 $oSearch->setPoiSearch(
286 $oSearchTerm->sClass,
289 $aNewSearches[] = $oSearch;
291 } elseif ($sPhraseType != 'country'
292 && is_a($oSearchTerm, '\Nominatim\Token\Word')
294 $iWordID = $oSearchTerm->iId;
295 // Full words can only be a name if they appear at the beginning
296 // of the phrase. In structured search the name must forcably in
297 // the first phrase. In unstructured search it may be in a later
298 // phrase when the first phrase is a house number.
299 if (!empty($this->aName) || !($bFirstPhrase || $sPhraseType == '')) {
300 if (($sPhraseType == '' || !$bFirstPhrase) && !$bHasPartial) {
301 $oSearch = clone $this;
302 $oSearch->iNamePhrase = -1;
303 $oSearch->iSearchRank += 3 * $oSearchTerm->iTermCount;
304 $oSearch->aAddress[$iWordID] = $iWordID;
305 $aNewSearches[] = $oSearch;
307 } elseif (empty($this->aNameNonSearch)) {
308 $oSearch = clone $this;
309 $oSearch->iSearchRank++;
310 $oSearch->aName = array($iWordID => $iWordID);
311 if (CONST_Search_NameOnlySearchFrequencyThreshold) {
312 $oSearch->bRareName =
313 $oSearchTerm->iSearchNameCount
314 < CONST_Search_NameOnlySearchFrequencyThreshold;
316 $aNewSearches[] = $oSearch;
320 return $aNewSearches;
324 * Derive new searches by adding a partial term to the existing search.
326 * @param string $sToken Term for the token.
327 * @param object $oSearchTerm Description of the token.
328 * @param bool $bStructuredPhrases True if the search is structured.
329 * @param integer $iPhrase Number of the phrase the token is in.
330 * @param array[] $aFullTokens List of full term tokens with the
333 * @return SearchDescription[] List of derived search descriptions.
335 public function extendWithPartialTerm($sToken, $oSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
337 // Only allow name terms.
338 if (!(is_a($oSearchTerm, '\Nominatim\Token\Word'))
339 || strpos($sToken, ' ') !== false
344 $aNewSearches = array();
345 $iWordID = $oSearchTerm->iId;
347 if ((!$bStructuredPhrases || $iPhrase > 0)
348 && (!empty($this->aName))
350 $oSearch = clone $this;
351 $oSearch->iSearchRank++;
352 if (preg_match('#^[0-9 ]+$#', $sToken)) {
353 $oSearch->iSearchRank++;
355 if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
356 $oSearch->aAddress[$iWordID] = $iWordID;
358 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
359 if (!empty($aFullTokens)) {
360 $oSearch->iSearchRank++;
363 $aNewSearches[] = $oSearch;
366 if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
367 && ((empty($this->aName) && empty($this->aNameNonSearch)) || $this->iNamePhrase == $iPhrase)
369 $oSearch = clone $this;
370 $oSearch->iSearchRank++;
371 if (empty($this->aName) && empty($this->aNameNonSearch)) {
372 $oSearch->iSearchRank++;
374 if (preg_match('#^[0-9 ]+$#', $sToken)) {
375 $oSearch->iSearchRank++;
377 if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
378 if (empty($this->aName)
379 && CONST_Search_NameOnlySearchFrequencyThreshold
381 $oSearch->bRareName =
382 $oSearchTerm->iSearchNameCount
383 < CONST_Search_NameOnlySearchFrequencyThreshold;
385 $oSearch->bRareName = false;
387 $oSearch->aName[$iWordID] = $iWordID;
389 if (!empty($aFullTokens)) {
390 $oSearch->iSearchRank++;
392 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
394 $oSearch->iNamePhrase = $iPhrase;
395 $aNewSearches[] = $oSearch;
398 return $aNewSearches;
401 /////////// Query functions
405 * Query database for places that match this search.
407 * @param object $oDB Nominatim::DB instance to use.
408 * @param integer $iMinRank Minimum address rank to restrict search to.
409 * @param integer $iMaxRank Maximum address rank to restrict search to.
410 * @param integer $iLimit Maximum number of results.
412 * @return mixed[] An array with two fields: IDs contains the list of
413 * matching place IDs and houseNumber the houseNumber
414 * if appicable or -1 if not.
416 public function query(&$oDB, $iMinRank, $iMaxRank, $iLimit)
421 if ($this->sCountryCode
422 && empty($this->aName)
425 && !$this->oContext->hasNearPoint()
427 // Just looking for a country - look it up
428 if (4 >= $iMinRank && 4 <= $iMaxRank) {
429 $aResults = $this->queryCountry($oDB);
431 } elseif (empty($this->aName) && empty($this->aAddress)) {
432 // Neither name nor address? Then we must be
433 // looking for a POI in a geographic area.
434 if ($this->oContext->isBoundedSearch()) {
435 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
437 } elseif ($this->iOperator == Operator::POSTCODE) {
438 // looking for postcode
439 $aResults = $this->queryPostcode($oDB, $iLimit);
442 // First search for places according to name and address.
443 $aResults = $this->queryNamedPlace(
450 // Now search for housenumber, if housenumber provided. Can be zero.
451 if (($this->sHouseNumber || $this->sHouseNumber === '0') && !empty($aResults)) {
452 $aHnResults = $this->queryHouseNumber($oDB, $aResults);
454 // Downgrade the rank of the street results, they are missing
455 // the housenumber. Also drop POI places (rank 30) here, they
456 // cannot be a parent place and therefore must not be shown
457 // as a result for a search with a missing housenumber.
458 foreach ($aResults as $oRes) {
459 if ($oRes->iAddressRank < 28) {
460 if ($oRes->iAddressRank >= 26) {
461 $oRes->iResultRank++;
463 $oRes->iResultRank += 2;
465 $aHnResults[$oRes->iId] = $oRes;
469 $aResults = $aHnResults;
472 // finally get POIs if requested
473 if ($this->sClass && !empty($aResults)) {
474 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
478 Debug::printDebugTable('Place IDs', $aResults);
480 if (!empty($aResults) && $this->sPostcode) {
481 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
483 $sSQL = 'SELECT place_id FROM placex';
484 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
485 $sSQL .= " AND postcode != '".$this->sPostcode."'";
486 Debug::printSQL($sSQL);
487 $aFilteredPlaceIDs = $oDB->getCol($sSQL);
488 if ($aFilteredPlaceIDs) {
489 foreach ($aFilteredPlaceIDs as $iPlaceId) {
490 $aResults[$iPlaceId]->iResultRank++;
500 private function queryCountry(&$oDB)
502 $sSQL = 'SELECT place_id FROM placex ';
503 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
504 $sSQL .= ' AND rank_search = 4';
505 if ($this->oContext->bViewboxBounded) {
506 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
508 $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
510 Debug::printSQL($sSQL);
512 $iPlaceId = $oDB->getOne($sSQL);
516 $aResults[$iPlaceId] = new Result($iPlaceId);
522 private function queryNearbyPoi(&$oDB, $iLimit)
524 if (!$this->sClass) {
528 $aDBResults = array();
529 $sPoiTable = $this->poiTable();
531 if ($oDB->tableExists($sPoiTable)) {
532 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
533 if ($this->oContext->sqlCountryList) {
534 $sSQL .= ' JOIN placex USING (place_id)';
536 if ($this->oContext->hasNearPoint()) {
537 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
538 } elseif ($this->oContext->bViewboxBounded) {
539 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
541 if ($this->oContext->sqlCountryList) {
542 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
544 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
545 if ($this->oContext->sqlViewboxCentre) {
546 $sSQL .= ' ORDER BY ST_Distance(';
547 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
548 } elseif ($this->oContext->hasNearPoint()) {
549 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
551 $sSQL .= " LIMIT $iLimit";
552 Debug::printSQL($sSQL);
553 $aDBResults = $oDB->getCol($sSQL);
556 if ($this->oContext->hasNearPoint()) {
557 $sSQL = 'SELECT place_id FROM placex WHERE ';
558 $sSQL .= 'class = :class and type = :type';
559 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
560 $sSQL .= ' AND linked_place_id is null';
561 if ($this->oContext->sqlCountryList) {
562 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
564 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
565 $sSQL .= " LIMIT $iLimit";
566 Debug::printSQL($sSQL);
567 $aDBResults = $oDB->getCol(
569 array(':class' => $this->sClass, ':type' => $this->sType)
574 foreach ($aDBResults as $iPlaceId) {
575 $aResults[$iPlaceId] = new Result($iPlaceId);
581 private function queryPostcode(&$oDB, $iLimit)
583 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
585 if (!empty($this->aAddress)) {
586 $sSQL .= ', search_name s ';
587 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
588 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
589 $sSQL .= ' @> '.$oDB->getArraySQL($this->aAddress).' AND ';
594 $sSQL .= "p.postcode = '".reset($this->aName)."'";
595 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
596 if ($this->oContext->bViewboxBounded) {
597 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
599 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
600 $sSQL .= " LIMIT $iLimit";
602 Debug::printSQL($sSQL);
605 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
606 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
612 private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
617 // Sort by existence of the requested house number but only if not
618 // too many results are expected for the street, i.e. if the result
619 // will be narrowed down by an address. Remeber that with ordering
620 // every single result has to be checked.
621 if ($this->sHouseNumber && ($this->bRareName || !empty($this->aAddress) || $this->sPostcode)) {
622 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
624 $aOrder[0] .= 'EXISTS(';
625 $aOrder[0] .= ' SELECT place_id';
626 $aOrder[0] .= ' FROM placex';
627 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
628 $aOrder[0] .= " AND housenumber ~* E'".$sHouseNumberRegex."'";
629 $aOrder[0] .= ' LIMIT 1';
631 // also housenumbers from interpolation lines table are needed
632 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
633 $iHouseNumber = intval($this->sHouseNumber);
634 $aOrder[0] .= 'OR EXISTS(';
635 $aOrder[0] .= ' SELECT place_id ';
636 $aOrder[0] .= ' FROM location_property_osmline ';
637 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
638 $aOrder[0] .= ' AND startnumber is not NULL';
639 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
640 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
641 $aOrder[0] .= ' LIMIT 1';
644 $aOrder[0] .= ') DESC';
647 if (!empty($this->aName)) {
648 $aTerms[] = 'name_vector @> '.$oDB->getArraySQL($this->aName);
650 if (!empty($this->aAddress)) {
651 // For infrequent name terms disable index usage for address
652 if ($this->bRareName) {
653 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.$oDB->getArraySQL($this->aAddress);
655 $aTerms[] = 'nameaddress_vector @> '.$oDB->getArraySQL($this->aAddress);
659 $sCountryTerm = $this->countryCodeSQL('country_code');
661 $aTerms[] = $sCountryTerm;
664 if ($this->sHouseNumber) {
665 $aTerms[] = 'address_rank between 16 and 30';
666 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
667 if ($iMinAddressRank > 0) {
668 $aTerms[] = "((address_rank between $iMinAddressRank and $iMaxAddressRank) or (search_rank between $iMinAddressRank and $iMaxAddressRank))";
672 if ($this->oContext->hasNearPoint()) {
673 $aTerms[] = $this->oContext->withinSQL('centroid');
674 $aOrder[] = $this->oContext->distanceSQL('centroid');
675 } elseif ($this->sPostcode) {
676 if (empty($this->aAddress)) {
677 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
679 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
683 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
685 $aTerms[] = $sExcludeSQL;
688 if ($this->oContext->bViewboxBounded) {
689 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
692 if ($this->oContext->hasNearPoint()) {
693 $aOrder[] = $this->oContext->distanceSQL('centroid');
696 if ($this->sHouseNumber) {
697 $sImportanceSQL = '- abs(26 - address_rank) + 3';
699 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
701 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
702 $aOrder[] = "$sImportanceSQL DESC";
704 $aFullNameAddress = $this->oContext->getFullNameTerms();
705 if (!empty($aFullNameAddress)) {
706 $sExactMatchSQL = ' ( ';
707 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
708 $sExactMatchSQL .= ' SELECT unnest('.$oDB->getArraySQL($aFullNameAddress).')';
709 $sExactMatchSQL .= ' INTERSECT ';
710 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
711 $sExactMatchSQL .= ' ) s';
712 $sExactMatchSQL .= ') as exactmatch';
713 $aOrder[] = 'exactmatch DESC';
715 $sExactMatchSQL = '0::int as exactmatch';
718 if ($this->sHouseNumber || $this->sClass) {
724 if (!empty($aTerms)) {
725 $sSQL = 'SELECT place_id, address_rank,'.$sExactMatchSQL;
726 $sSQL .= ' FROM search_name';
727 $sSQL .= ' WHERE '.join(' and ', $aTerms);
728 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
729 $sSQL .= ' LIMIT '.$iLimit;
731 Debug::printSQL($sSQL);
733 $aDBResults = $oDB->getAll($sSQL, null, 'Could not get places for search terms.');
735 foreach ($aDBResults as $aResult) {
736 $oResult = new Result($aResult['place_id']);
737 $oResult->iExactMatches = $aResult['exactmatch'];
738 $oResult->iAddressRank = $aResult['address_rank'];
739 $aResults[$aResult['place_id']] = $oResult;
746 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
749 $sRoadPlaceIDs = Result::joinIdsByTableMaxRank(
751 Result::TABLE_PLACEX,
754 $sPOIPlaceIDs = Result::joinIdsByTableMinRank(
756 Result::TABLE_PLACEX,
760 $aIDCondition = array();
761 if ($sRoadPlaceIDs) {
762 $aIDCondition[] = 'parent_place_id in ('.$sRoadPlaceIDs.')';
765 $aIDCondition[] = 'place_id in ('.$sPOIPlaceIDs.')';
768 if (empty($aIDCondition)) {
772 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
773 $sSQL = 'SELECT place_id FROM placex WHERE';
774 $sSQL .= " housenumber ~* E'".$sHouseNumberRegex."'";
775 $sSQL .= ' AND ('.join(' OR ', $aIDCondition).')';
776 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
778 Debug::printSQL($sSQL);
780 // XXX should inherit the exactMatches from its parent
781 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
782 $aResults[$iPlaceId] = new Result($iPlaceId);
785 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
786 $iHousenumber = intval($this->sHouseNumber);
787 if ($bIsIntHouseNumber && $sRoadPlaceIDs && empty($aResults)) {
788 // if nothing found, search in the interpolation line table
789 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
790 $sSQL .= ' WHERE startnumber is not NULL';
791 $sSQL .= ' AND parent_place_id in ('.$sRoadPlaceIDs.') AND (';
792 if ($iHousenumber % 2 == 0) {
793 // If housenumber is even, look for housenumber in streets
794 // with interpolationtype even or all.
795 $sSQL .= "interpolationtype='even'";
797 // Else look for housenumber with interpolationtype odd or all.
798 $sSQL .= "interpolationtype='odd'";
800 $sSQL .= " or interpolationtype='all') and ";
801 $sSQL .= $iHousenumber.'>=startnumber and ';
802 $sSQL .= $iHousenumber.'<=endnumber';
803 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
805 Debug::printSQL($sSQL);
807 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
808 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
809 $oResult->iHouseNumber = $iHousenumber;
810 $aResults[$iPlaceId] = $oResult;
814 // If nothing found then search in Tiger data (location_property_tiger)
815 if (CONST_Use_US_Tiger_Data && $sRoadPlaceIDs && $bIsIntHouseNumber && empty($aResults)) {
816 $sSQL = 'SELECT place_id FROM location_property_tiger';
817 $sSQL .= ' WHERE parent_place_id in ('.$sRoadPlaceIDs.') 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] ?? '['.$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>';