]> git.openstreetmap.org Git - nominatim.git/blob - lib/SearchDescription.php
improve handling of multi-word partials in SearchDescription
[nominatim.git] / lib / SearchDescription.php
1 <?php
2
3 namespace Nominatim;
4
5 require_once(CONST_BasePath.'/lib/SpecialSearchOperator.php');
6 require_once(CONST_BasePath.'/lib/SearchContext.php');
7 require_once(CONST_BasePath.'/lib/Result.php');
8
9 /**
10  * Description of a single interpretation of a search query.
11  */
12 class SearchDescription
13 {
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.
31     private $sClass = '';
32     /// Type of special feature to search for.
33     private $sType = '';
34     /// Housenumber of the object.
35     private $sHouseNumber = '';
36     /// Postcode for the object.
37     private $sPostcode = '';
38     /// Global search constraints.
39     private $oContext;
40
41     // Temporary values used while creating the search description.
42
43     /// Index of phrase currently processed.
44     private $iNamePhrase = -1;
45
46     /**
47      * Create an empty search description.
48      *
49      * @param object $oContext Global context to use. Will be inherited by
50      *                         all derived search objects.
51      */
52     public function __construct($oContext)
53     {
54         $this->oContext = $oContext;
55     }
56
57     /**
58      * Get current search rank.
59      *
60      * The higher the search rank the lower the likelihood that the
61      * search is a correct interpretation of the search query.
62      *
63      * @return integer Search rank.
64      */
65     public function getRank()
66     {
67         return $this->iSearchRank;
68     }
69
70     /**
71      * Make this search a POI search.
72      *
73      * In a POI search, objects are not (only) searched by their name
74      * but also by the primary OSM key/value pair (class and type in Nominatim).
75      *
76      * @param integer $iOperator Type of POI search
77      * @param string  $sClass    Class (or OSM tag key) of POI.
78      * @param string  $sType     Type (or OSM tag value) of POI.
79      *
80      * @return void
81      */
82     public function setPoiSearch($iOperator, $sClass, $sType)
83     {
84         $this->iOperator = $iOperator;
85         $this->sClass = $sClass;
86         $this->sType = $sType;
87     }
88
89     /**
90      * Check if this might be a full address search.
91      *
92      * @return bool True if the search contains name, address and housenumber.
93      */
94     public function looksLikeFullAddress()
95     {
96         return (!empty($this->aName))
97                && (!empty($this->aAddress) || $this->sCountryCode)
98                && preg_match('/[0-9]+/', $this->sHouseNumber);
99     }
100
101     /**
102      * Check if any operator is set.
103      *
104      * @return bool True, if this is a special search operation.
105      */
106     public function hasOperator()
107     {
108         return $this->iOperator != Operator::NONE;
109     }
110
111     /**
112      * Extract key/value pairs from a query.
113      *
114      * Key/value pairs are recognised if they are of the form [<key>=<value>].
115      * If multiple terms of this kind are found then all terms are removed
116      * but only the first is used for search.
117      *
118      * @param string $sQuery Original query string.
119      *
120      * @return string The query string with the special search patterns removed.
121      */
122     public function extractKeyValuePairs($sQuery)
123     {
124         // Search for terms of kind [<key>=<value>].
125         preg_match_all(
126             '/\\[([\\w_]*)=([\\w_]*)\\]/',
127             $sQuery,
128             $aSpecialTermsRaw,
129             PREG_SET_ORDER
130         );
131
132         foreach ($aSpecialTermsRaw as $aTerm) {
133             $sQuery = str_replace($aTerm[0], ' ', $sQuery);
134             if (!$this->hasOperator()) {
135                 $this->setPoiSearch(Operator::TYPE, $aTerm[1], $aTerm[2]);
136             }
137         }
138
139         return $sQuery;
140     }
141
142     /**
143      * Check if the combination of parameters is sensible.
144      *
145      * @return bool True, if the search looks valid.
146      */
147     public function isValidSearch()
148     {
149         if (empty($this->aName)) {
150             if ($this->sHouseNumber) {
151                 return false;
152             }
153             if (!$this->sClass && !$this->sCountryCode) {
154                 return false;
155             }
156         }
157
158         return true;
159     }
160
161     /////////// Search building functions
162
163
164     /**
165      * Derive new searches by adding a full term to the existing search.
166      *
167      * @param object $oSearchTerm  Description of the token.
168      * @param bool   $bHasPartial  True if there are also tokens of partial terms
169      *                             with the same name.
170      * @param string $sPhraseType  Type of phrase the token is contained in.
171      * @param bool   $bFirstToken  True if the token is at the beginning of the
172      *                             query.
173      * @param bool   $bFirstPhrase True if the token is in the first phrase of
174      *                             the query.
175      * @param bool   $bLastToken   True if the token is at the end of the query.
176      *
177      * @return SearchDescription[] List of derived search descriptions.
178      */
179     public function extendWithFullTerm($oSearchTerm, $bHasPartial, $sPhraseType, $bFirstToken, $bFirstPhrase, $bLastToken)
180     {
181         $aNewSearches = array();
182
183         if (($sPhraseType == '' || $sPhraseType == 'country')
184             && is_a($oSearchTerm, '\Nominatim\Token\Country')
185         ) {
186             if (!$this->sCountryCode) {
187                 $oSearch = clone $this;
188                 $oSearch->iSearchRank++;
189                 $oSearch->sCountryCode = $oSearchTerm->sCountryCode;
190                 // Country is almost always at the end of the string
191                 // - increase score for finding it anywhere else (optimisation)
192                 if (!$bLastToken) {
193                     $oSearch->iSearchRank += 5;
194                 }
195                 $aNewSearches[] = $oSearch;
196             }
197         } elseif (($sPhraseType == '' || $sPhraseType == 'postalcode')
198                   && is_a($oSearchTerm, '\Nominatim\Token\Postcode')
199         ) {
200             if (!$this->sPostcode) {
201                 // If we have structured search or this is the first term,
202                 // make the postcode the primary search element.
203                 if ($this->iOperator == Operator::NONE && $bFirstToken) {
204                     $oSearch = clone $this;
205                     $oSearch->iSearchRank++;
206                     $oSearch->iOperator = Operator::POSTCODE;
207                     $oSearch->aAddress = array_merge($this->aAddress, $this->aName);
208                     $oSearch->aName =
209                         array($oSearchTerm->iId => $oSearchTerm->sPostcode);
210                     $aNewSearches[] = $oSearch;
211                 }
212
213                 // If we have a structured search or this is not the first term,
214                 // add the postcode as an addendum.
215                 if ($this->iOperator != Operator::POSTCODE
216                     && ($sPhraseType == 'postalcode' || !empty($this->aName))
217                 ) {
218                     $oSearch = clone $this;
219                     $oSearch->iSearchRank++;
220                     if (strlen($oSearchTerm->sPostcode) < 4) {
221                         $oSearch->iSearchRank += 4 - strlen($oSearchTerm->sPostcode);
222                     }
223                     $oSearch->sPostcode = $oSearchTerm->sPostcode;
224                     $aNewSearches[] = $oSearch;
225                 }
226             }
227         } elseif (($sPhraseType == '' || $sPhraseType == 'street')
228                  && is_a($oSearchTerm, '\Nominatim\Token\HouseNumber')
229         ) {
230             if (!$this->sHouseNumber && $this->iOperator != Operator::POSTCODE) {
231                 $oSearch = clone $this;
232                 $oSearch->iSearchRank++;
233                 $oSearch->sHouseNumber = $oSearchTerm->sToken;
234                 // sanity check: if the housenumber is not mainly made
235                 // up of numbers, add a penalty
236                 if (preg_match('/\\d/', $oSearch->sHouseNumber) === 0
237                     || preg_match_all('/[^0-9]/', $oSearch->sHouseNumber, $aMatches) > 2) {
238                     $oSearch->iSearchRank++;
239                 }
240                 if (empty($oSearchTerm->iId)) {
241                     $oSearch->iSearchRank++;
242                 }
243                 // also must not appear in the middle of the address
244                 if (!empty($this->aAddress)
245                     || (!empty($this->aAddressNonSearch))
246                     || $this->sPostcode
247                 ) {
248                     $oSearch->iSearchRank++;
249                 }
250                 $aNewSearches[] = $oSearch;
251             }
252         } elseif ($sPhraseType == ''
253                   && is_a($oSearchTerm, '\Nominatim\Token\SpecialTerm')
254         ) {
255             if ($this->iOperator == Operator::NONE) {
256                 $oSearch = clone $this;
257                 $oSearch->iSearchRank++;
258
259                 $iOp = $oSearchTerm->iOperator;
260                 if ($iOp == Operator::NONE) {
261                     if (!empty($this->aName) || $this->oContext->isBoundedSearch()) {
262                         $iOp = Operator::NAME;
263                     } else {
264                         $iOp = Operator::NEAR;
265                     }
266                     $oSearch->iSearchRank += 2;
267                 }
268
269                 $oSearch->setPoiSearch(
270                     $iOp,
271                     $oSearchTerm->sClass,
272                     $oSearchTerm->sType
273                 );
274                 $aNewSearches[] = $oSearch;
275             }
276         } elseif ($sPhraseType != 'country'
277                   && is_a($oSearchTerm, '\Nominatim\Token\Word')
278         ) {
279             $iWordID = $oSearchTerm->iId;
280             // Full words can only be a name if they appear at the beginning
281             // of the phrase. In structured search the name must forcably in
282             // the first phrase. In unstructured search it may be in a later
283             // phrase when the first phrase is a house number.
284             if (!empty($this->aName) || !($bFirstPhrase || $sPhraseType == '')) {
285                 if (($sPhraseType == '' || !$bFirstPhrase) && !$bHasPartial) {
286                     $oSearch = clone $this;
287                     $oSearch->iSearchRank += 3 * $oSearchTerm->iTermCount;
288                     $oSearch->aAddress[$iWordID] = $iWordID;
289                     $aNewSearches[] = $oSearch;
290                 }
291             } else {
292                 $oSearch = clone $this;
293                 $oSearch->iSearchRank++;
294                 $oSearch->aName = array($iWordID => $iWordID);
295                 if (CONST_Search_NameOnlySearchFrequencyThreshold) {
296                     $oSearch->bRareName =
297                         $oSearchTerm->iSearchNameCount
298                           < CONST_Search_NameOnlySearchFrequencyThreshold;
299                 }
300                 $aNewSearches[] = $oSearch;
301             }
302         }
303
304         return $aNewSearches;
305     }
306
307     /**
308      * Derive new searches by adding a partial term to the existing search.
309      *
310      * @param string  $sToken             Term for the token.
311      * @param object  $oSearchTerm        Description of the token.
312      * @param bool    $bStructuredPhrases True if the search is structured.
313      * @param integer $iPhrase            Number of the phrase the token is in.
314      * @param array[] $aFullTokens        List of full term tokens with the
315      *                                    same name.
316      *
317      * @return SearchDescription[] List of derived search descriptions.
318      */
319     public function extendWithPartialTerm($sToken, $oSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
320     {
321         // Only allow name terms.
322         if (!(is_a($oSearchTerm, '\Nominatim\Token\Word'))) {
323             return array();
324         }
325
326         $aNewSearches = array();
327         $iWordID = $oSearchTerm->iId;
328
329         if ((!$bStructuredPhrases || $iPhrase > 0)
330             && (!empty($this->aName))
331             && strpos($sToken, ' ') === false
332         ) {
333             if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
334                 $oSearch = clone $this;
335                 $oSearch->iSearchRank += $oSearchTerm->iTermCount;
336                 if (empty($this->aName)) {
337                     $oSearch->iSearchRank++;
338                 }
339                 if (preg_match('#^[0-9]+$#', $sToken)) {
340                     $oSearch->iSearchRank++;
341                 }
342                 $oSearch->aAddress[$iWordID] = $iWordID;
343                 $aNewSearches[] = $oSearch;
344             } else {
345                 $oSearch = clone $this;
346                 $oSearch->iSearchRank++;
347                 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
348                 if (!empty($aFullTokens)) {
349                     $oSearch->iSearchRank++;
350                 }
351                 $aNewSearches[] = $oSearch;
352
353                 // revert to the token version?
354                 foreach ($aFullTokens as $oSearchTermToken) {
355                     if (is_a($oSearchTermToken, '\Nominatim\Token\Word')) {
356                         $oSearch = clone $this;
357                         $oSearch->iSearchRank += 3;
358                         $oSearch->aAddress[$oSearchTermToken->iId]
359                             = $oSearchTermToken->iId;
360                         $aNewSearches[] = $oSearch;
361                     }
362                 }
363             }
364         }
365
366         if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
367             && (empty($this->aName) || $this->iNamePhrase == $iPhrase)
368         ) {
369             $oSearch = clone $this;
370             $oSearch->iSearchRank += 2;
371             if (empty($this->aName)) {
372                 $oSearch->iSearchRank += 1;
373             }
374             if (preg_match('#^[0-9]+$#', $sToken)) {
375                 $oSearch->iSearchRank += 2;
376             }
377             if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
378                 if (empty($this->aName)
379                     && CONST_Search_NameOnlySearchFrequencyThreshold
380                 ) {
381                     $oSearch->bRareName =
382                         $oSearchTerm->iSearchNameCount
383                           < CONST_Search_NameOnlySearchFrequencyThreshold;
384                 } else {
385                     $oSearch->bRareName = false;
386                 }
387                 $oSearch->aName[$iWordID] = $iWordID;
388             } else {
389                 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
390             }
391             $oSearch->iNamePhrase = $iPhrase;
392             $aNewSearches[] = $oSearch;
393         }
394
395         return $aNewSearches;
396     }
397
398     /////////// Query functions
399
400
401     /**
402      * Query database for places that match this search.
403      *
404      * @param object  $oDB      Nominatim::DB instance to use.
405      * @param integer $iMinRank Minimum address rank to restrict search to.
406      * @param integer $iMaxRank Maximum address rank to restrict search to.
407      * @param integer $iLimit   Maximum number of results.
408      *
409      * @return mixed[] An array with two fields: IDs contains the list of
410      *                 matching place IDs and houseNumber the houseNumber
411      *                 if appicable or -1 if not.
412      */
413     public function query(&$oDB, $iMinRank, $iMaxRank, $iLimit)
414     {
415         $aResults = array();
416         $iHousenumber = -1;
417
418         if ($this->sCountryCode
419             && empty($this->aName)
420             && !$this->iOperator
421             && !$this->sClass
422             && !$this->oContext->hasNearPoint()
423         ) {
424             // Just looking for a country - look it up
425             if (4 >= $iMinRank && 4 <= $iMaxRank) {
426                 $aResults = $this->queryCountry($oDB);
427             }
428         } elseif (empty($this->aName) && empty($this->aAddress)) {
429             // Neither name nor address? Then we must be
430             // looking for a POI in a geographic area.
431             if ($this->oContext->isBoundedSearch()) {
432                 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
433             }
434         } elseif ($this->iOperator == Operator::POSTCODE) {
435             // looking for postcode
436             $aResults = $this->queryPostcode($oDB, $iLimit);
437         } else {
438             // Ordinary search:
439             // First search for places according to name and address.
440             $aResults = $this->queryNamedPlace(
441                 $oDB,
442                 $iMinRank,
443                 $iMaxRank,
444                 $iLimit
445             );
446
447             // Now search for housenumber, if housenumber provided. Can be zero.
448             if (($this->sHouseNumber || $this->sHouseNumber === '0') && !empty($aResults)) {
449                 // Downgrade the rank of the street results, they are missing
450                 // the housenumber.
451                 foreach ($aResults as $oRes) {
452                     $oRes->iResultRank++;
453                 }
454
455                 $aHnResults = $this->queryHouseNumber($oDB, $aResults);
456
457                 if (!empty($aHnResults)) {
458                     foreach ($aHnResults as $oRes) {
459                         $aResults[$oRes->iId] = $oRes;
460                     }
461                 }
462             }
463
464             // finally get POIs if requested
465             if ($this->sClass && !empty($aResults)) {
466                 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
467             }
468         }
469
470         Debug::printDebugTable('Place IDs', $aResults);
471
472         if (!empty($aResults) && $this->sPostcode) {
473             $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
474             if ($sPlaceIds) {
475                 $sSQL = 'SELECT place_id FROM placex';
476                 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
477                 $sSQL .= " AND postcode != '".$this->sPostcode."'";
478                 Debug::printSQL($sSQL);
479                 $aFilteredPlaceIDs = $oDB->getCol($sSQL);
480                 if ($aFilteredPlaceIDs) {
481                     foreach ($aFilteredPlaceIDs as $iPlaceId) {
482                         $aResults[$iPlaceId]->iResultRank++;
483                     }
484                 }
485             }
486         }
487
488         return $aResults;
489     }
490
491
492     private function queryCountry(&$oDB)
493     {
494         $sSQL = 'SELECT place_id FROM placex ';
495         $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
496         $sSQL .= ' AND rank_search = 4';
497         if ($this->oContext->bViewboxBounded) {
498             $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
499         }
500         $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
501
502         Debug::printSQL($sSQL);
503
504         $iPlaceId = $oDB->getOne($sSQL);
505
506         $aResults = array();
507         if ($iPlaceId) {
508             $aResults[$iPlaceId] = new Result($iPlaceId);
509         }
510
511         return $aResults;
512     }
513
514     private function queryNearbyPoi(&$oDB, $iLimit)
515     {
516         if (!$this->sClass) {
517             return array();
518         }
519
520         $aDBResults = array();
521         $sPoiTable = $this->poiTable();
522
523         if ($oDB->tableExists($sPoiTable)) {
524             $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
525             if ($this->oContext->sqlCountryList) {
526                 $sSQL .= ' JOIN placex USING (place_id)';
527             }
528             if ($this->oContext->hasNearPoint()) {
529                 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
530             } elseif ($this->oContext->bViewboxBounded) {
531                 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
532             }
533             if ($this->oContext->sqlCountryList) {
534                 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
535             }
536             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
537             if ($this->oContext->sqlViewboxCentre) {
538                 $sSQL .= ' ORDER BY ST_Distance(';
539                 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
540             } elseif ($this->oContext->hasNearPoint()) {
541                 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
542             }
543             $sSQL .= " LIMIT $iLimit";
544             Debug::printSQL($sSQL);
545             $aDBResults = $oDB->getCol($sSQL);
546         }
547
548         if ($this->oContext->hasNearPoint()) {
549             $sSQL = 'SELECT place_id FROM placex WHERE ';
550             $sSQL .= 'class = :class and type = :type';
551             $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
552             $sSQL .= ' AND linked_place_id is null';
553             if ($this->oContext->sqlCountryList) {
554                 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
555             }
556             $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
557             $sSQL .= " LIMIT $iLimit";
558             Debug::printSQL($sSQL);
559             $aDBResults = $oDB->getCol(
560                 $sSQL,
561                 array(':class' => $this->sClass, ':type' => $this->sType)
562             );
563         }
564
565         $aResults = array();
566         foreach ($aDBResults as $iPlaceId) {
567             $aResults[$iPlaceId] = new Result($iPlaceId);
568         }
569
570         return $aResults;
571     }
572
573     private function queryPostcode(&$oDB, $iLimit)
574     {
575         $sSQL = 'SELECT p.place_id FROM location_postcode p ';
576
577         if (!empty($this->aAddress)) {
578             $sSQL .= ', search_name s ';
579             $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
580             $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
581             $sSQL .= '      @> '.$oDB->getArraySQL($this->aAddress).' AND ';
582         } else {
583             $sSQL .= 'WHERE ';
584         }
585
586         $sSQL .= "p.postcode = '".reset($this->aName)."'";
587         $sSQL .= $this->countryCodeSQL(' AND p.country_code');
588         if ($this->oContext->bViewboxBounded) {
589             $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
590         }
591         $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
592         $sSQL .= " LIMIT $iLimit";
593
594         Debug::printSQL($sSQL);
595
596         $aResults = array();
597         foreach ($oDB->getCol($sSQL) as $iPlaceId) {
598             $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
599         }
600
601         return $aResults;
602     }
603
604     private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
605     {
606         $aTerms = array();
607         $aOrder = array();
608
609         // Sort by existence of the requested house number but only if not
610         // too many results are expected for the street, i.e. if the result
611         // will be narrowed down by an address. Remeber that with ordering
612         // every single result has to be checked.
613         if ($this->sHouseNumber && (!empty($this->aAddress) || $this->sPostcode)) {
614             $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
615             $aOrder[] = ' (';
616             $aOrder[0] .= 'EXISTS(';
617             $aOrder[0] .= '  SELECT place_id';
618             $aOrder[0] .= '  FROM placex';
619             $aOrder[0] .= '  WHERE parent_place_id = search_name.place_id';
620             $aOrder[0] .= "    AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
621             $aOrder[0] .= '  LIMIT 1';
622             $aOrder[0] .= ') ';
623             // also housenumbers from interpolation lines table are needed
624             if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
625                 $iHouseNumber = intval($this->sHouseNumber);
626                 $aOrder[0] .= 'OR EXISTS(';
627                 $aOrder[0] .= '  SELECT place_id ';
628                 $aOrder[0] .= '  FROM location_property_osmline ';
629                 $aOrder[0] .= '  WHERE parent_place_id = search_name.place_id';
630                 $aOrder[0] .= '    AND startnumber is not NULL';
631                 $aOrder[0] .= '    AND '.$iHouseNumber.'>=startnumber ';
632                 $aOrder[0] .= '    AND '.$iHouseNumber.'<=endnumber ';
633                 $aOrder[0] .= '  LIMIT 1';
634                 $aOrder[0] .= ')';
635             }
636             $aOrder[0] .= ') DESC';
637         }
638
639         if (!empty($this->aName)) {
640             $aTerms[] = 'name_vector @> '.$oDB->getArraySQL($this->aName);
641         }
642         if (!empty($this->aAddress)) {
643             // For infrequent name terms disable index usage for address
644             if ($this->bRareName) {
645                 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.$oDB->getArraySQL($this->aAddress);
646             } else {
647                 $aTerms[] = 'nameaddress_vector @> '.$oDB->getArraySQL($this->aAddress);
648             }
649         }
650
651         $sCountryTerm = $this->countryCodeSQL('country_code');
652         if ($sCountryTerm) {
653             $aTerms[] = $sCountryTerm;
654         }
655
656         if ($this->sHouseNumber) {
657             $aTerms[] = 'address_rank between 16 and 30';
658         } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
659             if ($iMinAddressRank > 0) {
660                 $aTerms[] = "((address_rank between $iMinAddressRank and $iMaxAddressRank) or (search_rank between $iMinAddressRank and $iMaxAddressRank))";
661             }
662         }
663
664         if ($this->oContext->hasNearPoint()) {
665             $aTerms[] = $this->oContext->withinSQL('centroid');
666             $aOrder[] = $this->oContext->distanceSQL('centroid');
667         } elseif ($this->sPostcode) {
668             if (empty($this->aAddress)) {
669                 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
670             } else {
671                 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
672             }
673         }
674
675         $sExcludeSQL = $this->oContext->excludeSQL('place_id');
676         if ($sExcludeSQL) {
677             $aTerms[] = $sExcludeSQL;
678         }
679
680         if ($this->oContext->bViewboxBounded) {
681             $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
682         }
683
684         if ($this->oContext->hasNearPoint()) {
685             $aOrder[] = $this->oContext->distanceSQL('centroid');
686         }
687
688         if ($this->sHouseNumber) {
689             $sImportanceSQL = '- abs(26 - address_rank) + 3';
690         } else {
691             $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
692         }
693         $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
694         $aOrder[] = "$sImportanceSQL DESC";
695
696         $aFullNameAddress = $this->oContext->getFullNameTerms();
697         if (!empty($aFullNameAddress)) {
698             $sExactMatchSQL = ' ( ';
699             $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
700             $sExactMatchSQL .= '  SELECT unnest('.$oDB->getArraySQL($aFullNameAddress).')';
701             $sExactMatchSQL .= '    INTERSECT ';
702             $sExactMatchSQL .= '  SELECT unnest(nameaddress_vector)';
703             $sExactMatchSQL .= ' ) s';
704             $sExactMatchSQL .= ') as exactmatch';
705             $aOrder[] = 'exactmatch DESC';
706         } else {
707             $sExactMatchSQL = '0::int as exactmatch';
708         }
709
710         if ($this->sHouseNumber || $this->sClass) {
711             $iLimit = 40;
712         }
713
714         $aResults = array();
715
716         if (!empty($aTerms)) {
717             $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
718             $sSQL .= ' FROM search_name';
719             $sSQL .= ' WHERE '.join(' and ', $aTerms);
720             $sSQL .= ' ORDER BY '.join(', ', $aOrder);
721             $sSQL .= ' LIMIT '.$iLimit;
722
723             Debug::printSQL($sSQL);
724
725             $aDBResults = $oDB->getAll($sSQL, null, 'Could not get places for search terms.');
726
727             foreach ($aDBResults as $aResult) {
728                 $oResult = new Result($aResult['place_id']);
729                 $oResult->iExactMatches = $aResult['exactmatch'];
730                 $aResults[$aResult['place_id']] = $oResult;
731             }
732         }
733
734         return $aResults;
735     }
736
737     private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
738     {
739         $aResults = array();
740         $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
741
742         if (!$sPlaceIDs) {
743             return $aResults;
744         }
745
746         $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
747         $sSQL = 'SELECT place_id FROM placex ';
748         $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
749         $sSQL .= "  AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
750         $sSQL .= $this->oContext->excludeSQL(' AND place_id');
751
752         Debug::printSQL($sSQL);
753
754         // XXX should inherit the exactMatches from its parent
755         foreach ($oDB->getCol($sSQL) as $iPlaceId) {
756             $aResults[$iPlaceId] = new Result($iPlaceId);
757         }
758
759         $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
760         $iHousenumber = intval($this->sHouseNumber);
761         if ($bIsIntHouseNumber && empty($aResults)) {
762             // if nothing found, search in the interpolation line table
763             $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
764             $sSQL .= ' WHERE startnumber is not NULL';
765             $sSQL .= '  AND parent_place_id in ('.$sPlaceIDs.') AND (';
766             if ($iHousenumber % 2 == 0) {
767                 // If housenumber is even, look for housenumber in streets
768                 // with interpolationtype even or all.
769                 $sSQL .= "interpolationtype='even'";
770             } else {
771                 // Else look for housenumber with interpolationtype odd or all.
772                 $sSQL .= "interpolationtype='odd'";
773             }
774             $sSQL .= " or interpolationtype='all') and ";
775             $sSQL .= $iHousenumber.'>=startnumber and ';
776             $sSQL .= $iHousenumber.'<=endnumber';
777             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
778
779             Debug::printSQL($sSQL);
780
781             foreach ($oDB->getCol($sSQL) as $iPlaceId) {
782                 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
783                 $oResult->iHouseNumber = $iHousenumber;
784                 $aResults[$iPlaceId] = $oResult;
785             }
786         }
787
788         // If nothing found try the aux fallback table
789         if (CONST_Use_Aux_Location_data && empty($aResults)) {
790             $sSQL = 'SELECT place_id FROM location_property_aux';
791             $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
792             $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
793             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
794
795             Debug::printSQL($sSQL);
796
797             foreach ($oDB->getCol($sSQL) as $iPlaceId) {
798                 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
799             }
800         }
801
802         // If nothing found then search in Tiger data (location_property_tiger)
803         if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && empty($aResults)) {
804             $sSQL = 'SELECT place_id FROM location_property_tiger';
805             $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
806             if ($iHousenumber % 2 == 0) {
807                 $sSQL .= "interpolationtype='even'";
808             } else {
809                 $sSQL .= "interpolationtype='odd'";
810             }
811             $sSQL .= " or interpolationtype='all') and ";
812             $sSQL .= $iHousenumber.'>=startnumber and ';
813             $sSQL .= $iHousenumber.'<=endnumber';
814             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
815
816             Debug::printSQL($sSQL);
817
818             foreach ($oDB->getCol($sSQL) as $iPlaceId) {
819                 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
820                 $oResult->iHouseNumber = $iHousenumber;
821                 $aResults[$iPlaceId] = $oResult;
822             }
823         }
824
825         return $aResults;
826     }
827
828
829     private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
830     {
831         $aResults = array();
832         $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
833
834         if (!$sPlaceIDs) {
835             return $aResults;
836         }
837
838         if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
839             // If they were searching for a named class (i.e. 'Kings Head pub')
840             // then we might have an extra match
841             $sSQL = 'SELECT place_id FROM placex ';
842             $sSQL .= " WHERE place_id in ($sPlaceIDs)";
843             $sSQL .= "   AND class='".$this->sClass."' ";
844             $sSQL .= "   AND type='".$this->sType."'";
845             $sSQL .= '   AND linked_place_id is null';
846             $sSQL .= $this->oContext->excludeSQL(' AND place_id');
847             $sSQL .= ' ORDER BY rank_search ASC ';
848             $sSQL .= " LIMIT $iLimit";
849
850             Debug::printSQL($sSQL);
851
852             foreach ($oDB->getCol($sSQL) as $iPlaceId) {
853                 $aResults[$iPlaceId] = new Result($iPlaceId);
854             }
855         }
856
857         // NEAR and IN are handled the same
858         if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
859             $sClassTable = $this->poiTable();
860             $bCacheTable = $oDB->tableExists($sClassTable);
861
862             $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
863             Debug::printSQL($sSQL);
864             $iMaxRank = (int) $oDB->getOne($sSQL);
865
866             // For state / country level searches the normal radius search doesn't work very well
867             $sPlaceGeom = false;
868             if ($iMaxRank < 9 && $bCacheTable) {
869                 // Try and get a polygon to search in instead
870                 $sSQL = 'SELECT geometry FROM placex';
871                 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
872                 $sSQL .= "   AND rank_search < $iMaxRank + 5";
873                 $sSQL .= "   AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
874                 $sSQL .= ' ORDER BY rank_search ASC ';
875                 $sSQL .= ' LIMIT 1';
876                 Debug::printSQL($sSQL);
877                 $sPlaceGeom = $oDB->getOne($sSQL);
878             }
879
880             if ($sPlaceGeom) {
881                 $sPlaceIDs = false;
882             } else {
883                 $iMaxRank += 5;
884                 $sSQL = 'SELECT place_id FROM placex';
885                 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
886                 Debug::printSQL($sSQL);
887                 $aPlaceIDs = $oDB->getCol($sSQL);
888                 $sPlaceIDs = join(',', $aPlaceIDs);
889             }
890
891             if ($sPlaceIDs || $sPlaceGeom) {
892                 $fRange = 0.01;
893                 if ($bCacheTable) {
894                     // More efficient - can make the range bigger
895                     $fRange = 0.05;
896
897                     $sOrderBySQL = '';
898                     if ($this->oContext->hasNearPoint()) {
899                         $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
900                     } elseif ($sPlaceIDs) {
901                         $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
902                     } elseif ($sPlaceGeom) {
903                         $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
904                     }
905
906                     $sSQL = 'SELECT distinct i.place_id';
907                     if ($sOrderBySQL) {
908                         $sSQL .= ', i.order_term';
909                     }
910                     $sSQL .= ' from (SELECT l.place_id';
911                     if ($sOrderBySQL) {
912                         $sSQL .= ','.$sOrderBySQL.' as order_term';
913                     }
914                     $sSQL .= ' from '.$sClassTable.' as l';
915
916                     if ($sPlaceIDs) {
917                         $sSQL .= ',placex as f WHERE ';
918                         $sSQL .= "f.place_id in ($sPlaceIDs) ";
919                         $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
920                     } elseif ($sPlaceGeom) {
921                         $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
922                     }
923
924                     $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
925                     $sSQL .= 'limit 300) i ';
926                     if ($sOrderBySQL) {
927                         $sSQL .= 'order by order_term asc';
928                     }
929                     $sSQL .= " limit $iLimit";
930
931                     Debug::printSQL($sSQL);
932
933                     foreach ($oDB->getCol($sSQL) as $iPlaceId) {
934                         $aResults[$iPlaceId] = new Result($iPlaceId);
935                     }
936                 } else {
937                     if ($this->oContext->hasNearPoint()) {
938                         $fRange = $this->oContext->nearRadius();
939                     }
940
941                     $sOrderBySQL = '';
942                     if ($this->oContext->hasNearPoint()) {
943                         $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
944                     } else {
945                         $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
946                     }
947
948                     $sSQL = 'SELECT distinct l.place_id';
949                     if ($sOrderBySQL) {
950                         $sSQL .= ','.$sOrderBySQL.' as orderterm';
951                     }
952                     $sSQL .= ' FROM placex as l, placex as f';
953                     $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
954                     $sSQL .= "  AND ST_DWithin(l.geometry, f.centroid, $fRange)";
955                     $sSQL .= "  AND l.class='".$this->sClass."'";
956                     $sSQL .= "  AND l.type='".$this->sType."'";
957                     $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
958                     if ($sOrderBySQL) {
959                         $sSQL .= 'ORDER BY orderterm ASC';
960                     }
961                     $sSQL .= " limit $iLimit";
962
963                     Debug::printSQL($sSQL);
964
965                     foreach ($oDB->getCol($sSQL) as $iPlaceId) {
966                         $aResults[$iPlaceId] = new Result($iPlaceId);
967                     }
968                 }
969             }
970         }
971
972         return $aResults;
973     }
974
975     private function poiTable()
976     {
977         return 'place_classtype_'.$this->sClass.'_'.$this->sType;
978     }
979
980     private function countryCodeSQL($sVar)
981     {
982         if ($this->sCountryCode) {
983             return $sVar.' = \''.$this->sCountryCode."'";
984         }
985         if ($this->oContext->sqlCountryList) {
986             return $sVar.' in '.$this->oContext->sqlCountryList;
987         }
988
989         return '';
990     }
991
992     /////////// Sort functions
993
994
995     public static function bySearchRank($a, $b)
996     {
997         if ($a->iSearchRank == $b->iSearchRank) {
998             return $a->iOperator + strlen($a->sHouseNumber)
999                      - $b->iOperator - strlen($b->sHouseNumber);
1000         }
1001
1002         return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
1003     }
1004
1005     //////////// Debugging functions
1006
1007
1008     public function debugInfo()
1009     {
1010         return array(
1011                 'Search rank' => $this->iSearchRank,
1012                 'Country code' => $this->sCountryCode,
1013                 'Name terms' => $this->aName,
1014                 'Name terms (stop words)' => $this->aNameNonSearch,
1015                 'Address terms' => $this->aAddress,
1016                 'Address terms (stop words)' => $this->aAddressNonSearch,
1017                 'Address terms (full words)' => $this->aFullNameAddress,
1018                 'Special search' => $this->iOperator,
1019                 'Class' => $this->sClass,
1020                 'Type' => $this->sType,
1021                 'House number' => $this->sHouseNumber,
1022                 'Postcode' => $this->sPostcode
1023                );
1024     }
1025
1026     public function dumpAsHtmlTableRow(&$aWordIDs)
1027     {
1028         $kf = function ($k) use (&$aWordIDs) {
1029             return $aWordIDs[$k];
1030         };
1031
1032         echo '<tr>';
1033         echo "<td>$this->iSearchRank</td>";
1034         echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
1035         echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
1036         echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
1037         echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1038         echo '<td>'.$this->sCountryCode.'</td>';
1039         echo '<td>'.Operator::toString($this->iOperator).'</td>';
1040         echo '<td>'.$this->sClass.'</td>';
1041         echo '<td>'.$this->sType.'</td>';
1042         echo '<td>'.$this->sPostcode.'</td>';
1043         echo '<td>'.$this->sHouseNumber.'</td>';
1044
1045         echo '</tr>';
1046     }
1047 }