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 * Extract key/value pairs from a query.
73 * Key/value pairs are recognised if they are of the form [<key>=<value>].
74 * If multiple terms of this kind are found then all terms are removed
75 * but only the first is used for search.
77 * @param string $sQuery Original query string.
79 * @return string The query string with the special search patterns removed.
81 public function extractKeyValuePairs($sQuery)
83 // Search for terms of kind [<key>=<value>].
85 '/\\[([\\w_]*)=([\\w_]*)\\]/',
91 foreach ($aSpecialTermsRaw as $aTerm) {
92 $sQuery = str_replace($aTerm[0], ' ', $sQuery);
93 if (!$this->hasOperator()) {
94 $this->setPoiSearch(Operator::TYPE, $aTerm[1], $aTerm[2]);
102 * Check if the combination of parameters is sensible.
104 * @return bool True, if the search looks valid.
106 public function isValidSearch()
108 if (empty($this->aName)) {
109 if ($this->sHouseNumber) {
112 if (!$this->sClass && !$this->sCountryCode) {
120 /////////// Search building functions
123 * Create a copy of this search description adding to search rank.
125 * @param integer $iTermCost Cost to add to the current search rank.
127 * @return object Cloned search description.
129 public function clone($iTermCost)
131 $oSearch = clone $this;
132 $oSearch->iSearchRank += $iTermCost;
138 * Check if the search currently includes a name.
140 * @param bool bIncludeNonNames If true stop-word tokens are taken into
143 * @return bool True, if search has a name.
145 public function hasName($bIncludeNonNames = false)
147 return !empty($this->aName)
148 || (!empty($this->aNameNonSearch) && $bIncludeNonNames);
152 * Check if the search currently includes an address term.
154 * @return bool True, if any address term is included, including stop-word
157 public function hasAddress()
159 return !empty($this->aAddress) || !empty($this->aAddressNonSearch);
163 * Check if a country restriction is currently included in the search.
165 * @return bool True, if a country restriction is set.
167 public function hasCountry()
169 return $this->sCountryCode !== '';
173 * Check if a postcode is currently included in the search.
175 * @return bool True, if a postcode is set.
177 public function hasPostcode()
179 return $this->sPostcode !== '';
183 * Check if a house number is set for the search.
185 * @return bool True, if a house number is set.
187 public function hasHousenumber()
189 return $this->sHouseNumber !== '';
193 * Check if a special type of place is requested.
195 * param integer iOperator When set, check for the particular
196 * operator used for the special type.
198 * @return bool True, if speial type is requested or, if requested,
199 * a special type with the given operator.
201 public function hasOperator($iOperator = null)
203 return $iOperator === null ? $this->iOperator != Operator::NONE : $this->iOperator == $iOperator;
207 * Add the given token to the list of terms to search for in the address.
209 * @param integer iID ID of term to add.
210 * @param bool bSearchable Term should be used to search for result
211 * (i.e. term is not a stop word).
213 public function addAddressToken($iId, $bSearchable = true)
216 $this->aAddress[$iId] = $iId;
218 $this->aAddressNonSearch[$iId] = $iId;
223 * Add the given full-word token to the list of terms to search for in the
226 * @param interger iId ID of term to add.
227 * @param bool bRareName True if the term is infrequent enough to not
228 * require other constraints for efficient search.
230 public function addNameToken($iId, $bRareName)
232 $this->aName[$iId] = $iId;
233 $this->bRareName = $bRareName;
237 * Add the given partial token to the list of terms to search for in
240 * @param integer iID ID of term to add.
241 * @param bool bSearchable Term should be used to search for result
242 * (i.e. term is not a stop word).
243 * @param integer iPhraseNumber Index of phrase, where the partial term
246 public function addPartialNameToken($iId, $bSearchable, $iPhraseNumber)
249 $this->aName[$iId] = $iId;
251 $this->aNameNonSearch[$iId] = $iId;
253 $this->iNamePhrase = $iPhraseNumber;
257 * Set country restriction for the search.
259 * @param string sCountryCode Country code of country to restrict search to.
261 public function setCountry($sCountryCode)
263 $this->sCountryCode = $sCountryCode;
264 $this->iNamePhrase = -1;
268 * Set postcode search constraint.
270 * @param string sPostcode Postcode the result should have.
272 public function setPostcode($sPostcode)
274 $this->sPostcode = $sPostcode;
275 $this->iNamePhrase = -1;
279 * Make this search a search for a postcode object.
281 * @param integer iId Token Id for the postcode.
282 * @param string sPostcode Postcode to look for.
284 public function setPostcodeAsName($iId, $sPostcode)
286 $this->iOperator = Operator::POSTCODE;
287 $this->aAddress = array_merge($this->aAddress, $this->aName);
288 $this->aName = array($iId => $sPostcode);
289 $this->bRareName = true;
290 $this->iNamePhrase = -1;
294 * Set house number search cnstraint.
296 * @param string sNumber House number the result should have.
298 public function setHousenumber($sNumber)
300 $this->sHouseNumber = $sNumber;
301 $this->iNamePhrase = -1;
305 * Make this search a search for a house number.
307 * @param integer iId Token Id for the house number.
309 public function setHousenumberAsName($iId)
311 $this->aAddress = array_merge($this->aAddress, $this->aName);
312 $this->bRareName = false;
313 $this->aName = array($iId => $iId);
314 $this->iNamePhrase = -1;
318 * Make this search a POI search.
320 * In a POI search, objects are not (only) searched by their name
321 * but also by the primary OSM key/value pair (class and type in Nominatim).
323 * @param integer $iOperator Type of POI search
324 * @param string $sClass Class (or OSM tag key) of POI.
325 * @param string $sType Type (or OSM tag value) of POI.
329 public function setPoiSearch($iOperator, $sClass, $sType)
331 $this->iOperator = $iOperator;
332 $this->sClass = $sClass;
333 $this->sType = $sType;
334 $this->iNamePhrase = -1;
337 public function getNamePhrase()
339 return $this->iNamePhrase;
343 * Get the global search context.
345 * @return object Objects of global search constraints.
347 public function getContext()
349 return $this->oContext;
352 /////////// Query functions
356 * Query database for places that match this search.
358 * @param object $oDB Nominatim::DB instance to use.
359 * @param integer $iMinRank Minimum address rank to restrict search to.
360 * @param integer $iMaxRank Maximum address rank to restrict search to.
361 * @param integer $iLimit Maximum number of results.
363 * @return mixed[] An array with two fields: IDs contains the list of
364 * matching place IDs and houseNumber the houseNumber
365 * if appicable or -1 if not.
367 public function query(&$oDB, $iMinRank, $iMaxRank, $iLimit)
371 if ($this->sCountryCode
372 && empty($this->aName)
375 && !$this->oContext->hasNearPoint()
377 // Just looking for a country - look it up
378 if (4 >= $iMinRank && 4 <= $iMaxRank) {
379 $aResults = $this->queryCountry($oDB);
381 } elseif (empty($this->aName) && empty($this->aAddress)) {
382 // Neither name nor address? Then we must be
383 // looking for a POI in a geographic area.
384 if ($this->oContext->isBoundedSearch()) {
385 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
387 } elseif ($this->iOperator == Operator::POSTCODE) {
388 // looking for postcode
389 $aResults = $this->queryPostcode($oDB, $iLimit);
392 // First search for places according to name and address.
393 $aResults = $this->queryNamedPlace(
400 // Now search for housenumber, if housenumber provided. Can be zero.
401 if (($this->sHouseNumber || $this->sHouseNumber === '0') && !empty($aResults)) {
402 $aHnResults = $this->queryHouseNumber($oDB, $aResults);
404 // Downgrade the rank of the street results, they are missing
405 // the housenumber. Also drop POI places (rank 30) here, they
406 // cannot be a parent place and therefore must not be shown
407 // as a result for a search with a missing housenumber.
408 foreach ($aResults as $oRes) {
409 if ($oRes->iAddressRank < 28) {
410 if ($oRes->iAddressRank >= 26) {
411 $oRes->iResultRank++;
413 $oRes->iResultRank += 2;
415 $aHnResults[$oRes->iId] = $oRes;
419 $aResults = $aHnResults;
422 // finally get POIs if requested
423 if ($this->sClass && !empty($aResults)) {
424 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
428 Debug::printDebugTable('Place IDs', $aResults);
430 if (!empty($aResults) && $this->sPostcode) {
431 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
433 $sSQL = 'SELECT place_id FROM placex';
434 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
435 $sSQL .= " AND postcode != '".$this->sPostcode."'";
436 Debug::printSQL($sSQL);
437 $aFilteredPlaceIDs = $oDB->getCol($sSQL);
438 if ($aFilteredPlaceIDs) {
439 foreach ($aFilteredPlaceIDs as $iPlaceId) {
440 $aResults[$iPlaceId]->iResultRank++;
450 private function queryCountry(&$oDB)
452 $sSQL = 'SELECT place_id FROM placex ';
453 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
454 $sSQL .= ' AND rank_search = 4';
455 if ($this->oContext->bViewboxBounded) {
456 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
458 $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
460 Debug::printSQL($sSQL);
462 $iPlaceId = $oDB->getOne($sSQL);
466 $aResults[$iPlaceId] = new Result($iPlaceId);
472 private function queryNearbyPoi(&$oDB, $iLimit)
474 if (!$this->sClass) {
478 $aDBResults = array();
479 $sPoiTable = $this->poiTable();
481 if ($oDB->tableExists($sPoiTable)) {
482 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
483 if ($this->oContext->sqlCountryList) {
484 $sSQL .= ' JOIN placex USING (place_id)';
486 if ($this->oContext->hasNearPoint()) {
487 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
488 } elseif ($this->oContext->bViewboxBounded) {
489 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
491 if ($this->oContext->sqlCountryList) {
492 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
494 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
495 if ($this->oContext->sqlViewboxCentre) {
496 $sSQL .= ' ORDER BY ST_Distance(';
497 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
498 } elseif ($this->oContext->hasNearPoint()) {
499 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
501 $sSQL .= " LIMIT $iLimit";
502 Debug::printSQL($sSQL);
503 $aDBResults = $oDB->getCol($sSQL);
506 if ($this->oContext->hasNearPoint()) {
507 $sSQL = 'SELECT place_id FROM placex WHERE ';
508 $sSQL .= 'class = :class and type = :type';
509 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
510 $sSQL .= ' AND linked_place_id is null';
511 if ($this->oContext->sqlCountryList) {
512 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
514 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
515 $sSQL .= " LIMIT $iLimit";
516 Debug::printSQL($sSQL);
517 $aDBResults = $oDB->getCol(
519 array(':class' => $this->sClass, ':type' => $this->sType)
524 foreach ($aDBResults as $iPlaceId) {
525 $aResults[$iPlaceId] = new Result($iPlaceId);
531 private function queryPostcode(&$oDB, $iLimit)
533 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
535 if (!empty($this->aAddress)) {
536 $sSQL .= ', search_name s ';
537 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
538 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
539 $sSQL .= ' @> '.$oDB->getArraySQL($this->aAddress).' AND ';
544 $sSQL .= "p.postcode = '".reset($this->aName)."'";
545 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
546 if ($this->oContext->bViewboxBounded) {
547 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
549 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
550 $sSQL .= " LIMIT $iLimit";
552 Debug::printSQL($sSQL);
555 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
556 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
562 private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
567 // Sort by existence of the requested house number but only if not
568 // too many results are expected for the street, i.e. if the result
569 // will be narrowed down by an address. Remeber that with ordering
570 // every single result has to be checked.
571 if ($this->sHouseNumber && ($this->bRareName || !empty($this->aAddress) || $this->sPostcode)) {
572 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
574 $aOrder[0] .= 'EXISTS(';
575 $aOrder[0] .= ' SELECT place_id';
576 $aOrder[0] .= ' FROM placex';
577 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
578 $aOrder[0] .= " AND housenumber ~* E'".$sHouseNumberRegex."'";
579 $aOrder[0] .= ' LIMIT 1';
581 // also housenumbers from interpolation lines table are needed
582 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
583 $iHouseNumber = intval($this->sHouseNumber);
584 $aOrder[0] .= 'OR EXISTS(';
585 $aOrder[0] .= ' SELECT place_id ';
586 $aOrder[0] .= ' FROM location_property_osmline ';
587 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
588 $aOrder[0] .= ' AND startnumber is not NULL';
589 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
590 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
591 $aOrder[0] .= ' LIMIT 1';
594 $aOrder[0] .= ') DESC';
597 if (!empty($this->aName)) {
598 $aTerms[] = 'name_vector @> '.$oDB->getArraySQL($this->aName);
600 if (!empty($this->aAddress)) {
601 // For infrequent name terms disable index usage for address
602 if ($this->bRareName) {
603 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.$oDB->getArraySQL($this->aAddress);
605 $aTerms[] = 'nameaddress_vector @> '.$oDB->getArraySQL($this->aAddress);
609 $sCountryTerm = $this->countryCodeSQL('country_code');
611 $aTerms[] = $sCountryTerm;
614 if ($this->sHouseNumber) {
615 $aTerms[] = 'address_rank between 16 and 30';
616 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
617 if ($iMinAddressRank > 0) {
618 $aTerms[] = "((address_rank between $iMinAddressRank and $iMaxAddressRank) or (search_rank between $iMinAddressRank and $iMaxAddressRank))";
622 if ($this->oContext->hasNearPoint()) {
623 $aTerms[] = $this->oContext->withinSQL('centroid');
624 $aOrder[] = $this->oContext->distanceSQL('centroid');
625 } elseif ($this->sPostcode) {
626 if (empty($this->aAddress)) {
627 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
629 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
633 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
635 $aTerms[] = $sExcludeSQL;
638 if ($this->oContext->bViewboxBounded) {
639 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
642 if ($this->oContext->hasNearPoint()) {
643 $aOrder[] = $this->oContext->distanceSQL('centroid');
646 if ($this->sHouseNumber) {
647 $sImportanceSQL = '- abs(26 - address_rank) + 3';
649 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
651 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
652 $aOrder[] = "$sImportanceSQL DESC";
654 $aFullNameAddress = $this->oContext->getFullNameTerms();
655 if (!empty($aFullNameAddress)) {
656 $sExactMatchSQL = ' ( ';
657 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
658 $sExactMatchSQL .= ' SELECT unnest('.$oDB->getArraySQL($aFullNameAddress).')';
659 $sExactMatchSQL .= ' INTERSECT ';
660 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
661 $sExactMatchSQL .= ' ) s';
662 $sExactMatchSQL .= ') as exactmatch';
663 $aOrder[] = 'exactmatch DESC';
665 $sExactMatchSQL = '0::int as exactmatch';
668 if ($this->sHouseNumber || $this->sClass) {
674 if (!empty($aTerms)) {
675 $sSQL = 'SELECT place_id, address_rank,'.$sExactMatchSQL;
676 $sSQL .= ' FROM search_name';
677 $sSQL .= ' WHERE '.join(' and ', $aTerms);
678 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
679 $sSQL .= ' LIMIT '.$iLimit;
681 Debug::printSQL($sSQL);
683 $aDBResults = $oDB->getAll($sSQL, null, 'Could not get places for search terms.');
685 foreach ($aDBResults as $aResult) {
686 $oResult = new Result($aResult['place_id']);
687 $oResult->iExactMatches = $aResult['exactmatch'];
688 $oResult->iAddressRank = $aResult['address_rank'];
689 $aResults[$aResult['place_id']] = $oResult;
696 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
699 $sRoadPlaceIDs = Result::joinIdsByTableMaxRank(
701 Result::TABLE_PLACEX,
704 $sPOIPlaceIDs = Result::joinIdsByTableMinRank(
706 Result::TABLE_PLACEX,
710 $aIDCondition = array();
711 if ($sRoadPlaceIDs) {
712 $aIDCondition[] = 'parent_place_id in ('.$sRoadPlaceIDs.')';
715 $aIDCondition[] = 'place_id in ('.$sPOIPlaceIDs.')';
718 if (empty($aIDCondition)) {
722 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
723 $sSQL = 'SELECT place_id FROM placex WHERE';
724 $sSQL .= " housenumber ~* E'".$sHouseNumberRegex."'";
725 $sSQL .= ' AND ('.join(' OR ', $aIDCondition).')';
726 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
728 Debug::printSQL($sSQL);
730 // XXX should inherit the exactMatches from its parent
731 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
732 $aResults[$iPlaceId] = new Result($iPlaceId);
735 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
736 $iHousenumber = intval($this->sHouseNumber);
737 if ($bIsIntHouseNumber && $sRoadPlaceIDs && empty($aResults)) {
738 // if nothing found, search in the interpolation line table
739 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
740 $sSQL .= ' WHERE startnumber is not NULL';
741 $sSQL .= ' AND parent_place_id in ('.$sRoadPlaceIDs.') AND (';
742 if ($iHousenumber % 2 == 0) {
743 // If housenumber is even, look for housenumber in streets
744 // with interpolationtype even or all.
745 $sSQL .= "interpolationtype='even'";
747 // Else look for housenumber with interpolationtype odd or all.
748 $sSQL .= "interpolationtype='odd'";
750 $sSQL .= " or interpolationtype='all') and ";
751 $sSQL .= $iHousenumber.'>=startnumber and ';
752 $sSQL .= $iHousenumber.'<=endnumber';
753 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
755 Debug::printSQL($sSQL);
757 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
758 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
759 $oResult->iHouseNumber = $iHousenumber;
760 $aResults[$iPlaceId] = $oResult;
764 // If nothing found then search in Tiger data (location_property_tiger)
765 if (CONST_Use_US_Tiger_Data && $sRoadPlaceIDs && $bIsIntHouseNumber && empty($aResults)) {
766 $sSQL = 'SELECT place_id FROM location_property_tiger';
767 $sSQL .= ' WHERE parent_place_id in ('.$sRoadPlaceIDs.') and (';
768 if ($iHousenumber % 2 == 0) {
769 $sSQL .= "interpolationtype='even'";
771 $sSQL .= "interpolationtype='odd'";
773 $sSQL .= " or interpolationtype='all') and ";
774 $sSQL .= $iHousenumber.'>=startnumber and ';
775 $sSQL .= $iHousenumber.'<=endnumber';
776 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
778 Debug::printSQL($sSQL);
780 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
781 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
782 $oResult->iHouseNumber = $iHousenumber;
783 $aResults[$iPlaceId] = $oResult;
791 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
794 $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
800 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
801 // If they were searching for a named class (i.e. 'Kings Head pub')
802 // then we might have an extra match
803 $sSQL = 'SELECT place_id FROM placex ';
804 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
805 $sSQL .= " AND class='".$this->sClass."' ";
806 $sSQL .= " AND type='".$this->sType."'";
807 $sSQL .= ' AND linked_place_id is null';
808 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
809 $sSQL .= ' ORDER BY rank_search ASC ';
810 $sSQL .= " LIMIT $iLimit";
812 Debug::printSQL($sSQL);
814 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
815 $aResults[$iPlaceId] = new Result($iPlaceId);
819 // NEAR and IN are handled the same
820 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
821 $sClassTable = $this->poiTable();
822 $bCacheTable = $oDB->tableExists($sClassTable);
824 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
825 Debug::printSQL($sSQL);
826 $iMaxRank = (int) $oDB->getOne($sSQL);
828 // For state / country level searches the normal radius search doesn't work very well
830 if ($iMaxRank < 9 && $bCacheTable) {
831 // Try and get a polygon to search in instead
832 $sSQL = 'SELECT geometry FROM placex';
833 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
834 $sSQL .= " AND rank_search < $iMaxRank + 5";
835 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
836 $sSQL .= ' ORDER BY rank_search ASC ';
838 Debug::printSQL($sSQL);
839 $sPlaceGeom = $oDB->getOne($sSQL);
846 $sSQL = 'SELECT place_id FROM placex';
847 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
848 Debug::printSQL($sSQL);
849 $aPlaceIDs = $oDB->getCol($sSQL);
850 $sPlaceIDs = join(',', $aPlaceIDs);
853 if ($sPlaceIDs || $sPlaceGeom) {
856 // More efficient - can make the range bigger
860 if ($this->oContext->hasNearPoint()) {
861 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
862 } elseif ($sPlaceIDs) {
863 $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
864 } elseif ($sPlaceGeom) {
865 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
868 $sSQL = 'SELECT distinct i.place_id';
870 $sSQL .= ', i.order_term';
872 $sSQL .= ' from (SELECT l.place_id';
874 $sSQL .= ','.$sOrderBySQL.' as order_term';
876 $sSQL .= ' from '.$sClassTable.' as l';
879 $sSQL .= ',placex as f WHERE ';
880 $sSQL .= "f.place_id in ($sPlaceIDs) ";
881 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
882 } elseif ($sPlaceGeom) {
883 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
886 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
887 $sSQL .= 'limit 300) i ';
889 $sSQL .= 'order by order_term asc';
891 $sSQL .= " limit $iLimit";
893 Debug::printSQL($sSQL);
895 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
896 $aResults[$iPlaceId] = new Result($iPlaceId);
899 if ($this->oContext->hasNearPoint()) {
900 $fRange = $this->oContext->nearRadius();
904 if ($this->oContext->hasNearPoint()) {
905 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
907 $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
910 $sSQL = 'SELECT distinct l.place_id';
912 $sSQL .= ','.$sOrderBySQL.' as orderterm';
914 $sSQL .= ' FROM placex as l, placex as f';
915 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
916 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
917 $sSQL .= " AND l.class='".$this->sClass."'";
918 $sSQL .= " AND l.type='".$this->sType."'";
919 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
921 $sSQL .= 'ORDER BY orderterm ASC';
923 $sSQL .= " limit $iLimit";
925 Debug::printSQL($sSQL);
927 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
928 $aResults[$iPlaceId] = new Result($iPlaceId);
937 private function poiTable()
939 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
942 private function countryCodeSQL($sVar)
944 if ($this->sCountryCode) {
945 return $sVar.' = \''.$this->sCountryCode."'";
947 if ($this->oContext->sqlCountryList) {
948 return $sVar.' in '.$this->oContext->sqlCountryList;
954 /////////// Sort functions
957 public static function bySearchRank($a, $b)
959 if ($a->iSearchRank == $b->iSearchRank) {
960 return $a->iOperator + strlen($a->sHouseNumber)
961 - $b->iOperator - strlen($b->sHouseNumber);
964 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
967 //////////// Debugging functions
970 public function debugInfo()
973 'Search rank' => $this->iSearchRank,
974 'Country code' => $this->sCountryCode,
975 'Name terms' => $this->aName,
976 'Name terms (stop words)' => $this->aNameNonSearch,
977 'Address terms' => $this->aAddress,
978 'Address terms (stop words)' => $this->aAddressNonSearch,
979 'Address terms (full words)' => $this->aFullNameAddress ?? '',
980 'Special search' => $this->iOperator,
981 'Class' => $this->sClass,
982 'Type' => $this->sType,
983 'House number' => $this->sHouseNumber,
984 'Postcode' => $this->sPostcode
988 public function dumpAsHtmlTableRow(&$aWordIDs)
990 $kf = function ($k) use (&$aWordIDs) {
991 return $aWordIDs[$k] ?? '['.$k.']';
995 echo "<td>$this->iSearchRank</td>";
996 echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
997 echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
998 echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
999 echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1000 echo '<td>'.$this->sCountryCode.'</td>';
1001 echo '<td>'.Operator::toString($this->iOperator).'</td>';
1002 echo '<td>'.$this->sClass.'</td>';
1003 echo '<td>'.$this->sType.'</td>';
1004 echo '<td>'.$this->sPostcode.'</td>';
1005 echo '<td>'.$this->sHouseNumber.'</td>';