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 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->bRareName = false;
261 $oSearch->aName = array($oSearchTerm->iId => $oSearchTerm->iId);
262 $aNewSearches[] = $oSearch;
265 } elseif ($sPhraseType == ''
266 && is_a($oSearchTerm, '\Nominatim\Token\SpecialTerm')
268 if ($this->iOperator == Operator::NONE) {
269 $oSearch = clone $this;
270 $oSearch->iSearchRank++;
272 $iOp = $oSearchTerm->iOperator;
273 if ($iOp == Operator::NONE) {
274 if (!empty($this->aName) || $this->oContext->isBoundedSearch()) {
275 $iOp = Operator::NAME;
277 $iOp = Operator::NEAR;
279 $oSearch->iSearchRank += 2;
282 $oSearch->setPoiSearch(
284 $oSearchTerm->sClass,
287 $aNewSearches[] = $oSearch;
289 } elseif ($sPhraseType != 'country'
290 && is_a($oSearchTerm, '\Nominatim\Token\Word')
292 $iWordID = $oSearchTerm->iId;
293 // Full words can only be a name if they appear at the beginning
294 // of the phrase. In structured search the name must forcably in
295 // the first phrase. In unstructured search it may be in a later
296 // phrase when the first phrase is a house number.
297 if (!empty($this->aName) || !($bFirstPhrase || $sPhraseType == '')) {
298 if (($sPhraseType == '' || !$bFirstPhrase) && !$bHasPartial) {
299 $oSearch = clone $this;
300 $oSearch->iSearchRank += 3 * $oSearchTerm->iTermCount;
301 $oSearch->aAddress[$iWordID] = $iWordID;
302 $aNewSearches[] = $oSearch;
305 $oSearch = clone $this;
306 $oSearch->iSearchRank++;
307 $oSearch->aName = array($iWordID => $iWordID);
308 if (CONST_Search_NameOnlySearchFrequencyThreshold) {
309 $oSearch->bRareName =
310 $oSearchTerm->iSearchNameCount
311 < CONST_Search_NameOnlySearchFrequencyThreshold;
313 $aNewSearches[] = $oSearch;
317 return $aNewSearches;
321 * Derive new searches by adding a partial term to the existing search.
323 * @param string $sToken Term for the token.
324 * @param object $oSearchTerm Description of the token.
325 * @param bool $bStructuredPhrases True if the search is structured.
326 * @param integer $iPhrase Number of the phrase the token is in.
327 * @param array[] $aFullTokens List of full term tokens with the
330 * @return SearchDescription[] List of derived search descriptions.
332 public function extendWithPartialTerm($sToken, $oSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
334 // Only allow name terms.
335 if (!(is_a($oSearchTerm, '\Nominatim\Token\Word'))) {
339 $aNewSearches = array();
340 $iWordID = $oSearchTerm->iId;
342 if ((!$bStructuredPhrases || $iPhrase > 0)
343 && (!empty($this->aName))
344 && strpos($sToken, ' ') === false
346 if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
347 $oSearch = clone $this;
348 $oSearch->iSearchRank += $oSearchTerm->iTermCount + 1;
349 if (empty($this->aName)) {
350 $oSearch->iSearchRank++;
352 if (preg_match('#^[0-9]+$#', $sToken)) {
353 $oSearch->iSearchRank++;
355 $oSearch->aAddress[$iWordID] = $iWordID;
356 $aNewSearches[] = $oSearch;
358 $oSearch = clone $this;
359 $oSearch->iSearchRank += $oSearchTerm->iTermCount + 1;
360 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
361 if (!empty($aFullTokens)) {
362 $oSearch->iSearchRank++;
364 $aNewSearches[] = $oSearch;
366 // revert to the token version?
367 foreach ($aFullTokens as $oSearchTermToken) {
368 if (is_a($oSearchTermToken, '\Nominatim\Token\Word')) {
369 $oSearch = clone $this;
370 $oSearch->iSearchRank += 3;
371 $oSearch->aAddress[$oSearchTermToken->iId]
372 = $oSearchTermToken->iId;
373 $aNewSearches[] = $oSearch;
379 if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
380 && (empty($this->aName) || $this->iNamePhrase == $iPhrase)
382 $oSearch = clone $this;
383 $oSearch->iSearchRank += 2;
384 if (empty($this->aName)) {
385 $oSearch->iSearchRank += 1;
387 if (preg_match('#^[0-9]+$#', $sToken)) {
388 $oSearch->iSearchRank += 2;
390 if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
391 if (empty($this->aName)
392 && CONST_Search_NameOnlySearchFrequencyThreshold
394 $oSearch->bRareName =
395 $oSearchTerm->iSearchNameCount
396 < CONST_Search_NameOnlySearchFrequencyThreshold;
398 $oSearch->bRareName = false;
400 $oSearch->aName[$iWordID] = $iWordID;
402 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
404 $oSearch->iNamePhrase = $iPhrase;
405 $aNewSearches[] = $oSearch;
408 return $aNewSearches;
411 /////////// Query functions
415 * Query database for places that match this search.
417 * @param object $oDB Nominatim::DB instance to use.
418 * @param integer $iMinRank Minimum address rank to restrict search to.
419 * @param integer $iMaxRank Maximum address rank to restrict search to.
420 * @param integer $iLimit Maximum number of results.
422 * @return mixed[] An array with two fields: IDs contains the list of
423 * matching place IDs and houseNumber the houseNumber
424 * if appicable or -1 if not.
426 public function query(&$oDB, $iMinRank, $iMaxRank, $iLimit)
431 if ($this->sCountryCode
432 && empty($this->aName)
435 && !$this->oContext->hasNearPoint()
437 // Just looking for a country - look it up
438 if (4 >= $iMinRank && 4 <= $iMaxRank) {
439 $aResults = $this->queryCountry($oDB);
441 } elseif (empty($this->aName) && empty($this->aAddress)) {
442 // Neither name nor address? Then we must be
443 // looking for a POI in a geographic area.
444 if ($this->oContext->isBoundedSearch()) {
445 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
447 } elseif ($this->iOperator == Operator::POSTCODE) {
448 // looking for postcode
449 $aResults = $this->queryPostcode($oDB, $iLimit);
452 // First search for places according to name and address.
453 $aResults = $this->queryNamedPlace(
460 // Now search for housenumber, if housenumber provided. Can be zero.
461 if (($this->sHouseNumber || $this->sHouseNumber === '0') && !empty($aResults)) {
462 // Downgrade the rank of the street results, they are missing
464 foreach ($aResults as $oRes) {
465 $oRes->iResultRank++;
468 $aHnResults = $this->queryHouseNumber($oDB, $aResults);
470 if (!empty($aHnResults)) {
471 foreach ($aHnResults as $oRes) {
472 $aResults[$oRes->iId] = $oRes;
477 // finally get POIs if requested
478 if ($this->sClass && !empty($aResults)) {
479 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
483 Debug::printDebugTable('Place IDs', $aResults);
485 if (!empty($aResults) && $this->sPostcode) {
486 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
488 $sSQL = 'SELECT place_id FROM placex';
489 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
490 $sSQL .= " AND postcode != '".$this->sPostcode."'";
491 Debug::printSQL($sSQL);
492 $aFilteredPlaceIDs = $oDB->getCol($sSQL);
493 if ($aFilteredPlaceIDs) {
494 foreach ($aFilteredPlaceIDs as $iPlaceId) {
495 $aResults[$iPlaceId]->iResultRank++;
505 private function queryCountry(&$oDB)
507 $sSQL = 'SELECT place_id FROM placex ';
508 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
509 $sSQL .= ' AND rank_search = 4';
510 if ($this->oContext->bViewboxBounded) {
511 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
513 $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
515 Debug::printSQL($sSQL);
517 $iPlaceId = $oDB->getOne($sSQL);
521 $aResults[$iPlaceId] = new Result($iPlaceId);
527 private function queryNearbyPoi(&$oDB, $iLimit)
529 if (!$this->sClass) {
533 $aDBResults = array();
534 $sPoiTable = $this->poiTable();
536 if ($oDB->tableExists($sPoiTable)) {
537 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
538 if ($this->oContext->sqlCountryList) {
539 $sSQL .= ' JOIN placex USING (place_id)';
541 if ($this->oContext->hasNearPoint()) {
542 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
543 } elseif ($this->oContext->bViewboxBounded) {
544 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
546 if ($this->oContext->sqlCountryList) {
547 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
549 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
550 if ($this->oContext->sqlViewboxCentre) {
551 $sSQL .= ' ORDER BY ST_Distance(';
552 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
553 } elseif ($this->oContext->hasNearPoint()) {
554 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
556 $sSQL .= " LIMIT $iLimit";
557 Debug::printSQL($sSQL);
558 $aDBResults = $oDB->getCol($sSQL);
561 if ($this->oContext->hasNearPoint()) {
562 $sSQL = 'SELECT place_id FROM placex WHERE ';
563 $sSQL .= 'class = :class and type = :type';
564 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
565 $sSQL .= ' AND linked_place_id is null';
566 if ($this->oContext->sqlCountryList) {
567 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
569 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
570 $sSQL .= " LIMIT $iLimit";
571 Debug::printSQL($sSQL);
572 $aDBResults = $oDB->getCol(
574 array(':class' => $this->sClass, ':type' => $this->sType)
579 foreach ($aDBResults as $iPlaceId) {
580 $aResults[$iPlaceId] = new Result($iPlaceId);
586 private function queryPostcode(&$oDB, $iLimit)
588 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
590 if (!empty($this->aAddress)) {
591 $sSQL .= ', search_name s ';
592 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
593 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
594 $sSQL .= ' @> '.$oDB->getArraySQL($this->aAddress).' AND ';
599 $sSQL .= "p.postcode = '".reset($this->aName)."'";
600 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
601 if ($this->oContext->bViewboxBounded) {
602 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
604 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
605 $sSQL .= " LIMIT $iLimit";
607 Debug::printSQL($sSQL);
610 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
611 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
617 private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
622 // Sort by existence of the requested house number but only if not
623 // too many results are expected for the street, i.e. if the result
624 // will be narrowed down by an address. Remeber that with ordering
625 // every single result has to be checked.
626 if ($this->sHouseNumber && (!empty($this->aAddress) || $this->sPostcode)) {
627 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
629 $aOrder[0] .= 'EXISTS(';
630 $aOrder[0] .= ' SELECT place_id';
631 $aOrder[0] .= ' FROM placex';
632 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
633 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
634 $aOrder[0] .= ' LIMIT 1';
636 // also housenumbers from interpolation lines table are needed
637 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
638 $iHouseNumber = intval($this->sHouseNumber);
639 $aOrder[0] .= 'OR EXISTS(';
640 $aOrder[0] .= ' SELECT place_id ';
641 $aOrder[0] .= ' FROM location_property_osmline ';
642 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
643 $aOrder[0] .= ' AND startnumber is not NULL';
644 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
645 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
646 $aOrder[0] .= ' LIMIT 1';
649 $aOrder[0] .= ') DESC';
652 if (!empty($this->aName)) {
653 $aTerms[] = 'name_vector @> '.$oDB->getArraySQL($this->aName);
655 if (!empty($this->aAddress)) {
656 // For infrequent name terms disable index usage for address
657 if ($this->bRareName) {
658 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.$oDB->getArraySQL($this->aAddress);
660 $aTerms[] = 'nameaddress_vector @> '.$oDB->getArraySQL($this->aAddress);
664 $sCountryTerm = $this->countryCodeSQL('country_code');
666 $aTerms[] = $sCountryTerm;
669 if ($this->sHouseNumber) {
670 $aTerms[] = 'address_rank between 16 and 30';
671 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
672 if ($iMinAddressRank > 0) {
673 $aTerms[] = "((address_rank between $iMinAddressRank and $iMaxAddressRank) or (search_rank between $iMinAddressRank and $iMaxAddressRank))";
677 if ($this->oContext->hasNearPoint()) {
678 $aTerms[] = $this->oContext->withinSQL('centroid');
679 $aOrder[] = $this->oContext->distanceSQL('centroid');
680 } elseif ($this->sPostcode) {
681 if (empty($this->aAddress)) {
682 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
684 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
688 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
690 $aTerms[] = $sExcludeSQL;
693 if ($this->oContext->bViewboxBounded) {
694 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
697 if ($this->oContext->hasNearPoint()) {
698 $aOrder[] = $this->oContext->distanceSQL('centroid');
701 if ($this->sHouseNumber) {
702 $sImportanceSQL = '- abs(26 - address_rank) + 3';
704 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
706 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
707 $aOrder[] = "$sImportanceSQL DESC";
709 $aFullNameAddress = $this->oContext->getFullNameTerms();
710 if (!empty($aFullNameAddress)) {
711 $sExactMatchSQL = ' ( ';
712 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
713 $sExactMatchSQL .= ' SELECT unnest('.$oDB->getArraySQL($aFullNameAddress).')';
714 $sExactMatchSQL .= ' INTERSECT ';
715 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
716 $sExactMatchSQL .= ' ) s';
717 $sExactMatchSQL .= ') as exactmatch';
718 $aOrder[] = 'exactmatch DESC';
720 $sExactMatchSQL = '0::int as exactmatch';
723 if ($this->sHouseNumber || $this->sClass) {
729 if (!empty($aTerms)) {
730 $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
731 $sSQL .= ' FROM search_name';
732 $sSQL .= ' WHERE '.join(' and ', $aTerms);
733 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
734 $sSQL .= ' LIMIT '.$iLimit;
736 Debug::printSQL($sSQL);
738 $aDBResults = $oDB->getAll($sSQL, null, 'Could not get places for search terms.');
740 foreach ($aDBResults as $aResult) {
741 $oResult = new Result($aResult['place_id']);
742 $oResult->iExactMatches = $aResult['exactmatch'];
743 $aResults[$aResult['place_id']] = $oResult;
750 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
753 $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
759 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
760 $sSQL = 'SELECT place_id FROM placex ';
761 $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
762 $sSQL .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
763 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
765 Debug::printSQL($sSQL);
767 // XXX should inherit the exactMatches from its parent
768 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
769 $aResults[$iPlaceId] = new Result($iPlaceId);
772 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
773 $iHousenumber = intval($this->sHouseNumber);
774 if ($bIsIntHouseNumber && empty($aResults)) {
775 // if nothing found, search in the interpolation line table
776 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
777 $sSQL .= ' WHERE startnumber is not NULL';
778 $sSQL .= ' AND parent_place_id in ('.$sPlaceIDs.') AND (';
779 if ($iHousenumber % 2 == 0) {
780 // If housenumber is even, look for housenumber in streets
781 // with interpolationtype even or all.
782 $sSQL .= "interpolationtype='even'";
784 // Else look for housenumber with interpolationtype odd or all.
785 $sSQL .= "interpolationtype='odd'";
787 $sSQL .= " or interpolationtype='all') and ";
788 $sSQL .= $iHousenumber.'>=startnumber and ';
789 $sSQL .= $iHousenumber.'<=endnumber';
790 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
792 Debug::printSQL($sSQL);
794 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
795 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
796 $oResult->iHouseNumber = $iHousenumber;
797 $aResults[$iPlaceId] = $oResult;
801 // If nothing found try the aux fallback table
802 if (CONST_Use_Aux_Location_data && empty($aResults)) {
803 $sSQL = 'SELECT place_id FROM location_property_aux';
804 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
805 $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
806 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
808 Debug::printSQL($sSQL);
810 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
811 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
815 // If nothing found then search in Tiger data (location_property_tiger)
816 if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && empty($aResults)) {
817 $sSQL = 'SELECT place_id FROM location_property_tiger';
818 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
819 if ($iHousenumber % 2 == 0) {
820 $sSQL .= "interpolationtype='even'";
822 $sSQL .= "interpolationtype='odd'";
824 $sSQL .= " or interpolationtype='all') and ";
825 $sSQL .= $iHousenumber.'>=startnumber and ';
826 $sSQL .= $iHousenumber.'<=endnumber';
827 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
829 Debug::printSQL($sSQL);
831 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
832 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
833 $oResult->iHouseNumber = $iHousenumber;
834 $aResults[$iPlaceId] = $oResult;
842 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
845 $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
851 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
852 // If they were searching for a named class (i.e. 'Kings Head pub')
853 // then we might have an extra match
854 $sSQL = 'SELECT place_id FROM placex ';
855 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
856 $sSQL .= " AND class='".$this->sClass."' ";
857 $sSQL .= " AND type='".$this->sType."'";
858 $sSQL .= ' AND linked_place_id is null';
859 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
860 $sSQL .= ' ORDER BY rank_search ASC ';
861 $sSQL .= " LIMIT $iLimit";
863 Debug::printSQL($sSQL);
865 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
866 $aResults[$iPlaceId] = new Result($iPlaceId);
870 // NEAR and IN are handled the same
871 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
872 $sClassTable = $this->poiTable();
873 $bCacheTable = $oDB->tableExists($sClassTable);
875 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
876 Debug::printSQL($sSQL);
877 $iMaxRank = (int) $oDB->getOne($sSQL);
879 // For state / country level searches the normal radius search doesn't work very well
881 if ($iMaxRank < 9 && $bCacheTable) {
882 // Try and get a polygon to search in instead
883 $sSQL = 'SELECT geometry FROM placex';
884 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
885 $sSQL .= " AND rank_search < $iMaxRank + 5";
886 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
887 $sSQL .= ' ORDER BY rank_search ASC ';
889 Debug::printSQL($sSQL);
890 $sPlaceGeom = $oDB->getOne($sSQL);
897 $sSQL = 'SELECT place_id FROM placex';
898 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
899 Debug::printSQL($sSQL);
900 $aPlaceIDs = $oDB->getCol($sSQL);
901 $sPlaceIDs = join(',', $aPlaceIDs);
904 if ($sPlaceIDs || $sPlaceGeom) {
907 // More efficient - can make the range bigger
911 if ($this->oContext->hasNearPoint()) {
912 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
913 } elseif ($sPlaceIDs) {
914 $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
915 } elseif ($sPlaceGeom) {
916 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
919 $sSQL = 'SELECT distinct i.place_id';
921 $sSQL .= ', i.order_term';
923 $sSQL .= ' from (SELECT l.place_id';
925 $sSQL .= ','.$sOrderBySQL.' as order_term';
927 $sSQL .= ' from '.$sClassTable.' as l';
930 $sSQL .= ',placex as f WHERE ';
931 $sSQL .= "f.place_id in ($sPlaceIDs) ";
932 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
933 } elseif ($sPlaceGeom) {
934 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
937 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
938 $sSQL .= 'limit 300) i ';
940 $sSQL .= 'order by order_term asc';
942 $sSQL .= " limit $iLimit";
944 Debug::printSQL($sSQL);
946 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
947 $aResults[$iPlaceId] = new Result($iPlaceId);
950 if ($this->oContext->hasNearPoint()) {
951 $fRange = $this->oContext->nearRadius();
955 if ($this->oContext->hasNearPoint()) {
956 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
958 $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
961 $sSQL = 'SELECT distinct l.place_id';
963 $sSQL .= ','.$sOrderBySQL.' as orderterm';
965 $sSQL .= ' FROM placex as l, placex as f';
966 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
967 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
968 $sSQL .= " AND l.class='".$this->sClass."'";
969 $sSQL .= " AND l.type='".$this->sType."'";
970 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
972 $sSQL .= 'ORDER BY orderterm ASC';
974 $sSQL .= " limit $iLimit";
976 Debug::printSQL($sSQL);
978 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
979 $aResults[$iPlaceId] = new Result($iPlaceId);
988 private function poiTable()
990 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
993 private function countryCodeSQL($sVar)
995 if ($this->sCountryCode) {
996 return $sVar.' = \''.$this->sCountryCode."'";
998 if ($this->oContext->sqlCountryList) {
999 return $sVar.' in '.$this->oContext->sqlCountryList;
1005 /////////// Sort functions
1008 public static function bySearchRank($a, $b)
1010 if ($a->iSearchRank == $b->iSearchRank) {
1011 return $a->iOperator + strlen($a->sHouseNumber)
1012 - $b->iOperator - strlen($b->sHouseNumber);
1015 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
1018 //////////// Debugging functions
1021 public function debugInfo()
1024 'Search rank' => $this->iSearchRank,
1025 'Country code' => $this->sCountryCode,
1026 'Name terms' => $this->aName,
1027 'Name terms (stop words)' => $this->aNameNonSearch,
1028 'Address terms' => $this->aAddress,
1029 'Address terms (stop words)' => $this->aAddressNonSearch,
1030 'Address terms (full words)' => $this->aFullNameAddress,
1031 'Special search' => $this->iOperator,
1032 'Class' => $this->sClass,
1033 'Type' => $this->sType,
1034 'House number' => $this->sHouseNumber,
1035 'Postcode' => $this->sPostcode
1039 public function dumpAsHtmlTableRow(&$aWordIDs)
1041 $kf = function ($k) use (&$aWordIDs) {
1042 return $aWordIDs[$k];
1046 echo "<td>$this->iSearchRank</td>";
1047 echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
1048 echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
1049 echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
1050 echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1051 echo '<td>'.$this->sCountryCode.'</td>';
1052 echo '<td>'.Operator::toString($this->iOperator).'</td>';
1053 echo '<td>'.$this->sClass.'</td>';
1054 echo '<td>'.$this->sType.'</td>';
1055 echo '<td>'.$this->sPostcode.'</td>';
1056 echo '<td>'.$this->sHouseNumber.'</td>';