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 /// Subset of word ids of full words making up the address.
25 private $aFullNameAddress = array();
26 /// List of word ids that appear in the name but should be ignored.
27 private $aNameNonSearch = array();
28 /// List of word ids that appear in the address but should be ignored.
29 private $aAddressNonSearch = array();
30 /// Kind of search for special searches, see Nominatim::Operator.
31 private $iOperator = Operator::NONE;
32 /// Class of special feature to search for.
34 /// Type of special feature to search for.
36 /// Housenumber of the object.
37 private $sHouseNumber = '';
38 /// Postcode for the object.
39 private $sPostcode = '';
40 /// Global search constraints.
43 // Temporary values used while creating the search description.
45 /// Index of phrase currently processed.
46 private $iNamePhrase = -1;
49 * Create an empty search description.
51 * @param object $oContext Global context to use. Will be inherited by
52 * all derived search objects.
54 public function __construct($oContext)
56 $this->oContext = $oContext;
60 * Get current search rank.
62 * The higher the search rank the lower the likelihood that the
63 * search is a correct interpretation of the search query.
65 * @return integer Search rank.
67 public function getRank()
69 return $this->iSearchRank;
73 * Make this search a POI search.
75 * In a POI search, objects are not (only) searched by their name
76 * but also by the primary OSM key/value pair (class and type in Nominatim).
78 * @param integer $iOperator Type of POI search
79 * @param string $sClass Class (or OSM tag key) of POI.
80 * @param string $sType Type (or OSM tag value) of POI.
84 public function setPoiSearch($iOperator, $sClass, $sType)
86 $this->iOperator = $iOperator;
87 $this->sClass = $sClass;
88 $this->sType = $sType;
92 * Check if this might be a full address search.
94 * @return bool True if the search contains name, address and housenumber.
96 public function looksLikeFullAddress()
98 return (!empty($this->aName))
99 && (!empty($this->aAddress) || $this->sCountryCode)
100 && preg_match('/[0-9]+/', $this->sHouseNumber);
104 * Check if any operator is set.
106 * @return bool True, if this is a special search operation.
108 public function hasOperator()
110 return $this->iOperator != Operator::NONE;
114 * Extract key/value pairs from a query.
116 * Key/value pairs are recognised if they are of the form [<key>=<value>].
117 * If multiple terms of this kind are found then all terms are removed
118 * but only the first is used for search.
120 * @param string $sQuery Original query string.
122 * @return string The query string with the special search patterns removed.
124 public function extractKeyValuePairs($sQuery)
126 // Search for terms of kind [<key>=<value>].
128 '/\\[([\\w_]*)=([\\w_]*)\\]/',
134 foreach ($aSpecialTermsRaw as $aTerm) {
135 $sQuery = str_replace($aTerm[0], ' ', $sQuery);
136 if (!$this->hasOperator()) {
137 $this->setPoiSearch(Operator::TYPE, $aTerm[1], $aTerm[2]);
145 * Check if the combination of parameters is sensible.
147 * @return bool True, if the search looks valid.
149 public function isValidSearch()
151 if (empty($this->aName)) {
152 if ($this->sHouseNumber) {
155 if (!$this->sClass && !$this->sCountryCode) {
163 /////////// Search building functions
167 * Derive new searches by adding a full term to the existing search.
169 * @param object $oSearchTerm Description of the token.
170 * @param bool $bHasPartial True if there are also tokens of partial terms
171 * with the same name.
172 * @param string $sPhraseType Type of phrase the token is contained in.
173 * @param bool $bFirstToken True if the token is at the beginning of the
175 * @param bool $bFirstPhrase True if the token is in the first phrase of
177 * @param bool $bLastToken True if the token is at the end of the query.
179 * @return SearchDescription[] List of derived search descriptions.
181 public function extendWithFullTerm($oSearchTerm, $bHasPartial, $sPhraseType, $bFirstToken, $bFirstPhrase, $bLastToken)
183 $aNewSearches = array();
185 if (($sPhraseType == '' || $sPhraseType == 'country')
186 && is_a($oSearchTerm, '\Nominatim\Token\Country')
188 if (!$this->sCountryCode) {
189 $oSearch = clone $this;
190 $oSearch->iSearchRank++;
191 $oSearch->sCountryCode = $oSearchTerm->sCountryCode;
192 // Country is almost always at the end of the string
193 // - increase score for finding it anywhere else (optimisation)
195 $oSearch->iSearchRank += 5;
197 $aNewSearches[] = $oSearch;
199 } elseif (($sPhraseType == '' || $sPhraseType == 'postalcode')
200 && is_a($oSearchTerm, '\Nominatim\Token\Postcode')
202 // We need to try the case where the postal code is the primary element
203 // (i.e. no way to tell if it is (postalcode, city) OR (city, postalcode)
205 if (!$this->sPostcode) {
206 // If we have structured search or this is the first term,
207 // make the postcode the primary search element.
208 if ($this->iOperator == Operator::NONE
209 && ($sPhraseType == 'postalcode' || $bFirstToken)
211 $oSearch = clone $this;
212 $oSearch->iSearchRank++;
213 $oSearch->iOperator = Operator::POSTCODE;
214 $oSearch->aAddress = array_merge($this->aAddress, $this->aName);
216 array($oSearchTerm->iId => $oSearchTerm->sPostcode);
217 $aNewSearches[] = $oSearch;
220 // If we have a structured search or this is not the first term,
221 // add the postcode as an addendum.
222 if ($this->iOperator != Operator::POSTCODE
223 && ($sPhraseType == 'postalcode' || !empty($this->aName))
225 $oSearch = clone $this;
226 $oSearch->iSearchRank++;
227 $oSearch->sPostcode = $oSearchTerm->sPostcode;
228 $aNewSearches[] = $oSearch;
231 } elseif (($sPhraseType == '' || $sPhraseType == 'street')
232 && is_a($oSearchTerm, '\Nominatim\Token\HouseNumber')
234 if (!$this->sHouseNumber && $this->iOperator != Operator::POSTCODE) {
235 $oSearch = clone $this;
236 $oSearch->iSearchRank++;
237 $oSearch->sHouseNumber = $oSearchTerm->sToken;
238 // sanity check: if the housenumber is not mainly made
239 // up of numbers, add a penalty
240 if (preg_match('/\\d/', $oSearch->sHouseNumber) === 0
241 || preg_match_all('/[^0-9]/', $oSearch->sHouseNumber, $aMatches) > 2) {
242 $oSearch->iSearchRank++;
244 if (empty($oSearchTerm->iId)) {
245 $oSearch->iSearchRank++;
247 // also must not appear in the middle of the address
248 if (!empty($this->aAddress)
249 || (!empty($this->aAddressNonSearch))
252 $oSearch->iSearchRank++;
254 $aNewSearches[] = $oSearch;
256 } elseif ($sPhraseType == ''
257 && is_a($oSearchTerm, '\Nominatim\Token\SpecialTerm')
259 if ($this->iOperator == Operator::NONE) {
260 $oSearch = clone $this;
261 $oSearch->iSearchRank++;
263 $iOp = $oSearchTerm->iOperator;
264 if ($iOp == Operator::NONE) {
265 if (!empty($this->aName) || $this->oContext->isBoundedSearch()) {
266 $iOp = Operator::NAME;
268 $iOp = Operator::NEAR;
270 $oSearch->iSearchRank += 2;
273 $oSearch->setPoiSearch(
275 $oSearchTerm->sClass,
278 $aNewSearches[] = $oSearch;
280 } elseif ($sPhraseType != 'country'
281 && is_a($oSearchTerm, '\Nominatim\Token\Word')
283 $iWordID = $oSearchTerm->iId;
284 // Full words can only be a name if they appear at the beginning
285 // of the phrase. In structured search the name must forcably in
286 // the first phrase. In unstructured search it may be in a later
287 // phrase when the first phrase is a house number.
288 if (!empty($this->aName) || !($bFirstPhrase || $sPhraseType == '')) {
289 if (($sPhraseType == '' || !$bFirstPhrase) && !$bHasPartial) {
290 $oSearch = clone $this;
291 $oSearch->iSearchRank += 2;
292 $oSearch->aAddress[$iWordID] = $iWordID;
293 $aNewSearches[] = $oSearch;
295 $this->aFullNameAddress[$iWordID] = $iWordID;
298 $oSearch = clone $this;
299 $oSearch->iSearchRank++;
300 $oSearch->aName = array($iWordID => $iWordID);
301 if (CONST_Search_NameOnlySearchFrequencyThreshold) {
302 $oSearch->bRareName =
303 $oSearchTerm->iSearchNameCount
304 < CONST_Search_NameOnlySearchFrequencyThreshold;
306 $aNewSearches[] = $oSearch;
310 return $aNewSearches;
314 * Derive new searches by adding a partial term to the existing search.
316 * @param string $sToken Term for the token.
317 * @param object $oSearchTerm Description of the token.
318 * @param bool $bStructuredPhrases True if the search is structured.
319 * @param integer $iPhrase Number of the phrase the token is in.
320 * @param array[] $aFullTokens List of full term tokens with the
323 * @return SearchDescription[] List of derived search descriptions.
325 public function extendWithPartialTerm($sToken, $oSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
327 // Only allow name terms.
328 if (!(is_a($oSearchTerm, '\Nominatim\Token\Word'))) {
332 $aNewSearches = array();
333 $iWordID = $oSearchTerm->iId;
335 if ((!$bStructuredPhrases || $iPhrase > 0)
336 && (!empty($this->aName))
337 && strpos($sToken, ' ') === false
339 if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
340 $oSearch = clone $this;
341 $oSearch->iSearchRank += 2;
342 $oSearch->aAddress[$iWordID] = $iWordID;
343 $aNewSearches[] = $oSearch;
345 $oSearch = clone $this;
346 $oSearch->iSearchRank++;
347 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
348 if (preg_match('#^[0-9]+$#', $sToken)) {
349 $oSearch->iSearchRank += 2;
351 if (!empty($aFullTokens)) {
352 $oSearch->iSearchRank++;
354 $aNewSearches[] = $oSearch;
356 // revert to the token version?
357 foreach ($aFullTokens as $oSearchTermToken) {
358 if (is_a($oSearchTermToken, '\Nominatim\Token\Word')) {
359 $oSearch = clone $this;
360 $oSearch->iSearchRank++;
361 $oSearch->aAddress[$oSearchTermToken->iId]
362 = $oSearchTermToken->iId;
363 $aNewSearches[] = $oSearch;
369 if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
370 && (empty($this->aName) || $this->iNamePhrase == $iPhrase)
372 $oSearch = clone $this;
373 $oSearch->iSearchRank += 2;
374 if (empty($this->aName)) {
375 $oSearch->iSearchRank += 1;
377 if (preg_match('#^[0-9]+$#', $sToken)) {
378 $oSearch->iSearchRank += 2;
380 if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
381 if (empty($this->aName)
382 && CONST_Search_NameOnlySearchFrequencyThreshold
384 $oSearch->bRareName =
385 $oSearchTerm->iSearchNameCount
386 < CONST_Search_NameOnlySearchFrequencyThreshold;
388 $oSearch->bRareName = false;
390 $oSearch->aName[$iWordID] = $iWordID;
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
451 if ($this->sHouseNumber && !empty($aResults)) {
452 // Downgrade the rank of the street results, they are missing
454 foreach ($aResults as $oRes) {
455 $oRes->iResultRank++;
458 $aHnResults = $this->queryHouseNumber($oDB, $aResults);
460 if (!empty($aHnResults)) {
461 foreach ($aHnResults as $oRes) {
462 $aResults[$oRes->iId] = $oRes;
467 // finally get POIs if requested
468 if ($this->sClass && !empty($aResults)) {
469 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
473 Debug::printDebugTable('Place IDs', $aResults);
475 if (!empty($aResults) && $this->sPostcode) {
476 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
478 $sSQL = 'SELECT place_id FROM placex';
479 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
480 $sSQL .= " AND postcode != '".$this->sPostcode."'";
481 Debug::printSQL($sSQL);
482 $aFilteredPlaceIDs = $oDB->getCol($sSQL);
483 if ($aFilteredPlaceIDs) {
484 foreach ($aFilteredPlaceIDs as $iPlaceId) {
485 $aResults[$iPlaceId]->iResultRank++;
495 private function queryCountry(&$oDB)
497 $sSQL = 'SELECT place_id FROM placex ';
498 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
499 $sSQL .= ' AND rank_search = 4';
500 if ($this->oContext->bViewboxBounded) {
501 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
503 $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
505 Debug::printSQL($sSQL);
507 $iPlaceId = $oDB->getOne($sSQL);
511 $aResults[$iPlaceId] = new Result($iPlaceId);
517 private function queryNearbyPoi(&$oDB, $iLimit)
519 if (!$this->sClass) {
523 $aDBResults = array();
524 $sPoiTable = $this->poiTable();
526 if ($oDB->tableExists($sPoiTable)) {
527 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
528 if ($this->oContext->sqlCountryList) {
529 $sSQL .= ' JOIN placex USING (place_id)';
531 if ($this->oContext->hasNearPoint()) {
532 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
533 } elseif ($this->oContext->bViewboxBounded) {
534 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
536 if ($this->oContext->sqlCountryList) {
537 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
539 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
540 if ($this->oContext->sqlViewboxCentre) {
541 $sSQL .= ' ORDER BY ST_Distance(';
542 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
543 } elseif ($this->oContext->hasNearPoint()) {
544 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
546 $sSQL .= " LIMIT $iLimit";
547 Debug::printSQL($sSQL);
548 $aDBResults = $oDB->getCol($sSQL);
551 if ($this->oContext->hasNearPoint()) {
552 $sSQL = 'SELECT place_id FROM placex WHERE ';
553 $sSQL .= 'class = :class and type = :type';
554 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
555 $sSQL .= ' AND linked_place_id is null';
556 if ($this->oContext->sqlCountryList) {
557 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
559 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
560 $sSQL .= " LIMIT $iLimit";
561 Debug::printSQL($sSQL);
562 $aDBResults = $oDB->getCol(
564 array(':class' => $this->sClass, ':type' => $this->sType)
569 foreach ($aDBResults as $iPlaceId) {
570 $aResults[$iPlaceId] = new Result($iPlaceId);
576 private function queryPostcode(&$oDB, $iLimit)
578 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
580 if (!empty($this->aAddress)) {
581 $sSQL .= ', search_name s ';
582 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
583 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
584 $sSQL .= ' @> '.$oDB->getArraySQL($this->aAddress).' AND ';
589 $sSQL .= "p.postcode = '".reset($this->aName)."'";
590 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
591 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
592 $sSQL .= " LIMIT $iLimit";
594 Debug::printSQL($sSQL);
597 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
598 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
604 private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
609 // Sort by existence of the requested house number but only if not
610 // too many results are expected for the street, i.e. if the result
611 // will be narrowed down by an address. Remeber that with ordering
612 // every single result has to be checked.
613 if ($this->sHouseNumber && (!empty($this->aAddress) || $this->sPostcode)) {
614 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
616 $aOrder[0] .= 'EXISTS(';
617 $aOrder[0] .= ' SELECT place_id';
618 $aOrder[0] .= ' FROM placex';
619 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
620 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
621 $aOrder[0] .= ' LIMIT 1';
623 // also housenumbers from interpolation lines table are needed
624 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
625 $iHouseNumber = intval($this->sHouseNumber);
626 $aOrder[0] .= 'OR EXISTS(';
627 $aOrder[0] .= ' SELECT place_id ';
628 $aOrder[0] .= ' FROM location_property_osmline ';
629 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
630 $aOrder[0] .= ' AND startnumber is not NULL';
631 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
632 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
633 $aOrder[0] .= ' LIMIT 1';
636 $aOrder[0] .= ') DESC';
639 if (!empty($this->aName)) {
640 $aTerms[] = 'name_vector @> '.$oDB->getArraySQL($this->aName);
642 if (!empty($this->aAddress)) {
643 // For infrequent name terms disable index usage for address
644 if ($this->bRareName) {
645 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.$oDB->getArraySQL($this->aAddress);
647 $aTerms[] = 'nameaddress_vector @> '.$oDB->getArraySQL($this->aAddress);
651 $sCountryTerm = $this->countryCodeSQL('country_code');
653 $aTerms[] = $sCountryTerm;
656 if ($this->sHouseNumber) {
657 $aTerms[] = 'address_rank between 16 and 27';
658 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
659 if ($iMinAddressRank > 0) {
660 $aTerms[] = 'address_rank >= '.$iMinAddressRank;
662 if ($iMaxAddressRank < 30) {
663 $aTerms[] = 'address_rank <= '.$iMaxAddressRank;
667 if ($this->oContext->hasNearPoint()) {
668 $aTerms[] = $this->oContext->withinSQL('centroid');
669 $aOrder[] = $this->oContext->distanceSQL('centroid');
670 } elseif ($this->sPostcode) {
671 if (empty($this->aAddress)) {
672 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
674 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
678 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
680 $aTerms[] = $sExcludeSQL;
683 if ($this->oContext->bViewboxBounded) {
684 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
687 if ($this->oContext->hasNearPoint()) {
688 $aOrder[] = $this->oContext->distanceSQL('centroid');
691 if ($this->sHouseNumber) {
692 $sImportanceSQL = '- abs(26 - address_rank) + 3';
694 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
696 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
697 $aOrder[] = "$sImportanceSQL DESC";
699 if (!empty($this->aFullNameAddress)) {
700 $sExactMatchSQL = ' ( ';
701 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
702 $sExactMatchSQL .= ' SELECT unnest('.$oDB->getArraySQL($this->aFullNameAddress).')';
703 $sExactMatchSQL .= ' INTERSECT ';
704 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
705 $sExactMatchSQL .= ' ) s';
706 $sExactMatchSQL .= ') as exactmatch';
707 $aOrder[] = 'exactmatch DESC';
709 $sExactMatchSQL = '0::int as exactmatch';
712 if ($this->sHouseNumber || $this->sClass) {
718 if (!empty($aTerms)) {
719 $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
720 $sSQL .= ' FROM search_name';
721 $sSQL .= ' WHERE '.join(' and ', $aTerms);
722 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
723 $sSQL .= ' LIMIT '.$iLimit;
725 Debug::printSQL($sSQL);
727 $aDBResults = $oDB->getAll($sSQL, null, 'Could not get places for search terms.');
729 foreach ($aDBResults as $aResult) {
730 $oResult = new Result($aResult['place_id']);
731 $oResult->iExactMatches = $aResult['exactmatch'];
732 $aResults[$aResult['place_id']] = $oResult;
739 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
742 $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
748 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
749 $sSQL = 'SELECT place_id FROM placex ';
750 $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
751 $sSQL .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
752 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
754 Debug::printSQL($sSQL);
756 // XXX should inherit the exactMatches from its parent
757 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
758 $aResults[$iPlaceId] = new Result($iPlaceId);
761 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
762 $iHousenumber = intval($this->sHouseNumber);
763 if ($bIsIntHouseNumber && empty($aResults)) {
764 // if nothing found, search in the interpolation line table
765 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
766 $sSQL .= ' WHERE startnumber is not NULL';
767 $sSQL .= ' AND parent_place_id in ('.$sPlaceIDs.') AND (';
768 if ($iHousenumber % 2 == 0) {
769 // If housenumber is even, look for housenumber in streets
770 // with interpolationtype even or all.
771 $sSQL .= "interpolationtype='even'";
773 // Else look for housenumber with interpolationtype odd or all.
774 $sSQL .= "interpolationtype='odd'";
776 $sSQL .= " or interpolationtype='all') and ";
777 $sSQL .= $iHousenumber.'>=startnumber and ';
778 $sSQL .= $iHousenumber.'<=endnumber';
779 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
781 Debug::printSQL($sSQL);
783 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
784 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
785 $oResult->iHouseNumber = $iHousenumber;
786 $aResults[$iPlaceId] = $oResult;
790 // If nothing found try the aux fallback table
791 if (CONST_Use_Aux_Location_data && empty($aResults)) {
792 $sSQL = 'SELECT place_id FROM location_property_aux';
793 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
794 $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
795 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
797 Debug::printSQL($sSQL);
799 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
800 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
804 // If nothing found then search in Tiger data (location_property_tiger)
805 if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && empty($aResults)) {
806 $sSQL = 'SELECT place_id FROM location_property_tiger';
807 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
808 if ($iHousenumber % 2 == 0) {
809 $sSQL .= "interpolationtype='even'";
811 $sSQL .= "interpolationtype='odd'";
813 $sSQL .= " or interpolationtype='all') and ";
814 $sSQL .= $iHousenumber.'>=startnumber and ';
815 $sSQL .= $iHousenumber.'<=endnumber';
816 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
818 Debug::printSQL($sSQL);
820 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
821 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
822 $oResult->iHouseNumber = $iHousenumber;
823 $aResults[$iPlaceId] = $oResult;
831 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
834 $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
840 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
841 // If they were searching for a named class (i.e. 'Kings Head pub')
842 // then we might have an extra match
843 $sSQL = 'SELECT place_id FROM placex ';
844 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
845 $sSQL .= " AND class='".$this->sClass."' ";
846 $sSQL .= " AND type='".$this->sType."'";
847 $sSQL .= ' AND linked_place_id is null';
848 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
849 $sSQL .= ' ORDER BY rank_search ASC ';
850 $sSQL .= " LIMIT $iLimit";
852 Debug::printSQL($sSQL);
854 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
855 $aResults[$iPlaceId] = new Result($iPlaceId);
859 // NEAR and IN are handled the same
860 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
861 $sClassTable = $this->poiTable();
862 $bCacheTable = $oDB->tableExists($sClassTable);
864 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
865 Debug::printSQL($sSQL);
866 $iMaxRank = (int) $oDB->getOne($sSQL);
868 // For state / country level searches the normal radius search doesn't work very well
870 if ($iMaxRank < 9 && $bCacheTable) {
871 // Try and get a polygon to search in instead
872 $sSQL = 'SELECT geometry FROM placex';
873 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
874 $sSQL .= " AND rank_search < $iMaxRank + 5";
875 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
876 $sSQL .= ' ORDER BY rank_search ASC ';
878 Debug::printSQL($sSQL);
879 $sPlaceGeom = $oDB->getOne($sSQL);
886 $sSQL = 'SELECT place_id FROM placex';
887 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
888 Debug::printSQL($sSQL);
889 $aPlaceIDs = $oDB->getCol($sSQL);
890 $sPlaceIDs = join(',', $aPlaceIDs);
893 if ($sPlaceIDs || $sPlaceGeom) {
896 // More efficient - can make the range bigger
900 if ($this->oContext->hasNearPoint()) {
901 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
902 } elseif ($sPlaceIDs) {
903 $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
904 } elseif ($sPlaceGeom) {
905 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
908 $sSQL = 'SELECT distinct i.place_id';
910 $sSQL .= ', i.order_term';
912 $sSQL .= ' from (SELECT l.place_id';
914 $sSQL .= ','.$sOrderBySQL.' as order_term';
916 $sSQL .= ' from '.$sClassTable.' as l';
919 $sSQL .= ',placex as f WHERE ';
920 $sSQL .= "f.place_id in ($sPlaceIDs) ";
921 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
922 } elseif ($sPlaceGeom) {
923 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
926 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
927 $sSQL .= 'limit 300) i ';
929 $sSQL .= 'order by order_term asc';
931 $sSQL .= " limit $iLimit";
933 Debug::printSQL($sSQL);
935 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
936 $aResults[$iPlaceId] = new Result($iPlaceId);
939 if ($this->oContext->hasNearPoint()) {
940 $fRange = $this->oContext->nearRadius();
944 if ($this->oContext->hasNearPoint()) {
945 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
947 $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
950 $sSQL = 'SELECT distinct l.place_id';
952 $sSQL .= ','.$sOrderBySQL.' as orderterm';
954 $sSQL .= ' FROM placex as l, placex as f';
955 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
956 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
957 $sSQL .= " AND l.class='".$this->sClass."'";
958 $sSQL .= " AND l.type='".$this->sType."'";
959 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
961 $sSQL .= 'ORDER BY orderterm ASC';
963 $sSQL .= " limit $iLimit";
965 Debug::printSQL($sSQL);
967 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
968 $aResults[$iPlaceId] = new Result($iPlaceId);
977 private function poiTable()
979 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
982 private function countryCodeSQL($sVar)
984 if ($this->sCountryCode) {
985 return $sVar.' = \''.$this->sCountryCode."'";
987 if ($this->oContext->sqlCountryList) {
988 return $sVar.' in '.$this->oContext->sqlCountryList;
994 /////////// Sort functions
997 public static function bySearchRank($a, $b)
999 if ($a->iSearchRank == $b->iSearchRank) {
1000 return $a->iOperator + strlen($a->sHouseNumber)
1001 - $b->iOperator - strlen($b->sHouseNumber);
1004 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
1007 //////////// Debugging functions
1010 public function debugInfo()
1013 'Search rank' => $this->iSearchRank,
1014 'Country code' => $this->sCountryCode,
1015 'Name terms' => $this->aName,
1016 'Name terms (stop words)' => $this->aNameNonSearch,
1017 'Address terms' => $this->aAddress,
1018 'Address terms (stop words)' => $this->aAddressNonSearch,
1019 'Address terms (full words)' => $this->aFullNameAddress,
1020 'Special search' => $this->iOperator,
1021 'Class' => $this->sClass,
1022 'Type' => $this->sType,
1023 'House number' => $this->sHouseNumber,
1024 'Postcode' => $this->sPostcode
1028 public function dumpAsHtmlTableRow(&$aWordIDs)
1030 $kf = function ($k) use (&$aWordIDs) {
1031 return $aWordIDs[$k];
1035 echo "<td>$this->iSearchRank</td>";
1036 echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
1037 echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
1038 echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
1039 echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1040 echo '<td>'.$this->sCountryCode.'</td>';
1041 echo '<td>'.Operator::toString($this->iOperator).'</td>';
1042 echo '<td>'.$this->sClass.'</td>';
1043 echo '<td>'.$this->sType.'</td>';
1044 echo '<td>'.$this->sPostcode.'</td>';
1045 echo '<td>'.$this->sHouseNumber.'</td>';