Esempio n. 1
0
 /**
  * @param \Elastica\ResultSet            $resultSet
  * @param Mage_CatalogSearch_Model_Query $query
  */
 protected function fillSearchResultInMagentoResultTable(\Elastica\ResultSet $resultSet, Mage_CatalogSearch_Model_Query $query)
 {
     $writeAdapter = $this->_getWriteAdapter();
     $insertQuery = $this->buildInsertQuery($resultSet, $query->getId());
     $writeAdapter->query($insertQuery);
     $query->setIsProcessed(1);
 }
 /**
  * Reindex a single search query.
  *
  * @param Mage_CatalogSearch_Model_Query $query The search query.
  *
  * @return void
  */
 public function reindex($query)
 {
     /** Reindex all data from search terms custom positions index */
     $engine = Mage::helper('catalogsearch')->getEngine();
     $mapping = $engine->getCurrentIndex()->getMapping('product');
     $dataprovider = $mapping->getDataProvider('search_terms_position');
     $dataprovider->updateAllData($query->getStoreId(), $query->getProductIds());
 }
Esempio n. 3
0
 /**
  * Retrieve query model object
  *
  * @return Mage_CatalogSearch_Model_Query
  */
 public function getQuery()
 {
     if (!$this->_query) {
         $this->_query = Mage::getModel('catalogsearch/query')->loadByQuery($this->getQueryText());
         if (!$this->_query->getId()) {
             $this->_query->setQueryText($this->getQueryText());
         }
     }
     return $this->_query;
 }
Esempio n. 4
0
 /**
  * Prepare results for query
  *
  * @param Mage_CatalogSearch_Model_Fulltext $object
  * @param string $queryText
  * @param Mage_CatalogSearch_Model_Query $query
  * @return Mage_CatalogSearch_Model_Mysql4_Fulltext
  */
 public function prepareResult($object, $queryText, $query)
 {
     if (!$query->getIsProcessed()) {
         $searchType = $object->getSearchType($query->getStoreId());
         $stringHelper = Mage::helper('core/string');
         /* @var $stringHelper Mage_Core_Helper_String */
         $bind = array(':query' => $queryText);
         $like = array();
         $fulltextCond = '';
         $likeCond = '';
         $separateCond = '';
         if ($searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_LIKE || $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_COMBINE) {
             $words = $stringHelper->splitWords($queryText, true, $query->getMaxQueryWords());
             $likeI = 0;
             foreach ($words as $word) {
                 $like[] = '`s`.`data_index` LIKE :likew' . $likeI;
                 $bind[':likew' . $likeI] = '%' . $word . '%';
                 $likeI++;
             }
             if ($like) {
                 $likeCond = '(' . join(' AND ', $like) . ')';
             }
         }
         if ($searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_FULLTEXT || $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_COMBINE) {
             $fulltextCond = 'MATCH (`s`.`data_index`) AGAINST (:query IN BOOLEAN MODE)';
         }
         if ($searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_COMBINE && $likeCond) {
             $separateCond = ' OR ';
         }
         $sql = sprintf("INSERT INTO `{$this->getTable('catalogsearch/result')}` " . "(SELECT STRAIGHT_JOIN '%d', `s`.`product_id`, MATCH (`s`.`data_index`) " . "AGAINST (:query IN BOOLEAN MODE) FROM `{$this->getMainTable()}` AS `s` " . "INNER JOIN `{$this->getTable('catalog/product')}` AS `e` " . "ON `e`.`entity_id`=`s`.`product_id` WHERE (%s%s%s) AND `s`.`store_id`='%d')" . " ON DUPLICATE KEY UPDATE `relevance`=VALUES(`relevance`)", $query->getId(), $fulltextCond, $separateCond, $likeCond, $query->getStoreId());
         $this->_getWriteAdapter()->query($sql, $bind);
         $query->setIsProcessed(1);
     }
     return $this;
 }
