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 /// True if the name requires to be accompanied by address terms.
23 private $bNameNeedsAddress = false;
24 /// List of word ids making up the address of the object.
25 private $aAddress = 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 * Extract key/value pairs from a query.
75 * Key/value pairs are recognised if they are of the form [<key>=<value>].
76 * If multiple terms of this kind are found then all terms are removed
77 * but only the first is used for search.
79 * @param string $sQuery Original query string.
81 * @return string The query string with the special search patterns removed.
83 public function extractKeyValuePairs($sQuery)
85 // Search for terms of kind [<key>=<value>].
87 '/\\[([\\w_]*)=([\\w_]*)\\]/',
93 foreach ($aSpecialTermsRaw as $aTerm) {
94 $sQuery = str_replace($aTerm[0], ' ', $sQuery);
95 if (!$this->hasOperator()) {
96 $this->setPoiSearch(Operator::TYPE, $aTerm[1], $aTerm[2]);
104 * Check if the combination of parameters is sensible.
106 * @return bool True, if the search looks valid.
108 public function isValidSearch()
110 if (empty($this->aName)) {
111 if ($this->sHouseNumber) {
114 if (!$this->sClass && !$this->sCountryCode) {
118 if ($this->bNameNeedsAddress && empty($this->aAddress)) {
125 /////////// Search building functions
128 * Create a copy of this search description adding to search rank.
130 * @param integer $iTermCost Cost to add to the current search rank.
132 * @return object Cloned search description.
134 public function clone($iTermCost)
136 $oSearch = clone $this;
137 $oSearch->iSearchRank += $iTermCost;
143 * Check if the search currently includes a name.
145 * @param bool bIncludeNonNames If true stop-word tokens are taken into
148 * @return bool True, if search has a name.
150 public function hasName($bIncludeNonNames = false)
152 return !empty($this->aName)
153 || (!empty($this->aNameNonSearch) && $bIncludeNonNames);
157 * Check if the search currently includes an address term.
159 * @return bool True, if any address term is included, including stop-word
162 public function hasAddress()
164 return !empty($this->aAddress) || !empty($this->aAddressNonSearch);
168 * Check if a country restriction is currently included in the search.
170 * @return bool True, if a country restriction is set.
172 public function hasCountry()
174 return $this->sCountryCode !== '';
178 * Check if a postcode is currently included in the search.
180 * @return bool True, if a postcode is set.
182 public function hasPostcode()
184 return $this->sPostcode !== '';
188 * Check if a house number is set for the search.
190 * @return bool True, if a house number is set.
192 public function hasHousenumber()
194 return $this->sHouseNumber !== '';
198 * Check if a special type of place is requested.
200 * param integer iOperator When set, check for the particular
201 * operator used for the special type.
203 * @return bool True, if speial type is requested or, if requested,
204 * a special type with the given operator.
206 public function hasOperator($iOperator = null)
208 return $iOperator === null ? $this->iOperator != Operator::NONE : $this->iOperator == $iOperator;
212 * Add the given token to the list of terms to search for in the address.
214 * @param integer iID ID of term to add.
215 * @param bool bSearchable Term should be used to search for result
216 * (i.e. term is not a stop word).
218 public function addAddressToken($iId, $bSearchable = true)
221 $this->aAddress[$iId] = $iId;
223 $this->aAddressNonSearch[$iId] = $iId;
228 * Add the given full-word token to the list of terms to search for in the
231 * @param interger iId ID of term to add.
232 * @param bool bRareName True if the term is infrequent enough to not
233 * require other constraints for efficient search.
235 public function addNameToken($iId, $bRareName)
237 $this->aName[$iId] = $iId;
238 $this->bRareName = $bRareName;
239 $this->bNeedsAddress = false;
243 * Add the given partial token to the list of terms to search for in
246 * @param integer iID ID of term to add.
247 * @param bool bSearchable Term should be used to search for result
248 * (i.e. term is not a stop word).
249 * @param bool bNeedsAddress True if the term is too unspecific to be used
250 * in a stand-alone search without an address
251 * to narrow down the search.
252 * @param integer iPhraseNumber Index of phrase, where the partial term
255 public function addPartialNameToken($iId, $bSearchable, $bNeedsAddress, $iPhraseNumber)
257 if (empty($this->aName)) {
258 $this->bNameNeedsAddress = $bNeedsAddress;
260 $this->bNameNeedsAddress |= $bNeedsAddress;
263 $this->aName[$iId] = $iId;
265 $this->aNameNonSearch[$iId] = $iId;
267 $this->iNamePhrase = $iPhraseNumber;
271 * Set country restriction for the search.
273 * @param string sCountryCode Country code of country to restrict search to.
275 public function setCountry($sCountryCode)
277 $this->sCountryCode = $sCountryCode;
278 $this->iNamePhrase = -1;
282 * Set postcode search constraint.
284 * @param string sPostcode Postcode the result should have.
286 public function setPostcode($sPostcode)
288 $this->sPostcode = $sPostcode;
289 $this->iNamePhrase = -1;
293 * Make this search a search for a postcode object.
295 * @param integer iId Token Id for the postcode.
296 * @param string sPostcode Postcode to look for.
298 public function setPostcodeAsName($iId, $sPostcode)
300 $this->iOperator = Operator::POSTCODE;
301 $this->aAddress = array_merge($this->aAddress, $this->aName);
302 $this->aName = array($iId => $sPostcode);
303 $this->bRareName = true;
304 $this->iNamePhrase = -1;
308 * Set house number search cnstraint.
310 * @param string sNumber House number the result should have.
312 public function setHousenumber($sNumber)
314 $this->sHouseNumber = $sNumber;
315 $this->iNamePhrase = -1;
319 * Make this search a search for a house number.
321 * @param integer iId Token Id for the house number.
323 public function setHousenumberAsName($iId)
325 $this->aAddress = array_merge($this->aAddress, $this->aName);
326 $this->bRareName = false;
327 $this->aName = array($iId => $iId);
328 $this->iNamePhrase = -1;
332 * Make this search a POI search.
334 * In a POI search, objects are not (only) searched by their name
335 * but also by the primary OSM key/value pair (class and type in Nominatim).
337 * @param integer $iOperator Type of POI search
338 * @param string $sClass Class (or OSM tag key) of POI.
339 * @param string $sType Type (or OSM tag value) of POI.
343 public function setPoiSearch($iOperator, $sClass, $sType)
345 $this->iOperator = $iOperator;
346 $this->sClass = $sClass;
347 $this->sType = $sType;
348 $this->iNamePhrase = -1;
351 public function getNamePhrase()
353 return $this->iNamePhrase;
357 * Get the global search context.
359 * @return object Objects of global search constraints.
361 public function getContext()
363 return $this->oContext;
366 /////////// Query functions
370 * Query database for places that match this search.
372 * @param object $oDB Nominatim::DB instance to use.
373 * @param integer $iMinRank Minimum address rank to restrict search to.
374 * @param integer $iMaxRank Maximum address rank to restrict search to.
375 * @param integer $iLimit Maximum number of results.
377 * @return mixed[] An array with two fields: IDs contains the list of
378 * matching place IDs and houseNumber the houseNumber
379 * if appicable or -1 if not.
381 public function query(&$oDB, $iMinRank, $iMaxRank, $iLimit)
385 if ($this->sCountryCode
386 && empty($this->aName)
389 && !$this->oContext->hasNearPoint()
391 // Just looking for a country - look it up
392 if (4 >= $iMinRank && 4 <= $iMaxRank) {
393 $aResults = $this->queryCountry($oDB);
395 } elseif (empty($this->aName) && empty($this->aAddress)) {
396 // Neither name nor address? Then we must be
397 // looking for a POI in a geographic area.
398 if ($this->oContext->isBoundedSearch()) {
399 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
401 } elseif ($this->iOperator == Operator::POSTCODE) {
402 // looking for postcode
403 $aResults = $this->queryPostcode($oDB, $iLimit);
406 // First search for places according to name and address.
407 $aResults = $this->queryNamedPlace(
414 // Now search for housenumber, if housenumber provided. Can be zero.
415 if (($this->sHouseNumber || $this->sHouseNumber === '0') && !empty($aResults)) {
416 $aHnResults = $this->queryHouseNumber($oDB, $aResults);
418 // Downgrade the rank of the street results, they are missing
419 // the housenumber. Also drop POI places (rank 30) here, they
420 // cannot be a parent place and therefore must not be shown
421 // as a result for a search with a missing housenumber.
422 foreach ($aResults as $oRes) {
423 if ($oRes->iAddressRank < 28) {
424 if ($oRes->iAddressRank >= 26) {
425 $oRes->iResultRank++;
427 $oRes->iResultRank += 2;
429 $aHnResults[$oRes->iId] = $oRes;
433 $aResults = $aHnResults;
436 // finally get POIs if requested
437 if ($this->sClass && !empty($aResults)) {
438 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
442 Debug::printDebugTable('Place IDs', $aResults);
444 if (!empty($aResults) && $this->sPostcode) {
445 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
447 $sSQL = 'SELECT place_id FROM placex';
448 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
449 $sSQL .= " AND postcode != '".$this->sPostcode."'";
450 Debug::printSQL($sSQL);
451 $aFilteredPlaceIDs = $oDB->getCol($sSQL);
452 if ($aFilteredPlaceIDs) {
453 foreach ($aFilteredPlaceIDs as $iPlaceId) {
454 $aResults[$iPlaceId]->iResultRank++;
464 private function queryCountry(&$oDB)
466 $sSQL = 'SELECT place_id FROM placex ';
467 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
468 $sSQL .= ' AND rank_search = 4';
469 if ($this->oContext->bViewboxBounded) {
470 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
472 $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
474 Debug::printSQL($sSQL);
476 $iPlaceId = $oDB->getOne($sSQL);
480 $aResults[$iPlaceId] = new Result($iPlaceId);
486 private function queryNearbyPoi(&$oDB, $iLimit)
488 if (!$this->sClass) {
492 $aDBResults = array();
493 $sPoiTable = $this->poiTable();
495 if ($oDB->tableExists($sPoiTable)) {
496 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
497 if ($this->oContext->sqlCountryList) {
498 $sSQL .= ' JOIN placex USING (place_id)';
500 if ($this->oContext->hasNearPoint()) {
501 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
502 } elseif ($this->oContext->bViewboxBounded) {
503 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
505 if ($this->oContext->sqlCountryList) {
506 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
508 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
509 if ($this->oContext->sqlViewboxCentre) {
510 $sSQL .= ' ORDER BY ST_Distance(';
511 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
512 } elseif ($this->oContext->hasNearPoint()) {
513 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
515 $sSQL .= " LIMIT $iLimit";
516 Debug::printSQL($sSQL);
517 $aDBResults = $oDB->getCol($sSQL);
520 if ($this->oContext->hasNearPoint()) {
521 $sSQL = 'SELECT place_id FROM placex WHERE ';
522 $sSQL .= 'class = :class and type = :type';
523 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
524 $sSQL .= ' AND linked_place_id is null';
525 if ($this->oContext->sqlCountryList) {
526 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
528 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
529 $sSQL .= " LIMIT $iLimit";
530 Debug::printSQL($sSQL);
531 $aDBResults = $oDB->getCol(
533 array(':class' => $this->sClass, ':type' => $this->sType)
538 foreach ($aDBResults as $iPlaceId) {
539 $aResults[$iPlaceId] = new Result($iPlaceId);
545 private function queryPostcode(&$oDB, $iLimit)
547 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
549 if (!empty($this->aAddress)) {
550 $sSQL .= ', search_name s ';
551 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
552 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
553 $sSQL .= ' @> '.$oDB->getArraySQL($this->aAddress).' AND ';
558 $sSQL .= "p.postcode = '".reset($this->aName)."'";
559 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
560 if ($this->oContext->bViewboxBounded) {
561 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
563 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
564 $sSQL .= " LIMIT $iLimit";
566 Debug::printSQL($sSQL);
569 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
570 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
576 private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
581 // Sort by existence of the requested house number but only if not
582 // too many results are expected for the street, i.e. if the result
583 // will be narrowed down by an address. Remeber that with ordering
584 // every single result has to be checked.
585 if ($this->sHouseNumber && ($this->bRareName || !empty($this->aAddress) || $this->sPostcode)) {
586 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
588 $aOrder[0] .= 'EXISTS(';
589 $aOrder[0] .= ' SELECT place_id';
590 $aOrder[0] .= ' FROM placex';
591 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
592 $aOrder[0] .= " AND housenumber ~* E'".$sHouseNumberRegex."'";
593 $aOrder[0] .= ' LIMIT 1';
595 // also housenumbers from interpolation lines table are needed
596 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
597 $iHouseNumber = intval($this->sHouseNumber);
598 $aOrder[0] .= 'OR EXISTS(';
599 $aOrder[0] .= ' SELECT place_id ';
600 $aOrder[0] .= ' FROM location_property_osmline ';
601 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
602 $aOrder[0] .= ' AND startnumber is not NULL';
603 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
604 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
605 $aOrder[0] .= ' LIMIT 1';
608 $aOrder[0] .= ') DESC';
611 if (!empty($this->aName)) {
612 $aTerms[] = 'name_vector @> '.$oDB->getArraySQL($this->aName);
614 if (!empty($this->aAddress)) {
615 // For infrequent name terms disable index usage for address
616 if ($this->bRareName) {
617 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.$oDB->getArraySQL($this->aAddress);
619 $aTerms[] = 'nameaddress_vector @> '.$oDB->getArraySQL($this->aAddress);
623 $sCountryTerm = $this->countryCodeSQL('country_code');
625 $aTerms[] = $sCountryTerm;
628 if ($this->sHouseNumber) {
629 $aTerms[] = 'address_rank between 16 and 30';
630 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
631 if ($iMinAddressRank > 0) {
632 $aTerms[] = "((address_rank between $iMinAddressRank and $iMaxAddressRank) or (search_rank between $iMinAddressRank and $iMaxAddressRank))";
636 if ($this->oContext->hasNearPoint()) {
637 $aTerms[] = $this->oContext->withinSQL('centroid');
638 $aOrder[] = $this->oContext->distanceSQL('centroid');
639 } elseif ($this->sPostcode) {
640 if (empty($this->aAddress)) {
641 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.12))";
643 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
647 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
649 $aTerms[] = $sExcludeSQL;
652 if ($this->oContext->bViewboxBounded) {
653 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
656 if ($this->oContext->hasNearPoint()) {
657 $aOrder[] = $this->oContext->distanceSQL('centroid');
660 if ($this->sHouseNumber) {
661 $sImportanceSQL = '- abs(26 - address_rank) + 3';
663 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
665 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
666 $aOrder[] = "$sImportanceSQL DESC";
668 $aFullNameAddress = $this->oContext->getFullNameTerms();
669 if (!empty($aFullNameAddress)) {
670 $sExactMatchSQL = ' ( ';
671 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
672 $sExactMatchSQL .= ' SELECT unnest('.$oDB->getArraySQL($aFullNameAddress).')';
673 $sExactMatchSQL .= ' INTERSECT ';
674 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
675 $sExactMatchSQL .= ' ) s';
676 $sExactMatchSQL .= ') as exactmatch';
677 $aOrder[] = 'exactmatch DESC';
679 $sExactMatchSQL = '0::int as exactmatch';
682 if ($this->sHouseNumber || $this->sClass) {
688 if (!empty($aTerms)) {
689 $sSQL = 'SELECT place_id, address_rank,'.$sExactMatchSQL;
690 $sSQL .= ' FROM search_name';
691 $sSQL .= ' WHERE '.join(' and ', $aTerms);
692 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
693 $sSQL .= ' LIMIT '.$iLimit;
695 Debug::printSQL($sSQL);
697 $aDBResults = $oDB->getAll($sSQL, null, 'Could not get places for search terms.');
699 foreach ($aDBResults as $aResult) {
700 $oResult = new Result($aResult['place_id']);
701 $oResult->iExactMatches = $aResult['exactmatch'];
702 $oResult->iAddressRank = $aResult['address_rank'];
703 $aResults[$aResult['place_id']] = $oResult;
710 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
713 $sRoadPlaceIDs = Result::joinIdsByTableMaxRank(
715 Result::TABLE_PLACEX,
718 $sPOIPlaceIDs = Result::joinIdsByTableMinRank(
720 Result::TABLE_PLACEX,
724 $aIDCondition = array();
725 if ($sRoadPlaceIDs) {
726 $aIDCondition[] = 'parent_place_id in ('.$sRoadPlaceIDs.')';
729 $aIDCondition[] = 'place_id in ('.$sPOIPlaceIDs.')';
732 if (empty($aIDCondition)) {
736 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
737 $sSQL = 'SELECT place_id FROM placex WHERE';
738 $sSQL .= " housenumber ~* E'".$sHouseNumberRegex."'";
739 $sSQL .= ' AND ('.join(' OR ', $aIDCondition).')';
740 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
742 Debug::printSQL($sSQL);
744 // XXX should inherit the exactMatches from its parent
745 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
746 $aResults[$iPlaceId] = new Result($iPlaceId);
749 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
750 $iHousenumber = intval($this->sHouseNumber);
751 if ($bIsIntHouseNumber && $sRoadPlaceIDs && empty($aResults)) {
752 // if nothing found, search in the interpolation line table
753 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
754 $sSQL .= ' WHERE startnumber is not NULL';
755 $sSQL .= ' AND parent_place_id in ('.$sRoadPlaceIDs.') AND (';
756 if ($iHousenumber % 2 == 0) {
757 // If housenumber is even, look for housenumber in streets
758 // with interpolationtype even or all.
759 $sSQL .= "interpolationtype='even'";
761 // Else look for housenumber with interpolationtype odd or all.
762 $sSQL .= "interpolationtype='odd'";
764 $sSQL .= " or interpolationtype='all') and ";
765 $sSQL .= $iHousenumber.'>=startnumber and ';
766 $sSQL .= $iHousenumber.'<=endnumber';
767 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
769 Debug::printSQL($sSQL);
771 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
772 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
773 $oResult->iHouseNumber = $iHousenumber;
774 $aResults[$iPlaceId] = $oResult;
778 // If nothing found then search in Tiger data (location_property_tiger)
779 if (CONST_Use_US_Tiger_Data && $sRoadPlaceIDs && $bIsIntHouseNumber && empty($aResults)) {
780 $sSQL = 'SELECT place_id FROM location_property_tiger';
781 $sSQL .= ' WHERE parent_place_id in ('.$sRoadPlaceIDs.') and (';
782 if ($iHousenumber % 2 == 0) {
783 $sSQL .= "interpolationtype='even'";
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_TIGER);
796 $oResult->iHouseNumber = $iHousenumber;
797 $aResults[$iPlaceId] = $oResult;
805 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
808 $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
814 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
815 // If they were searching for a named class (i.e. 'Kings Head pub')
816 // then we might have an extra match
817 $sSQL = 'SELECT place_id FROM placex ';
818 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
819 $sSQL .= " AND class='".$this->sClass."' ";
820 $sSQL .= " AND type='".$this->sType."'";
821 $sSQL .= ' AND linked_place_id is null';
822 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
823 $sSQL .= ' ORDER BY rank_search ASC ';
824 $sSQL .= " LIMIT $iLimit";
826 Debug::printSQL($sSQL);
828 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
829 $aResults[$iPlaceId] = new Result($iPlaceId);
833 // NEAR and IN are handled the same
834 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
835 $sClassTable = $this->poiTable();
836 $bCacheTable = $oDB->tableExists($sClassTable);
838 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
839 Debug::printSQL($sSQL);
840 $iMaxRank = (int) $oDB->getOne($sSQL);
842 // For state / country level searches the normal radius search doesn't work very well
844 if ($iMaxRank < 9 && $bCacheTable) {
845 // Try and get a polygon to search in instead
846 $sSQL = 'SELECT geometry FROM placex';
847 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
848 $sSQL .= " AND rank_search < $iMaxRank + 5";
849 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
850 $sSQL .= ' ORDER BY rank_search ASC ';
852 Debug::printSQL($sSQL);
853 $sPlaceGeom = $oDB->getOne($sSQL);
860 $sSQL = 'SELECT place_id FROM placex';
861 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
862 Debug::printSQL($sSQL);
863 $aPlaceIDs = $oDB->getCol($sSQL);
864 $sPlaceIDs = join(',', $aPlaceIDs);
867 if ($sPlaceIDs || $sPlaceGeom) {
870 // More efficient - can make the range bigger
874 if ($this->oContext->hasNearPoint()) {
875 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
876 } elseif ($sPlaceIDs) {
877 $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
878 } elseif ($sPlaceGeom) {
879 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
882 $sSQL = 'SELECT distinct i.place_id';
884 $sSQL .= ', i.order_term';
886 $sSQL .= ' from (SELECT l.place_id';
888 $sSQL .= ','.$sOrderBySQL.' as order_term';
890 $sSQL .= ' from '.$sClassTable.' as l';
893 $sSQL .= ',placex as f WHERE ';
894 $sSQL .= "f.place_id in ($sPlaceIDs) ";
895 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
896 } elseif ($sPlaceGeom) {
897 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
900 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
901 $sSQL .= 'limit 300) i ';
903 $sSQL .= 'order by order_term asc';
905 $sSQL .= " limit $iLimit";
907 Debug::printSQL($sSQL);
909 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
910 $aResults[$iPlaceId] = new Result($iPlaceId);
913 if ($this->oContext->hasNearPoint()) {
914 $fRange = $this->oContext->nearRadius();
918 if ($this->oContext->hasNearPoint()) {
919 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
921 $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
924 $sSQL = 'SELECT distinct l.place_id';
926 $sSQL .= ','.$sOrderBySQL.' as orderterm';
928 $sSQL .= ' FROM placex as l, placex as f';
929 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
930 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
931 $sSQL .= " AND l.class='".$this->sClass."'";
932 $sSQL .= " AND l.type='".$this->sType."'";
933 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
935 $sSQL .= 'ORDER BY orderterm ASC';
937 $sSQL .= " limit $iLimit";
939 Debug::printSQL($sSQL);
941 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
942 $aResults[$iPlaceId] = new Result($iPlaceId);
951 private function poiTable()
953 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
956 private function countryCodeSQL($sVar)
958 if ($this->sCountryCode) {
959 return $sVar.' = \''.$this->sCountryCode."'";
961 if ($this->oContext->sqlCountryList) {
962 return $sVar.' in '.$this->oContext->sqlCountryList;
968 /////////// Sort functions
971 public static function bySearchRank($a, $b)
973 if ($a->iSearchRank == $b->iSearchRank) {
974 return $a->iOperator + strlen($a->sHouseNumber)
975 - $b->iOperator - strlen($b->sHouseNumber);
978 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
981 //////////// Debugging functions
984 public function debugInfo()
987 'Search rank' => $this->iSearchRank,
988 'Country code' => $this->sCountryCode,
989 'Name terms' => $this->aName,
990 'Name terms (stop words)' => $this->aNameNonSearch,
991 'Address terms' => $this->aAddress,
992 'Address terms (stop words)' => $this->aAddressNonSearch,
993 'Address terms (full words)' => $this->aFullNameAddress ?? '',
994 'Special search' => $this->iOperator,
995 'Class' => $this->sClass,
996 'Type' => $this->sType,
997 'House number' => $this->sHouseNumber,
998 'Postcode' => $this->sPostcode
1002 public function dumpAsHtmlTableRow(&$aWordIDs)
1004 $kf = function ($k) use (&$aWordIDs) {
1005 return $aWordIDs[$k] ?? '['.$k.']';
1009 echo "<td>$this->iSearchRank</td>";
1010 echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
1011 echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
1012 echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
1013 echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1014 echo '<td>'.$this->sCountryCode.'</td>';
1015 echo '<td>'.Operator::toString($this->iOperator).'</td>';
1016 echo '<td>'.$this->sClass.'</td>';
1017 echo '<td>'.$this->sType.'</td>';
1018 echo '<td>'.$this->sPostcode.'</td>';
1019 echo '<td>'.$this->sHouseNumber.'</td>';