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.
228 public function addNameToken($iId)
230 $this->aName[$iId] = $iId;
234 * Add the given partial token to the list of terms to search for in
237 * @param integer iID ID of term to add.
238 * @param bool bSearchable Term should be used to search for result
239 * (i.e. term is not a stop word).
240 * @param integer iPhraseNumber Index of phrase, where the partial term
243 public function addPartialNameToken($iId, $bSearchable, $iPhraseNumber)
246 $this->aName[$iId] = $iId;
248 $this->aNameNonSearch[$iId] = $iId;
250 $this->iNamePhrase = $iPhraseNumber;
253 public function markRareName()
255 $this->bRareName = true;
259 * Set country restriction for the search.
261 * @param string sCountryCode Country code of country to restrict search to.
263 public function setCountry($sCountryCode)
265 $this->sCountryCode = $sCountryCode;
266 $this->iNamePhrase = -1;
270 * Set postcode search constraint.
272 * @param string sPostcode Postcode the result should have.
274 public function setPostcode($sPostcode)
276 $this->sPostcode = $sPostcode;
277 $this->iNamePhrase = -1;
281 * Make this search a search for a postcode object.
283 * @param integer iId Token Id for the postcode.
284 * @param string sPostcode Postcode to look for.
286 public function setPostcodeAsName($iId, $sPostcode)
288 $this->iOperator = Operator::POSTCODE;
289 $this->aAddress = array_merge($this->aAddress, $this->aName);
290 $this->aName = array($iId => $sPostcode);
291 $this->bRareName = true;
292 $this->iNamePhrase = -1;
296 * Set house number search cnstraint.
298 * @param string sNumber House number the result should have.
300 public function setHousenumber($sNumber)
302 $this->sHouseNumber = $sNumber;
303 $this->iNamePhrase = -1;
307 * Make this search a search for a house number.
309 * @param integer iId Token Id for the house number.
311 public function setHousenumberAsName($iId)
313 $this->aAddress = array_merge($this->aAddress, $this->aName);
314 $this->bRareName = false;
315 $this->aName = array($iId => $iId);
316 $this->iNamePhrase = -1;
320 * Make this search a POI search.
322 * In a POI search, objects are not (only) searched by their name
323 * but also by the primary OSM key/value pair (class and type in Nominatim).
325 * @param integer $iOperator Type of POI search
326 * @param string $sClass Class (or OSM tag key) of POI.
327 * @param string $sType Type (or OSM tag value) of POI.
331 public function setPoiSearch($iOperator, $sClass, $sType)
333 $this->iOperator = $iOperator;
334 $this->sClass = $sClass;
335 $this->sType = $sType;
336 $this->iNamePhrase = -1;
339 public function getNamePhrase()
341 return $this->iNamePhrase;
345 * Get the global search context.
347 * @return object Objects of global search constraints.
349 public function getContext()
351 return $this->oContext;
354 /////////// Query functions
358 * Query database for places that match this search.
360 * @param object $oDB Nominatim::DB instance to use.
361 * @param integer $iMinRank Minimum address rank to restrict search to.
362 * @param integer $iMaxRank Maximum address rank to restrict search to.
363 * @param integer $iLimit Maximum number of results.
365 * @return mixed[] An array with two fields: IDs contains the list of
366 * matching place IDs and houseNumber the houseNumber
367 * if appicable or -1 if not.
369 public function query(&$oDB, $iMinRank, $iMaxRank, $iLimit)
373 if ($this->sCountryCode
374 && empty($this->aName)
377 && !$this->oContext->hasNearPoint()
379 // Just looking for a country - look it up
380 if (4 >= $iMinRank && 4 <= $iMaxRank) {
381 $aResults = $this->queryCountry($oDB);
383 } elseif (empty($this->aName) && empty($this->aAddress)) {
384 // Neither name nor address? Then we must be
385 // looking for a POI in a geographic area.
386 if ($this->oContext->isBoundedSearch()) {
387 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
389 } elseif ($this->iOperator == Operator::POSTCODE) {
390 // looking for postcode
391 $aResults = $this->queryPostcode($oDB, $iLimit);
394 // First search for places according to name and address.
395 $aResults = $this->queryNamedPlace(
402 // Now search for housenumber, if housenumber provided. Can be zero.
403 if (($this->sHouseNumber || $this->sHouseNumber === '0') && !empty($aResults)) {
404 $aHnResults = $this->queryHouseNumber($oDB, $aResults);
406 // Downgrade the rank of the street results, they are missing
407 // the housenumber. Also drop POI places (rank 30) here, they
408 // cannot be a parent place and therefore must not be shown
409 // as a result for a search with a missing housenumber.
410 foreach ($aResults as $oRes) {
411 if ($oRes->iAddressRank < 28) {
412 if ($oRes->iAddressRank >= 26) {
413 $oRes->iResultRank++;
415 $oRes->iResultRank += 2;
417 $aHnResults[$oRes->iId] = $oRes;
421 $aResults = $aHnResults;
424 // finally get POIs if requested
425 if ($this->sClass && !empty($aResults)) {
426 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
430 Debug::printDebugTable('Place IDs', $aResults);
432 if (!empty($aResults) && $this->sPostcode) {
433 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
435 $sSQL = 'SELECT place_id FROM placex';
436 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
437 $sSQL .= " AND postcode != '".$this->sPostcode."'";
438 Debug::printSQL($sSQL);
439 $aFilteredPlaceIDs = $oDB->getCol($sSQL);
440 if ($aFilteredPlaceIDs) {
441 foreach ($aFilteredPlaceIDs as $iPlaceId) {
442 $aResults[$iPlaceId]->iResultRank++;
452 private function queryCountry(&$oDB)
454 $sSQL = 'SELECT place_id FROM placex ';
455 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
456 $sSQL .= ' AND rank_search = 4';
457 if ($this->oContext->bViewboxBounded) {
458 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
460 $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
462 Debug::printSQL($sSQL);
464 $iPlaceId = $oDB->getOne($sSQL);
468 $aResults[$iPlaceId] = new Result($iPlaceId);
474 private function queryNearbyPoi(&$oDB, $iLimit)
476 if (!$this->sClass) {
480 $aDBResults = array();
481 $sPoiTable = $this->poiTable();
483 if ($oDB->tableExists($sPoiTable)) {
484 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
485 if ($this->oContext->sqlCountryList) {
486 $sSQL .= ' JOIN placex USING (place_id)';
488 if ($this->oContext->hasNearPoint()) {
489 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
490 } elseif ($this->oContext->bViewboxBounded) {
491 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
493 if ($this->oContext->sqlCountryList) {
494 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
496 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
497 if ($this->oContext->sqlViewboxCentre) {
498 $sSQL .= ' ORDER BY ST_Distance(';
499 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
500 } elseif ($this->oContext->hasNearPoint()) {
501 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
503 $sSQL .= " LIMIT $iLimit";
504 Debug::printSQL($sSQL);
505 $aDBResults = $oDB->getCol($sSQL);
508 if ($this->oContext->hasNearPoint()) {
509 $sSQL = 'SELECT place_id FROM placex WHERE ';
510 $sSQL .= 'class = :class and type = :type';
511 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
512 $sSQL .= ' AND linked_place_id is null';
513 if ($this->oContext->sqlCountryList) {
514 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
516 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
517 $sSQL .= " LIMIT $iLimit";
518 Debug::printSQL($sSQL);
519 $aDBResults = $oDB->getCol(
521 array(':class' => $this->sClass, ':type' => $this->sType)
526 foreach ($aDBResults as $iPlaceId) {
527 $aResults[$iPlaceId] = new Result($iPlaceId);
533 private function queryPostcode(&$oDB, $iLimit)
535 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
537 if (!empty($this->aAddress)) {
538 $sSQL .= ', search_name s ';
539 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
540 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
541 $sSQL .= ' @> '.$oDB->getArraySQL($this->aAddress).' AND ';
546 $sSQL .= "p.postcode = '".reset($this->aName)."'";
547 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
548 if ($this->oContext->bViewboxBounded) {
549 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
551 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
552 $sSQL .= " LIMIT $iLimit";
554 Debug::printSQL($sSQL);
557 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
558 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
564 private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
569 // Sort by existence of the requested house number but only if not
570 // too many results are expected for the street, i.e. if the result
571 // will be narrowed down by an address. Remeber that with ordering
572 // every single result has to be checked.
573 if ($this->sHouseNumber && ($this->bRareName || !empty($this->aAddress) || $this->sPostcode)) {
574 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
576 $aOrder[0] .= 'EXISTS(';
577 $aOrder[0] .= ' SELECT place_id';
578 $aOrder[0] .= ' FROM placex';
579 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
580 $aOrder[0] .= " AND housenumber ~* E'".$sHouseNumberRegex."'";
581 $aOrder[0] .= ' LIMIT 1';
583 // also housenumbers from interpolation lines table are needed
584 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
585 $iHouseNumber = intval($this->sHouseNumber);
586 $aOrder[0] .= 'OR EXISTS(';
587 $aOrder[0] .= ' SELECT place_id ';
588 $aOrder[0] .= ' FROM location_property_osmline ';
589 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
590 $aOrder[0] .= ' AND startnumber is not NULL';
591 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
592 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
593 $aOrder[0] .= ' LIMIT 1';
596 $aOrder[0] .= ') DESC';
599 if (!empty($this->aName)) {
600 $aTerms[] = 'name_vector @> '.$oDB->getArraySQL($this->aName);
602 if (!empty($this->aAddress)) {
603 // For infrequent name terms disable index usage for address
604 if ($this->bRareName) {
605 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.$oDB->getArraySQL($this->aAddress);
607 $aTerms[] = 'nameaddress_vector @> '.$oDB->getArraySQL($this->aAddress);
611 $sCountryTerm = $this->countryCodeSQL('country_code');
613 $aTerms[] = $sCountryTerm;
616 if ($this->sHouseNumber) {
617 $aTerms[] = 'address_rank between 16 and 30';
618 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
619 if ($iMinAddressRank > 0) {
620 $aTerms[] = "((address_rank between $iMinAddressRank and $iMaxAddressRank) or (search_rank between $iMinAddressRank and $iMaxAddressRank))";
624 if ($this->oContext->hasNearPoint()) {
625 $aTerms[] = $this->oContext->withinSQL('centroid');
626 $aOrder[] = $this->oContext->distanceSQL('centroid');
627 } elseif ($this->sPostcode) {
628 if (empty($this->aAddress)) {
629 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
631 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
635 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
637 $aTerms[] = $sExcludeSQL;
640 if ($this->oContext->bViewboxBounded) {
641 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
644 if ($this->oContext->hasNearPoint()) {
645 $aOrder[] = $this->oContext->distanceSQL('centroid');
648 if ($this->sHouseNumber) {
649 $sImportanceSQL = '- abs(26 - address_rank) + 3';
651 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
653 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
654 $aOrder[] = "$sImportanceSQL DESC";
656 $aFullNameAddress = $this->oContext->getFullNameTerms();
657 if (!empty($aFullNameAddress)) {
658 $sExactMatchSQL = ' ( ';
659 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
660 $sExactMatchSQL .= ' SELECT unnest('.$oDB->getArraySQL($aFullNameAddress).')';
661 $sExactMatchSQL .= ' INTERSECT ';
662 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
663 $sExactMatchSQL .= ' ) s';
664 $sExactMatchSQL .= ') as exactmatch';
665 $aOrder[] = 'exactmatch DESC';
667 $sExactMatchSQL = '0::int as exactmatch';
670 if ($this->sHouseNumber || $this->sClass) {
676 if (!empty($aTerms)) {
677 $sSQL = 'SELECT place_id, address_rank,'.$sExactMatchSQL;
678 $sSQL .= ' FROM search_name';
679 $sSQL .= ' WHERE '.join(' and ', $aTerms);
680 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
681 $sSQL .= ' LIMIT '.$iLimit;
683 Debug::printSQL($sSQL);
685 $aDBResults = $oDB->getAll($sSQL, null, 'Could not get places for search terms.');
687 foreach ($aDBResults as $aResult) {
688 $oResult = new Result($aResult['place_id']);
689 $oResult->iExactMatches = $aResult['exactmatch'];
690 $oResult->iAddressRank = $aResult['address_rank'];
691 $aResults[$aResult['place_id']] = $oResult;
698 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
701 $sRoadPlaceIDs = Result::joinIdsByTableMaxRank(
703 Result::TABLE_PLACEX,
706 $sPOIPlaceIDs = Result::joinIdsByTableMinRank(
708 Result::TABLE_PLACEX,
712 $aIDCondition = array();
713 if ($sRoadPlaceIDs) {
714 $aIDCondition[] = 'parent_place_id in ('.$sRoadPlaceIDs.')';
717 $aIDCondition[] = 'place_id in ('.$sPOIPlaceIDs.')';
720 if (empty($aIDCondition)) {
724 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
725 $sSQL = 'SELECT place_id FROM placex WHERE';
726 $sSQL .= " housenumber ~* E'".$sHouseNumberRegex."'";
727 $sSQL .= ' AND ('.join(' OR ', $aIDCondition).')';
728 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
730 Debug::printSQL($sSQL);
732 // XXX should inherit the exactMatches from its parent
733 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
734 $aResults[$iPlaceId] = new Result($iPlaceId);
737 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
738 $iHousenumber = intval($this->sHouseNumber);
739 if ($bIsIntHouseNumber && $sRoadPlaceIDs && empty($aResults)) {
740 // if nothing found, search in the interpolation line table
741 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
742 $sSQL .= ' WHERE startnumber is not NULL';
743 $sSQL .= ' AND parent_place_id in ('.$sRoadPlaceIDs.') AND (';
744 if ($iHousenumber % 2 == 0) {
745 // If housenumber is even, look for housenumber in streets
746 // with interpolationtype even or all.
747 $sSQL .= "interpolationtype='even'";
749 // Else look for housenumber with interpolationtype odd or all.
750 $sSQL .= "interpolationtype='odd'";
752 $sSQL .= " or interpolationtype='all') and ";
753 $sSQL .= $iHousenumber.'>=startnumber and ';
754 $sSQL .= $iHousenumber.'<=endnumber';
755 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
757 Debug::printSQL($sSQL);
759 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
760 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
761 $oResult->iHouseNumber = $iHousenumber;
762 $aResults[$iPlaceId] = $oResult;
766 // If nothing found then search in Tiger data (location_property_tiger)
767 if (CONST_Use_US_Tiger_Data && $sRoadPlaceIDs && $bIsIntHouseNumber && empty($aResults)) {
768 $sSQL = 'SELECT place_id FROM location_property_tiger';
769 $sSQL .= ' WHERE parent_place_id in ('.$sRoadPlaceIDs.') and (';
770 if ($iHousenumber % 2 == 0) {
771 $sSQL .= "interpolationtype='even'";
773 $sSQL .= "interpolationtype='odd'";
775 $sSQL .= " or interpolationtype='all') and ";
776 $sSQL .= $iHousenumber.'>=startnumber and ';
777 $sSQL .= $iHousenumber.'<=endnumber';
778 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
780 Debug::printSQL($sSQL);
782 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
783 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
784 $oResult->iHouseNumber = $iHousenumber;
785 $aResults[$iPlaceId] = $oResult;
793 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
796 $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
802 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
803 // If they were searching for a named class (i.e. 'Kings Head pub')
804 // then we might have an extra match
805 $sSQL = 'SELECT place_id FROM placex ';
806 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
807 $sSQL .= " AND class='".$this->sClass."' ";
808 $sSQL .= " AND type='".$this->sType."'";
809 $sSQL .= ' AND linked_place_id is null';
810 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
811 $sSQL .= ' ORDER BY rank_search ASC ';
812 $sSQL .= " LIMIT $iLimit";
814 Debug::printSQL($sSQL);
816 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
817 $aResults[$iPlaceId] = new Result($iPlaceId);
821 // NEAR and IN are handled the same
822 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
823 $sClassTable = $this->poiTable();
824 $bCacheTable = $oDB->tableExists($sClassTable);
826 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
827 Debug::printSQL($sSQL);
828 $iMaxRank = (int) $oDB->getOne($sSQL);
830 // For state / country level searches the normal radius search doesn't work very well
832 if ($iMaxRank < 9 && $bCacheTable) {
833 // Try and get a polygon to search in instead
834 $sSQL = 'SELECT geometry FROM placex';
835 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
836 $sSQL .= " AND rank_search < $iMaxRank + 5";
837 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
838 $sSQL .= ' ORDER BY rank_search ASC ';
840 Debug::printSQL($sSQL);
841 $sPlaceGeom = $oDB->getOne($sSQL);
848 $sSQL = 'SELECT place_id FROM placex';
849 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
850 Debug::printSQL($sSQL);
851 $aPlaceIDs = $oDB->getCol($sSQL);
852 $sPlaceIDs = join(',', $aPlaceIDs);
855 if ($sPlaceIDs || $sPlaceGeom) {
858 // More efficient - can make the range bigger
862 if ($this->oContext->hasNearPoint()) {
863 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
864 } elseif ($sPlaceIDs) {
865 $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
866 } elseif ($sPlaceGeom) {
867 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
870 $sSQL = 'SELECT distinct i.place_id';
872 $sSQL .= ', i.order_term';
874 $sSQL .= ' from (SELECT l.place_id';
876 $sSQL .= ','.$sOrderBySQL.' as order_term';
878 $sSQL .= ' from '.$sClassTable.' as l';
881 $sSQL .= ',placex as f WHERE ';
882 $sSQL .= "f.place_id in ($sPlaceIDs) ";
883 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
884 } elseif ($sPlaceGeom) {
885 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
888 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
889 $sSQL .= 'limit 300) i ';
891 $sSQL .= 'order by order_term asc';
893 $sSQL .= " limit $iLimit";
895 Debug::printSQL($sSQL);
897 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
898 $aResults[$iPlaceId] = new Result($iPlaceId);
901 if ($this->oContext->hasNearPoint()) {
902 $fRange = $this->oContext->nearRadius();
906 if ($this->oContext->hasNearPoint()) {
907 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
909 $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
912 $sSQL = 'SELECT distinct l.place_id';
914 $sSQL .= ','.$sOrderBySQL.' as orderterm';
916 $sSQL .= ' FROM placex as l, placex as f';
917 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
918 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
919 $sSQL .= " AND l.class='".$this->sClass."'";
920 $sSQL .= " AND l.type='".$this->sType."'";
921 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
923 $sSQL .= 'ORDER BY orderterm ASC';
925 $sSQL .= " limit $iLimit";
927 Debug::printSQL($sSQL);
929 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
930 $aResults[$iPlaceId] = new Result($iPlaceId);
939 private function poiTable()
941 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
944 private function countryCodeSQL($sVar)
946 if ($this->sCountryCode) {
947 return $sVar.' = \''.$this->sCountryCode."'";
949 if ($this->oContext->sqlCountryList) {
950 return $sVar.' in '.$this->oContext->sqlCountryList;
956 /////////// Sort functions
959 public static function bySearchRank($a, $b)
961 if ($a->iSearchRank == $b->iSearchRank) {
962 return $a->iOperator + strlen($a->sHouseNumber)
963 - $b->iOperator - strlen($b->sHouseNumber);
966 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
969 //////////// Debugging functions
972 public function debugInfo()
975 'Search rank' => $this->iSearchRank,
976 'Country code' => $this->sCountryCode,
977 'Name terms' => $this->aName,
978 'Name terms (stop words)' => $this->aNameNonSearch,
979 'Address terms' => $this->aAddress,
980 'Address terms (stop words)' => $this->aAddressNonSearch,
981 'Address terms (full words)' => $this->aFullNameAddress ?? '',
982 'Special search' => $this->iOperator,
983 'Class' => $this->sClass,
984 'Type' => $this->sType,
985 'House number' => $this->sHouseNumber,
986 'Postcode' => $this->sPostcode
990 public function dumpAsHtmlTableRow(&$aWordIDs)
992 $kf = function ($k) use (&$aWordIDs) {
993 return $aWordIDs[$k] ?? '['.$k.']';
997 echo "<td>$this->iSearchRank</td>";
998 echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
999 echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
1000 echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
1001 echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1002 echo '<td>'.$this->sCountryCode.'</td>';
1003 echo '<td>'.Operator::toString($this->iOperator).'</td>';
1004 echo '<td>'.$this->sClass.'</td>';
1005 echo '<td>'.$this->sType.'</td>';
1006 echo '<td>'.$this->sPostcode.'</td>';
1007 echo '<td>'.$this->sHouseNumber.'</td>';