Esempio n. 5
0
 /**
  * Prepare results for query
  *
  * @param Mage_CatalogSearch_Model_Fulltext $object
  * @param string $queryText
  * @param Mage_CatalogSearch_Model_Query $query
  * @return Mage_CatalogSearch_Model_Mysql4_Fulltext
  */
 public function prepareResult($object, $queryText, $query)
 {
     if (!$query->getIsProcessed()) {
         $searchType = $object->getSearchType($query->getStoreId());
         $stringHelper = Mage::helper('core/string');
         /* @var $stringHelper Mage_Core_Helper_String */
         $words = $stringHelper->splitWords($queryText, true, $query->getMaxQueryWords());
         $query_text = array();
         $query_text_str = '';
         if (is_array($words)) {
             foreach ($words as $word) {
                 $query_text[] = '+' . $word . '*';
             }
             $query_text_str = implode(' ', $query_text);
         }
         $bind = array(':query' => $query_text_str);
         $like = array();
         $fulltextCond = '';
         $likeCond = '';
         $separateCond = '';
         if ($searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_LIKE || $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_COMBINE) {
             $likeI = 0;
             foreach ($words as $word) {
                 $like[] = '`s`.`data_index` LIKE :likew' . $likeI;
                 $bind[':likew' . $likeI] = $word . "%";
                 $likeI++;
             }
             if ($like) {
                 $likeCond = '(' . join(' AND ', $like) . ')';
             }
         }
         if ($searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_FULLTEXT || $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_COMBINE) {
             $fulltextCond = 'MATCH (`s`.`data_index`) AGAINST (:query IN BOOLEAN MODE)';
         }
         if ($searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_COMBINE && $likeCond) {
             $separateCond = ' OR ';
         }
         //$relevanceExpression = '(MATCH (`s`.`data_index`) AGAINST (:query))';
         // Add priority attributes
         for ($i = 0; $i < self::NUMBER_OF_PRIORITY_SEARCH_ATTRIBUTES; $i++) {
             $weight = $this->_getPriorityWeight($i);
             if ($weight != 0) {
                 if ($i == 0) {
                     $relevanceExpression = '(' . intval($weight) . '*(MATCH(`s`.`data_index_' . ($i + 1) . '`) AGAINST (:query)))';
                 } else {
                     $relevanceExpression .= '+(' . intval($weight) . '*(MATCH(`s`.`data_index_' . ($i + 1) . '`) AGAINST (:query)))';
                 }
             }
         }
         if ($this->_getNegateRelevance()) {
             $relevanceExpression = '-(' . $relevanceExpression . ')';
         }
         $sql = sprintf("INSERT INTO `{$this->getTable('catalogsearch/result')}` " . "(SELECT '%d', `s`.`product_id`, %s " . "FROM `{$this->getMainTable()}` AS `s` INNER JOIN `{$this->getTable('catalog/product')}` AS `e`" . "ON `e`.`entity_id`=`s`.`product_id` WHERE (%s%s%s) AND `s`.`store_id`='%d')" . " ON DUPLICATE KEY UPDATE `relevance`=VALUES(`relevance`)", $query->getId(), $relevanceExpression, $fulltextCond, $separateCond, $likeCond, $query->getStoreId());
         $this->_getWriteAdapter()->query($sql, $bind);
         //@TODO $this->computeRelevances($object, $queryText, $query);
         $query->setIsProcessed(1);
     }
     return $this;
 }
