diff --git a/Lib/Search/BookSearch.php b/Lib/Search/BookSearch.php index 9b70e45..96ba8da 100644 --- a/Lib/Search/BookSearch.php +++ b/Lib/Search/BookSearch.php @@ -146,6 +146,43 @@ class BookSearch ); } + /** + * Return a list of suggested titles for the given text + * @param string $text + * @return array + */ + public function suggest($text) { + $this->query->setQuery($text); + $this->query->setStart(0); + $this->query->setRows(0); + $this->query->setParam('suggest', 'true'); + + $results = $this->client->query($this->query)->getResponse(); + + $text = mb_strtolower ($text, 'UTF-8'); + + $suggestions = array(); + if(isset($results['suggest'])) { + foreach($results['suggest'] as $suggester) { + foreach($suggester[$text]['suggestions'] as $s) { + $s->term = strip_tags($s->term); + + $pos = strpos(mb_strtolower($s->term, 'UTF-8'), $text); + if($pos !== false) { + // increase weight of proposition that have the words at the beginning + $s->weight += (int) ((1 - $pos / strlen($s->term)) * 100); + } + $suggestions[$s->term] = (array) $s; + } + } + } + + usort($suggestions, function($a, $b) { + return $b['weight'] - $a['weight']; + }); + + return $suggestions; + } /** * Retrieve books from Solr based on their code (NoticeNr). diff --git a/NetBiblio.php b/NetBiblio.php index 491ba08..3bd5407 100644 --- a/NetBiblio.php +++ b/NetBiblio.php @@ -672,6 +672,17 @@ class NetBiblio extends WebService return array_merge($data, $this->AddBookData($results['books'])); } + /** + * This method return a list of suggested titles for the given search terms + * @param string $text + * @return array + */ + public function Suggest($text) + { + $bs = new BookSearch(); + return $bs->suggest($text); + } + /** * This method returns the list of all volunteer readers that read book * in the database.