3 * SPDX-License-Identifier: GPL-2.0-only
5 * This file is part of Nominatim. (https://nominatim.org)
7 * Copyright (C) 2022 by the Nominatim developer community.
8 * For a full list of authors see the git log.
13 require_once(CONST_LibDir.'/SpecialSearchOperator.php');
14 require_once(CONST_LibDir.'/SearchContext.php');
15 require_once(CONST_LibDir.'/Result.php');
18 * Description of a single interpretation of a search query.
20 class SearchDescription
22 /// Ranking how well the description fits the query.
23 private $iSearchRank = 0;
24 /// Country code of country the result must belong to.
25 private $sCountryCode = '';
26 /// List of word ids making up the name of the object.
27 private $aName = array();
28 /// True if the name is rare enough to force index use on name.
29 private $bRareName = false;
30 /// True if the name requires to be accompanied by address terms.
31 private $bNameNeedsAddress = false;
32 /// List of word ids making up the address of the object.
33 private $aAddress = array();
34 /// List of word ids that appear in the name but should be ignored.
35 private $aNameNonSearch = array();
36 /// List of word ids that appear in the address but should be ignored.
37 private $aAddressNonSearch = array();
38 /// Kind of search for special searches, see Nominatim::Operator.
39 private $iOperator = Operator::NONE;
40 /// Class of special feature to search for.
42 /// Type of special feature to search for.
44 /// Housenumber of the object.
45 private $sHouseNumber = '';
46 /// Postcode for the object.
47 private $sPostcode = '';
48 /// Global search constraints.
51 // Temporary values used while creating the search description.
53 /// Index of phrase currently processed.
54 private $iNamePhrase = -1;
57 * Create an empty search description.
59 * @param object $oContext Global context to use. Will be inherited by
60 * all derived search objects.
62 public function __construct($oContext)
64 $this->oContext = $oContext;
68 * Get current search rank.
70 * The higher the search rank the lower the likelihood that the
71 * search is a correct interpretation of the search query.
73 * @return integer Search rank.
75 public function getRank()
77 return $this->iSearchRank;
81 * Extract key/value pairs from a query.
83 * Key/value pairs are recognised if they are of the form [<key>=<value>].
84 * If multiple terms of this kind are found then all terms are removed
85 * but only the first is used for search.
87 * @param string $sQuery Original query string.
89 * @return string The query string with the special search patterns removed.
91 public function extractKeyValuePairs($sQuery)
93 // Search for terms of kind [<key>=<value>].
95 '/\\[([\\w_]*)=([\\w_]*)\\]/',
101 foreach ($aSpecialTermsRaw as $aTerm) {
102 $sQuery = str_replace($aTerm[0], ' ', $sQuery);
103 if (!$this->hasOperator()) {
104 $this->setPoiSearch(Operator::TYPE, $aTerm[1], $aTerm[2]);
112 * Check if the combination of parameters is sensible.
114 * @return bool True, if the search looks valid.
116 public function isValidSearch()
118 if (empty($this->aName)) {
119 if ($this->sHouseNumber) {
122 if (!$this->sClass && !$this->sCountryCode) {
126 if ($this->bNameNeedsAddress && empty($this->aAddress)) {
133 /////////// Search building functions
136 * Create a copy of this search description adding to search rank.
138 * @param integer $iTermCost Cost to add to the current search rank.
140 * @return object Cloned search description.
142 public function clone($iTermCost)
144 $oSearch = clone $this;
145 $oSearch->iSearchRank += $iTermCost;
151 * Check if the search currently includes a name.
153 * @param bool bIncludeNonNames If true stop-word tokens are taken into
156 * @return bool True, if search has a name.
158 public function hasName($bIncludeNonNames = false)
160 return !empty($this->aName)
161 || (!empty($this->aNameNonSearch) && $bIncludeNonNames);
165 * Check if the search currently includes an address term.
167 * @return bool True, if any address term is included, including stop-word
170 public function hasAddress()
172 return !empty($this->aAddress) || !empty($this->aAddressNonSearch);
176 * Check if a country restriction is currently included in the search.
178 * @return bool True, if a country restriction is set.
180 public function hasCountry()
182 return $this->sCountryCode !== '';
186 * Check if a postcode is currently included in the search.
188 * @return bool True, if a postcode is set.
190 public function hasPostcode()
192 return $this->sPostcode !== '';
196 * Check if a house number is set for the search.
198 * @return bool True, if a house number is set.
200 public function hasHousenumber()
202 return $this->sHouseNumber !== '';
206 * Check if a special type of place is requested.
208 * param integer iOperator When set, check for the particular
209 * operator used for the special type.
211 * @return bool True, if speial type is requested or, if requested,
212 * a special type with the given operator.
214 public function hasOperator($iOperator = null)
216 return $iOperator === null ? $this->iOperator != Operator::NONE : $this->iOperator == $iOperator;
220 * Add the given token to the list of terms to search for in the address.
222 * @param integer iID ID of term to add.
223 * @param bool bSearchable Term should be used to search for result
224 * (i.e. term is not a stop word).
226 public function addAddressToken($iId, $bSearchable = true)
229 $this->aAddress[$iId] = $iId;
231 $this->aAddressNonSearch[$iId] = $iId;
236 * Add the given full-word token to the list of terms to search for in the
239 * @param interger iId ID of term to add.
240 * @param bool bRareName True if the term is infrequent enough to not
241 * require other constraints for efficient search.
243 public function addNameToken($iId, $bRareName)
245 $this->aName[$iId] = $iId;
246 $this->bRareName = $bRareName;
247 $this->bNameNeedsAddress = false;
251 * Add the given partial token to the list of terms to search for in
254 * @param integer iID ID of term to add.
255 * @param bool bSearchable Term should be used to search for result
256 * (i.e. term is not a stop word).
257 * @param bool bNeedsAddress True if the term is too unspecific to be used
258 * in a stand-alone search without an address
259 * to narrow down the search.
260 * @param integer iPhraseNumber Index of phrase, where the partial term
263 public function addPartialNameToken($iId, $bSearchable, $bNeedsAddress, $iPhraseNumber)
265 if (empty($this->aName)) {
266 $this->bNameNeedsAddress = $bNeedsAddress;
267 } elseif ($bSearchable && count($this->aName) >= 2) {
268 $this->bNameNeedsAddress = false;
270 $this->bNameNeedsAddress &= $bNeedsAddress;
273 $this->aName[$iId] = $iId;
275 $this->aNameNonSearch[$iId] = $iId;
277 $this->iNamePhrase = $iPhraseNumber;
281 * Set country restriction for the search.
283 * @param string sCountryCode Country code of country to restrict search to.
285 public function setCountry($sCountryCode)
287 $this->sCountryCode = $sCountryCode;
288 $this->iNamePhrase = -1;
292 * Set postcode search constraint.
294 * @param string sPostcode Postcode the result should have.
296 public function setPostcode($sPostcode)
298 $this->sPostcode = $sPostcode;
299 $this->iNamePhrase = -1;
303 * Make this search a search for a postcode object.
305 * @param integer iId Token Id for the postcode.
306 * @param string sPostcode Postcode to look for.
308 public function setPostcodeAsName($iId, $sPostcode)
310 $this->iOperator = Operator::POSTCODE;
311 $this->aAddress = array_merge($this->aAddress, $this->aName);
312 $this->aName = array($iId => $sPostcode);
313 $this->bRareName = true;
314 $this->iNamePhrase = -1;
318 * Set house number search cnstraint.
320 * @param string sNumber House number the result should have.
322 public function setHousenumber($sNumber)
324 $this->sHouseNumber = $sNumber;
325 $this->iNamePhrase = -1;
329 * Make this search a search for a house number.
331 * @param integer iId Token Id for the house number.
333 public function setHousenumberAsName($iId)
335 $this->aAddress = array_merge($this->aAddress, $this->aName);
336 $this->bRareName = false;
337 $this->bNameNeedsAddress = true;
338 $this->aName = array($iId => $iId);
339 $this->iNamePhrase = -1;
343 * Make this search a POI search.
345 * In a POI search, objects are not (only) searched by their name
346 * but also by the primary OSM key/value pair (class and type in Nominatim).
348 * @param integer $iOperator Type of POI search
349 * @param string $sClass Class (or OSM tag key) of POI.
350 * @param string $sType Type (or OSM tag value) of POI.
354 public function setPoiSearch($iOperator, $sClass, $sType)
356 $this->iOperator = $iOperator;
357 $this->sClass = $sClass;
358 $this->sType = $sType;
359 $this->iNamePhrase = -1;
362 public function getNamePhrase()
364 return $this->iNamePhrase;
368 * Get the global search context.
370 * @return object Objects of global search constraints.
372 public function getContext()
374 return $this->oContext;
377 /////////// Query functions
381 * Query database for places that match this search.
383 * @param object $oDB Nominatim::DB instance to use.
384 * @param integer $iMinRank Minimum address rank to restrict search to.
385 * @param integer $iMaxRank Maximum address rank to restrict search to.
386 * @param integer $iLimit Maximum number of results.
388 * @return mixed[] An array with two fields: IDs contains the list of
389 * matching place IDs and houseNumber the houseNumber
390 * if appicable or -1 if not.
392 public function query(&$oDB, $iMinRank, $iMaxRank, $iLimit)
396 if ($this->sCountryCode
397 && empty($this->aName)
400 && !$this->oContext->hasNearPoint()
402 // Just looking for a country - look it up
403 if (4 >= $iMinRank && 4 <= $iMaxRank) {
404 $aResults = $this->queryCountry($oDB);
406 } elseif (empty($this->aName) && empty($this->aAddress)) {
407 // Neither name nor address? Then we must be
408 // looking for a POI in a geographic area.
409 if ($this->oContext->isBoundedSearch()) {
410 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
412 } elseif ($this->iOperator == Operator::POSTCODE) {
413 // looking for postcode
414 $aResults = $this->queryPostcode($oDB, $iLimit);
417 // First search for places according to name and address.
418 $aResults = $this->queryNamedPlace(
425 // finally get POIs if requested
426 if ($this->sClass && !empty($aResults)) {
427 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
431 Debug::printDebugTable('Place IDs', $aResults);
433 if (!empty($aResults) && $this->sPostcode) {
434 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
436 $sSQL = 'SELECT place_id FROM placex';
437 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
438 $sSQL .= " AND postcode != '".$this->sPostcode."'";
439 Debug::printSQL($sSQL);
440 $aFilteredPlaceIDs = $oDB->getCol($sSQL);
441 if ($aFilteredPlaceIDs) {
442 foreach ($aFilteredPlaceIDs as $iPlaceId) {
443 $aResults[$iPlaceId]->iResultRank++;
453 private function queryCountry(&$oDB)
455 $sSQL = 'SELECT place_id FROM placex ';
456 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
457 $sSQL .= ' AND rank_search = 4';
458 if ($this->oContext->bViewboxBounded) {
459 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
461 $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
463 Debug::printSQL($sSQL);
465 $iPlaceId = $oDB->getOne($sSQL);
469 $aResults[$iPlaceId] = new Result($iPlaceId);
475 private function queryNearbyPoi(&$oDB, $iLimit)
477 if (!$this->sClass) {
481 $aDBResults = array();
482 $sPoiTable = $this->poiTable();
484 if ($oDB->tableExists($sPoiTable)) {
485 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
486 if ($this->oContext->sqlCountryList) {
487 $sSQL .= ' JOIN placex USING (place_id)';
489 if ($this->oContext->hasNearPoint()) {
490 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
491 } elseif ($this->oContext->bViewboxBounded) {
492 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
494 if ($this->oContext->sqlCountryList) {
495 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
497 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
498 if ($this->oContext->sqlViewboxCentre) {
499 $sSQL .= ' ORDER BY ST_Distance(';
500 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
501 } elseif ($this->oContext->hasNearPoint()) {
502 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
504 $sSQL .= " LIMIT $iLimit";
505 Debug::printSQL($sSQL);
506 $aDBResults = $oDB->getCol($sSQL);
509 if ($this->oContext->hasNearPoint()) {
510 $sSQL = 'SELECT place_id FROM placex WHERE ';
511 $sSQL .= 'class = :class and type = :type';
512 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
513 $sSQL .= ' AND linked_place_id is null';
514 if ($this->oContext->sqlCountryList) {
515 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
517 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
518 $sSQL .= " LIMIT $iLimit";
519 Debug::printSQL($sSQL);
520 $aDBResults = $oDB->getCol(
522 array(':class' => $this->sClass, ':type' => $this->sType)
527 foreach ($aDBResults as $iPlaceId) {
528 $aResults[$iPlaceId] = new Result($iPlaceId);
534 private function queryPostcode(&$oDB, $iLimit)
536 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
538 if (!empty($this->aAddress)) {
539 $sSQL .= ', search_name s ';
540 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
541 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
542 $sSQL .= ' @> '.$oDB->getArraySQL($this->aAddress).' AND ';
547 $sSQL .= "p.postcode = '".reset($this->aName)."'";
548 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
549 if ($this->oContext->bViewboxBounded) {
550 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
552 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
553 $sSQL .= " LIMIT $iLimit";
555 Debug::printSQL($sSQL);
558 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
559 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
565 private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
570 if (!empty($this->aName)) {
571 $aTerms[] = 'name_vector @> '.$oDB->getArraySQL($this->aName);
573 if (!empty($this->aAddress)) {
574 // For infrequent name terms disable index usage for address
575 if ($this->bRareName) {
576 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.$oDB->getArraySQL($this->aAddress);
578 $aTerms[] = 'nameaddress_vector @> '.$oDB->getArraySQL($this->aAddress);
582 $sCountryTerm = $this->countryCodeSQL('country_code');
584 $aTerms[] = $sCountryTerm;
587 if ($this->sHouseNumber) {
588 $aTerms[] = 'address_rank between 16 and 30';
589 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
590 if ($iMinAddressRank > 0) {
591 $aTerms[] = "((address_rank between $iMinAddressRank and $iMaxAddressRank) or (search_rank between $iMinAddressRank and $iMaxAddressRank))";
595 if ($this->oContext->hasNearPoint()) {
596 $aTerms[] = $this->oContext->withinSQL('centroid');
597 $aOrder[] = $this->oContext->distanceSQL('centroid');
598 } elseif ($this->sPostcode) {
599 if (empty($this->aAddress)) {
600 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.12))";
602 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
606 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
608 $aTerms[] = $sExcludeSQL;
611 if ($this->oContext->bViewboxBounded) {
612 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
615 if ($this->sHouseNumber) {
616 $sImportanceSQL = '- abs(26 - address_rank) + 3';
618 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
620 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
621 $aOrder[] = "$sImportanceSQL DESC";
623 $aFullNameAddress = $this->oContext->getFullNameTerms();
624 if (!empty($aFullNameAddress)) {
625 $sExactMatchSQL = ' ( ';
626 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
627 $sExactMatchSQL .= ' SELECT unnest('.$oDB->getArraySQL($aFullNameAddress).')';
628 $sExactMatchSQL .= ' INTERSECT ';
629 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
630 $sExactMatchSQL .= ' ) s';
631 $sExactMatchSQL .= ') as exactmatch';
632 $aOrder[] = 'exactmatch DESC';
634 $sExactMatchSQL = '0::int as exactmatch';
637 if (empty($aTerms)) {
641 if ($this->hasHousenumber()) {
642 $sHouseNumberRegex = $oDB->getDBQuoted('\\\\m'.$this->sHouseNumber.'\\\\M');
644 // Housenumbers on streets and places.
645 $sPlacexSql = 'SELECT array_agg(place_id) FROM placex';
646 $sPlacexSql .= ' WHERE parent_place_id = sin.place_id AND sin.address_rank < 30';
647 $sPlacexSql .= $this->oContext->excludeSQL(' AND place_id');
648 $sPlacexSql .= ' and housenumber ~* E'.$sHouseNumberRegex;
650 // Interpolations on streets and places.
651 $sInterpolSql = 'null';
653 if (preg_match('/^[0-9]+$/', $this->sHouseNumber)) {
654 $sIpolHnr = 'WHERE parent_place_id = sin.place_id ';
655 $sIpolHnr .= ' AND startnumber is not NULL AND sin.address_rank < 30';
656 $sIpolHnr .= ' AND '.$this->sHouseNumber.' between startnumber and endnumber';
657 $sIpolHnr .= ' AND ('.$this->sHouseNumber.' - startnumber) % step = 0';
659 $sInterpolSql = 'SELECT array_agg(place_id) FROM location_property_osmline '.$sIpolHnr;
660 if (CONST_Use_US_Tiger_Data) {
661 $sTigerSql = 'SELECT array_agg(place_id) FROM location_property_tiger '.$sIpolHnr;
662 $sTigerSql .= " and sin.country_code = 'us'";
670 $sSelfHnr = 'SELECT * FROM placex WHERE place_id = search_name.place_id';
671 $sSelfHnr .= ' AND housenumber ~* E'.$sHouseNumberRegex;
673 $aTerms[] = '(address_rank < 30 or exists('.$sSelfHnr.'))';
676 $sSQL = 'SELECT sin.*, ';
677 $sSQL .= '('.$sPlacexSql.') as placex_hnr, ';
678 $sSQL .= '('.$sInterpolSql.') as interpol_hnr, ';
679 $sSQL .= '('.$sTigerSql.') as tiger_hnr ';
681 $sSQL .= ' SELECT place_id, address_rank, country_code,'.$sExactMatchSQL.',';
682 $sSQL .= ' CASE WHEN importance = 0 OR importance IS NULL';
683 $sSQL .= ' THEN 0.75001-(search_rank::float/40) ELSE importance END as importance';
684 $sSQL .= ' FROM search_name';
685 $sSQL .= ' WHERE '.join(' and ', $aTerms);
686 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
687 $sSQL .= ' LIMIT 40000';
689 $sSQL .= ' ORDER BY address_rank = 30 desc, placex_hnr, interpol_hnr, tiger_hnr,';
690 $sSQL .= ' importance';
691 $sSQL .= ' LIMIT '.$iLimit;
697 $sSQL = 'SELECT place_id, address_rank, '.$sExactMatchSQL;
698 $sSQL .= ' FROM search_name';
699 $sSQL .= ' WHERE '.join(' and ', $aTerms);
700 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
701 $sSQL .= ' LIMIT '.$iLimit;
704 Debug::printSQL($sSQL);
706 $aDBResults = $oDB->getAll($sSQL, null, 'Could not get places for search terms.');
710 foreach ($aDBResults as $aResult) {
711 $oResult = new Result($aResult['place_id']);
712 $oResult->iExactMatches = $aResult['exactmatch'];
713 $oResult->iAddressRank = $aResult['address_rank'];
716 if ($this->hasHousenumber() && $aResult['address_rank'] < 30) {
717 if ($aResult['placex_hnr']) {
718 foreach (explode(',', substr($aResult['placex_hnr'], 1, -1)) as $sPlaceID) {
719 $iPlaceID = intval($sPlaceID);
720 $oHnrResult = new Result($iPlaceID);
721 $oHnrResult->iExactMatches = $aResult['exactmatch'];
722 $oHnrResult->iAddressRank = 30;
723 $aResults[$iPlaceID] = $oHnrResult;
724 $bNeedResult = false;
727 if ($aResult['interpol_hnr']) {
728 foreach (explode(',', substr($aResult['interpol_hnr'], 1, -1)) as $sPlaceID) {
729 $iPlaceID = intval($sPlaceID);
730 $oHnrResult = new Result($iPlaceID, Result::TABLE_OSMLINE);
731 $oHnrResult->iExactMatches = $aResult['exactmatch'];
732 $oHnrResult->iAddressRank = 30;
733 $oHnrResult->iHouseNumber = intval($this->sHouseNumber);
734 $aResults[$iPlaceID] = $oHnrResult;
735 $bNeedResult = false;
738 if ($aResult['tiger_hnr']) {
739 foreach (explode(',', substr($aResult['tiger_hnr'], 1, -1)) as $sPlaceID) {
740 $iPlaceID = intval($sPlaceID);
741 $oHnrResult = new Result($iPlaceID, Result::TABLE_TIGER);
742 $oHnrResult->iExactMatches = $aResult['exactmatch'];
743 $oHnrResult->iAddressRank = 30;
744 $oHnrResult->iHouseNumber = intval($this->sHouseNumber);
745 $aResults[$iPlaceID] = $oHnrResult;
746 $bNeedResult = false;
750 if ($aResult['address_rank'] < 26) {
751 $oResult->iResultRank += 2;
753 $oResult->iResultRank++;
758 $aResults[$aResult['place_id']] = $oResult;
766 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
769 $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
775 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
776 // If they were searching for a named class (i.e. 'Kings Head pub')
777 // then we might have an extra match
778 $sSQL = 'SELECT place_id FROM placex ';
779 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
780 $sSQL .= " AND class='".$this->sClass."' ";
781 $sSQL .= " AND type='".$this->sType."'";
782 $sSQL .= ' AND linked_place_id is null';
783 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
784 $sSQL .= ' ORDER BY rank_search ASC ';
785 $sSQL .= " LIMIT $iLimit";
787 Debug::printSQL($sSQL);
789 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
790 $aResults[$iPlaceId] = new Result($iPlaceId);
794 // NEAR and IN are handled the same
795 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
796 $sClassTable = $this->poiTable();
797 $bCacheTable = $oDB->tableExists($sClassTable);
799 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
800 Debug::printSQL($sSQL);
801 $iMaxRank = (int) $oDB->getOne($sSQL);
803 // For state / country level searches the normal radius search doesn't work very well
805 if ($iMaxRank < 9 && $bCacheTable) {
806 // Try and get a polygon to search in instead
807 $sSQL = 'SELECT geometry FROM placex';
808 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
809 $sSQL .= " AND rank_search < $iMaxRank + 5";
810 $sSQL .= ' AND ST_Area(Box2d(geometry)) < 20';
811 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
812 $sSQL .= ' ORDER BY rank_search ASC ';
814 Debug::printSQL($sSQL);
815 $sPlaceGeom = $oDB->getOne($sSQL);
822 $sSQL = 'SELECT place_id FROM placex';
823 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
824 Debug::printSQL($sSQL);
825 $aPlaceIDs = $oDB->getCol($sSQL);
826 $sPlaceIDs = join(',', $aPlaceIDs);
829 if ($sPlaceIDs || $sPlaceGeom) {
832 // More efficient - can make the range bigger
836 if ($this->oContext->hasNearPoint()) {
837 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
838 } elseif ($sPlaceIDs) {
839 $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
840 } elseif ($sPlaceGeom) {
841 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
844 $sSQL = 'SELECT distinct i.place_id';
846 $sSQL .= ', i.order_term';
848 $sSQL .= ' from (SELECT l.place_id';
850 $sSQL .= ','.$sOrderBySQL.' as order_term';
852 $sSQL .= ' from '.$sClassTable.' as l';
855 $sSQL .= ',placex as f WHERE ';
856 $sSQL .= "f.place_id in ($sPlaceIDs) ";
857 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
858 } elseif ($sPlaceGeom) {
859 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
862 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
863 $sSQL .= 'limit 300) i ';
865 $sSQL .= 'order by order_term asc';
867 $sSQL .= " limit $iLimit";
869 Debug::printSQL($sSQL);
871 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
872 $aResults[$iPlaceId] = new Result($iPlaceId);
875 if ($this->oContext->hasNearPoint()) {
876 $fRange = $this->oContext->nearRadius();
880 if ($this->oContext->hasNearPoint()) {
881 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
883 $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
886 $sSQL = 'SELECT distinct l.place_id';
888 $sSQL .= ','.$sOrderBySQL.' as orderterm';
890 $sSQL .= ' FROM placex as l, placex as f';
891 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
892 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
893 $sSQL .= " AND l.class='".$this->sClass."'";
894 $sSQL .= " AND l.type='".$this->sType."'";
895 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
897 $sSQL .= 'ORDER BY orderterm ASC';
899 $sSQL .= " limit $iLimit";
901 Debug::printSQL($sSQL);
903 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
904 $aResults[$iPlaceId] = new Result($iPlaceId);
913 private function poiTable()
915 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
918 private function countryCodeSQL($sVar)
920 if ($this->sCountryCode) {
921 return $sVar.' = \''.$this->sCountryCode."'";
923 if ($this->oContext->sqlCountryList) {
924 return $sVar.' in '.$this->oContext->sqlCountryList;
930 /////////// Sort functions
933 public static function bySearchRank($a, $b)
935 if ($a->iSearchRank == $b->iSearchRank) {
936 return $a->iOperator + strlen($a->sHouseNumber)
937 - $b->iOperator - strlen($b->sHouseNumber);
940 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
943 //////////// Debugging functions
946 public function debugInfo()
949 'Search rank' => $this->iSearchRank,
950 'Country code' => $this->sCountryCode,
951 'Name terms' => $this->aName,
952 'Name terms (stop words)' => $this->aNameNonSearch,
953 'Address terms' => $this->aAddress,
954 'Address terms (stop words)' => $this->aAddressNonSearch,
955 'Address terms (full words)' => $this->aFullNameAddress ?? '',
956 'Special search' => $this->iOperator,
957 'Class' => $this->sClass,
958 'Type' => $this->sType,
959 'House number' => $this->sHouseNumber,
960 'Postcode' => $this->sPostcode
964 public function dumpAsHtmlTableRow(&$aWordIDs)
966 $kf = function ($k) use (&$aWordIDs) {
967 return $aWordIDs[$k] ?? '['.$k.']';
971 echo "<td>$this->iSearchRank</td>";
972 echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
973 echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
974 echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
975 echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
976 echo '<td>'.$this->sCountryCode.'</td>';
977 echo '<td>'.Operator::toString($this->iOperator).'</td>';
978 echo '<td>'.$this->sClass.'</td>';
979 echo '<td>'.$this->sType.'</td>';
980 echo '<td>'.$this->sPostcode.'</td>';
981 echo '<td>'.$this->sHouseNumber.'</td>';