Esempio n. 6
0
 /**
  * Prepare results for query
  *
  * @param Mage_CatalogSearch_Model_Fulltext $object
  * @param string $queryText
  * @param Mage_CatalogSearch_Model_Query $query
  * @return Mage_CatalogSearch_Model_Resource_Fulltext
  */
 public function prepareResult($object, $queryText, $query)
 {
     $adapter = $this->_getWriteAdapter();
     if (!$query->getIsProcessed()) {
         $searchType = $object->getSearchType($query->getStoreId());
         $preparedTerms = Mage::getResourceHelper('catalogsearch')->prepareTerms($queryText, $query->getMaxQueryWords());
         $bind = array();
         $like = array();
         $likeCond = '';
         if ($searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_LIKE || $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_COMBINE) {
             $helper = Mage::getResourceHelper('core');
             $words = Mage::helper('core/string')->splitWords($queryText, true, $query->getMaxQueryWords());
             foreach ($words as $word) {
                 $like[] = $helper->getCILike('s.data_index', $word, array('position' => 'any'));
             }
             if ($like) {
                 $likeCond = '(' . join(' OR ', $like) . ')';
             }
         }
         $mainTableAlias = 's';
         $fields = array('query_id' => new Zend_Db_Expr($query->getId()), 'product_id');
         $select = $adapter->select()->from(array($mainTableAlias => $this->getMainTable()), $fields)->joinInner(array('e' => $this->getTable('catalog/product')), 'e.entity_id = s.product_id', array())->where($mainTableAlias . '.store_id = ?', (int) $query->getStoreId());
         if ($searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_FULLTEXT || $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_COMBINE) {
             $bind[':query'] = implode(' ', $preparedTerms[0]);
             $where = Mage::getResourceHelper('catalogsearch')->chooseFulltext($this->getMainTable(), $mainTableAlias, $select);
         }
         if ($likeCond != '' && $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_COMBINE) {
             $where .= ($where ? ' OR ' : '') . $likeCond;
         } elseif ($likeCond != '' && $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_LIKE) {
             $select->columns(array('relevance' => new Zend_Db_Expr(0)));
             $where = $likeCond;
         }
         if ($where != '') {
             $select->where($where);
         }
         /*
         $sql = $adapter->insertFromSelect($select,
             $this->getTable('catalogsearch/result'),
             array(),
             Varien_Db_Adapter_Interface::INSERT_ON_DUPLICATE);
         $adapter->query($sql, $bind);
         */
         $conn = new Connection();
         $conn->setParams(array('host' => '127.0.0.1', 'port' => 9306));
         /** @var SphinxQL $sphinxQuery */
         $sphinxQuery = SphinxQL::create($conn)->select(array('*', SphinxQL::expr('WEIGHT()')))->from('fulltext')->option('ranker', 'bm25')->option('field_weights', SphinxQL::expr('(name=7, attributes=3, data_index=1)'))->option('cutoff', 5000)->option('max_matches', 1000)->limit(0, 100)->match('*', $queryText);
         $results = $sphinxQuery->execute();
         foreach ($results as $result) {
             // Ensure we log query results into the Magento table.
             $sql = sprintf("INSERT INTO {$this->getTable('catalogsearch/result')} " . " (query_id, product_id, relevance) VALUES " . " (%d, %d, %f) " . " ON DUPLICATE KEY UPDATE relevance = %f", $query->getId(), $result['id'], $result['weight()'] / 1000, $result['weight()'] / 1000);
             $this->_getWriteAdapter()->query($sql, $bind);
         }
         $conn->close();
         $query->setIsProcessed(1);
     }
     return $this;
 }
Esempio n. 7
0
 public function _getResource()
 {
     if (Mage::helper('catalog/category_flat')->isEnabled()) {
         // Temporary to test
         return Mage::getResourceSingleton('catalogsearch/query');
         //return Mage::getResourceSingleton('solr/product');
     } else {
         /** If we get here, we get nesting errors. please fix */
         return parent::getResource();
     }
 }
Esempio n. 8
0
 /**
  * Prepare results for query
  *
  * @param Mage_CatalogSearch_Model_Fulltext $object
  * @param string $queryText
  * @param Mage_CatalogSearch_Model_Query $query
  * @return Mage_CatalogSearch_Model_Resource_Fulltext
  */
 public function prepareResult($object, $queryText, $query)
 {
     $adapter = $this->_getWriteAdapter();
     if (!$query->getIsProcessed()) {
         $searchType = $object->getSearchType($query->getStoreId());
         $preparedTerms = Mage::getResourceHelper('catalogsearch')->prepareTerms($queryText, $query->getMaxQueryWords());
         $bind = array();
         $like = array();
         $likeCond = '';
         if ($searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_LIKE || $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_COMBINE) {
             $helper = Mage::getResourceHelper('core');
             $words = Mage::helper('core/string')->splitWords($queryText, true, $query->getMaxQueryWords());
             foreach ($words as $word) {
                 $like[] = $helper->getCILike('s.data_index', $word, array('position' => 'any'));
             }
             if ($like) {
                 $likeCond = '(' . join(' AND ', $like) . ')';
             }
         }
         $mainTableAlias = 's';
         $fields = array('query_id' => new Zend_Db_Expr($query->getId()), 'product_id');
         $select = $adapter->select()->from(array($mainTableAlias => $this->getMainTable()), $fields)->joinInner(array('e' => $this->getTable('catalog/product')), 'e.entity_id = s.product_id', array())->where($mainTableAlias . '.store_id = ?', (int) $query->getStoreId());
         if ($searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_FULLTEXT || $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_COMBINE) {
             $bind[':query'] = implode(' ', $preparedTerms[0]);
             $where = Mage::getResourceHelper('catalogsearch')->chooseFulltext($this->getMainTable(), $mainTableAlias, $select);
         }
         if ($likeCond != '' && $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_COMBINE) {
             $where .= ($where ? ' OR ' : '') . $likeCond;
         } elseif ($likeCond != '' && $searchType == Mage_CatalogSearch_Model_Fulltext::SEARCH_TYPE_LIKE) {
             $select->columns(array('relevance' => new Zend_Db_Expr(0)));
             $where = $likeCond;
         }
         if ($where != '') {
             $select->where($where);
         }
         $sql = $adapter->insertFromSelect($select, $this->getTable('catalogsearch/result'), array(), Varien_Db_Adapter_Interface::INSERT_ON_DUPLICATE);
         $adapter->query($sql, $bind);
         $query->setIsProcessed(1);
     }
     return $this;
 }
