public static function truncateHighLight($text, $limit) { preg_match('/' . preg_quote(ElasticSearchConfig::getHighLigthPre()) . '/', $text, $matches, PREG_OFFSET_CAPTURE); if ($matches) { $posPreTag = $matches[0][1]; //If pos if at the beginning it is not necessary to truncate the left part if ($posPreTag > $limit * 0.75) { $pos = strpos($text, " ", $posPreTag - $limit * 0.3); $text = substr($text, $pos); $text = '... ' . $text; } return JHtmlString::truncate($text, $limit + 4, true, true); } return $text; }
/** * Main method to make a search */ public function search() { $this->getSearchFields(); $word = JRequest::getString('searchword', null, 'get'); $offset = JRequest::getInt('start', 0, 'get'); $limit = JRequest::getInt('limit', 10, 'get'); if ($limit == 0) { // no limit $limit = 10000; } $this->getSearchAreas(); $elasticaQueryString = new \Elastica\Query\QueryString(); // Log search word only on the first page if ($offset == 0) { SearchHelper::logSearch($word); } // Convert accents $word = htmlentities($word, ENT_NOQUOTES, 'utf-8'); $word = preg_replace('#\\&([A-za-z])(?:uml|circ|tilde|acute|grave|cedil|ring)\\;#', '\\1', $word); $word = preg_replace('#\\&([A-za-z]{2})(?:lig)\\;#', '\\1', $word); $word = preg_replace('#\\&[^;]+\\;#', '', $word); // Check if there are quotes ( for exact search ) $exactSearch = false; if (strlen($word) > 1 && $word[0] == '"' && $word[strlen($word) - 1] == '"') { $exactSearch = true; $word = substr($word, 1, strlen($word) - 2); // Remove external " } $word = Elastica\Util::replaceBooleanWordsAndEscapeTerm($word); // Escape ElasticSearch specials char if ($exactSearch) { $word = '"' . $word . '"'; } if ($word == "") { $word = "*"; } $elasticaQueryString->setQuery($word); //Create the actual search object with some data. $elasticaQuery = new Elastica\Query(); $elasticaQuery->setQuery($elasticaQueryString); if (ElasticSearchConfig::getHighLigthEnable()) { $fields = $this->getHighlightFields(); $hlfields = array(); foreach ($fields as $field) { foreach ($field as $highlight) { $hlfields[] = array($highlight => array('fragment_size' => 1000, 'number_of_fragments' => 1)); } } $highlightFields = array('pre_tags' => array(ElasticSearchConfig::getHighLigthPre()), 'post_tags' => array(ElasticSearchConfig::getHighLigthPost()), "order" => "score", 'fields' => $hlfields); $elasticaQuery->setHighlight($highlightFields); } // Set offset and limit for pagination $elasticaQuery->setFrom($offset); $elasticaQuery->setLimit($limit); //Create a filter for _type $elasticaFilterype = $this->createFilterType($this->areas); // Add filter to the search object. $elasticaQuery->setFilter($elasticaFilterype); //Search on the index. $elasticaResultSet = $this->elasticaIndex->search($elasticaQuery); $this->results = $elasticaResultSet->getResults(); $this->totalHits = $elasticaResultSet->getTotalHits(); }