Esempio n. 9
0
 /**
  * Onject initialization
  */
 protected function setPopularity($popularity)
 {
     // If module is disabled
     if ((bool) Mage::getStoreConfig('disablelog/settings/enabled') == false) {
         return parent::setPopularity($popularity);
     }
     // Disable search-hitting for user-agents
     $userAgent = Mage::helper('core/http')->getHttpUserAgent();
     $ignoreAgents = Mage::getConfig()->getNode('global/skip_user_agents');
     if ($ignoreAgents) {
         $ignoreAgents = $ignoreAgents->asArray();
         foreach ($ignoreAgents as $ignoreAgent) {
             if (stristr($userAgent, $ignoreAgent)) {
                 return false;
             }
         }
     }
     return parent::setPopularity($popularity);
 }
 public function getObject(Mage_CatalogSearch_Model_Query $suggestion)
 {
     $suggestion_obj = array('objectID' => $suggestion->getData('query_id'), 'query' => $suggestion->getData('query_text'), 'number_of_results' => (int) $suggestion->getData('num_results'), 'popularity' => (int) $suggestion->getData('popularity'), 'updated_at' => (int) strtotime($suggestion->getData('updated_at')));
     return $suggestion_obj;
 }
Esempio n. 11
0
 /**
  * This function is called when a visitor searches
  *
  * @param Mage_CatalogSearch_Model_Fulltext $object
  * @param string $queryText
  * @param Mage_CatalogSearch_Model_Query $query
  * @return JeroenVermeulen_Solarium_Model_Resource_CatalogSearch_Fulltext
  */
 public function prepareResult($object, $queryText, $query)
 {
     if (JeroenVermeulen_Solarium_Model_Engine::isEnabled($query->getStoreId())) {
         $helper = Mage::helper('jeroenvermeulen_solarium');
         $adapter = $this->_getWriteAdapter();
         $searchResultTable = $this->getTable('catalogsearch/result');
         $catSearchHelper = Mage::helper('catalogsearch');
         $stringHelper = Mage::helper('core/string');
         $thisQueryLength = $stringHelper->strlen($queryText);
         $wordsFull = $stringHelper->splitWords($queryText, true);
         $wordsLike = $stringHelper->splitWords($queryText, true, $catSearchHelper->getMaxQueryWords());
         /* Validate strings and return normal search to handle messages */
         if ($catSearchHelper->getMaxQueryLength() < $thisQueryLength || $catSearchHelper->getMinQueryLength() > $thisQueryLength || count($wordsFull) > count($wordsLike)) {
             return parent::prepareResult($object, $queryText, $query);
         }
         /** @var JeroenVermeulen_Solarium_Model_Engine $engine */
         $engine = Mage::getSingleton('jeroenvermeulen_solarium/engine');
         if ($engine->isWorking()) {
             $searchResult = $engine->search($query->getStoreId(), $queryText);
             $searchResult->setUserQuery($queryText);
             Mage::register('solarium_search_result', $searchResult);
             if (!$searchResult->getResultCount()) {
                 // Autocorrect
                 if ($engine->getConf('results/autocorrect', $query->getStoreId())) {
                     $searchResult->autoCorrect();
                 }
             }
             $resultProducts = $searchResult->getResultProducts();
             if (!$searchResult->getResultCount()) {
                 // No results, we need to check if the index is empty.
                 if ($engine->isEmpty($query->getStoreId())) {
                     Mage::Log(sprintf('%s - Warning: index is empty', __CLASS__), Zend_Log::WARN);
                 } else {
                     $query->setIsProcessed(1);
                 }
             } else {
                 $columns = array('query_id', 'product_id', 'relevance');
                 $insertRows = array();
                 $queryId = $query->getId();
                 foreach ($resultProducts as $data) {
                     $insertRows[] = array($queryId, $data['product_id'], $data['relevance']);
                 }
                 $adapter->beginTransaction();
                 $adapter->delete($searchResultTable, 'query_id = ' . $queryId);
                 $adapter->insertArray($searchResultTable, $columns, $insertRows);
                 $adapter->commit();
                 $query->setIsProcessed(1);
             }
             // Autocorrect notification
             if ($searchResult->didAutoCorrect()) {
                 $catSearchHelper->addNoteMessage($helper->__("Showing results for '%s' instead.", $searchResult->getResultQuery()));
             }
             // "Did you mean" suggestions
             $suggestions = $searchResult->getBetterSuggestions();
             if ($suggestions) {
                 $suggestHtml = '';
                 foreach ($suggestions as $searchTerm => $result_count) {
                     $title = $helper->__('Results') . ': ' . $result_count;
                     $href = Mage::getUrl('catalogsearch/result', array('q' => $searchTerm));
                     $suggestHtml .= sprintf('&nbsp; <a title="%s" href="%s">%s</a>', $title, $href, $searchTerm);
                 }
                 $catSearchHelper->addNoteMessage($helper->__('Did you mean:') . $suggestHtml);
             }
             /** @deprecated The registry key 'solarium_suggest' is deprecated, it was used in 1.6.0 till 1.6.2 */
             Mage::register('solarium_suggest', $searchResult->getBetterSuggestions());
         }
     }
     if (!$query->getIsProcessed()) {
         Mage::log('Solr disabled or something went wrong, fallback to Magento Fulltext Search', Zend_Log::WARN);
         return parent::prepareResult($object, $queryText, $query);
     }
     return $this;
 }
 /**
  *
  * @param Mage_CatalogSearch_Model_Query $query        	
  * @return array
  */
 protected function _getBaseRecommendations($query)
 {
     $productIds = array();
     $storeId = (int) $query->getStoreId();
     $recommendationBase = Mage::getStoreConfig('catalog/autocompleterecommendations/recommendation_base', $storeId);
     $resourceModel = @$this->_recommendationBase[$recommendationBase]['resource_model'];
     $order = (array) @$this->_recommendationBase[$recommendationBase]['order'];
     $collection = Mage::getResourceModel($resourceModel);
     $collection->addOrderedQty()->setStoreId($storeId)->setStoreIds(array($storeId))->addStoreFilter($storeId)->addViewsCount();
     $from = Mage::getStoreConfig('catalog/autocompleterecommendations/recommendation_from', $storeId);
     if (!$from) {
         $from = date('Y-01-01');
     }
     $to = Mage::getStoreConfig('catalog/autocompleterecommendations/recommendation_to', $storeId);
     if (!$to) {
         $to = date('Y-m-d');
     }
     $collection->setDateRange($from, $to);
     if ($collection->getSize()) {
         $productIds = $collection->getColumnValues('entity_id');
     }
     return (array) $productIds;
 }
 /**
  * Verify if a given search query has custom positions defined for products
  *
  * @param Mage_CatalogSearch_Model_Query|int $query The concerned search query
  *
  * @return bool
  */
 public function hasCustomPositions($query)
 {
     $result = false;
     if ($query->getId()) {
         $adapter = $this->_getReadAdapter();
         $select = $adapter->select();
         $select->from(array("main_table" => $this->getMainTable()));
         $select->where('query_id = ?', (int) $query->getId());
         $result = $adapter->fetchRow($select) !== false;
     }
     return $result;
 }