/**
  *
  * User searcher method.
  * Example Usage :
  *      $userSearcher = $this->getServiceLocator()->get('search.query.user');
  *      $result       = $userSearcher->search(['name' => 'Haydar']);
  *
  * @param   array       $params
  * @return  array
  */
 public function search(array $params)
 {
     $qb = new \Elastica\QueryBuilder();
     $query = new \Elastica\Query($qb->query()->match_all());
     $resultSet = $this->doSearch($query, 1, 10);
     $paginator = $this->buildPaginator($resultSet);
     return $paginator;
 }
 public function autocompleteSearch(Request $request, $app, $type)
 {
     $searchText = $request->get('q');
     $search = (new \Elastica\Search(new \Elastica\Client(['host' => '162.243.187.198'])))->addIndex($app)->addType($type);
     $qb = new \Elastica\QueryBuilder();
     // $qb->query()->match()->setField('razon_social', $searchText)->setFieldType('razon_social', 'phrase')
     $query = (new Query())->setQuery($qb->query()->multi_match()->setFields(['_all'])->setType('phrase_prefix')->setQuery($searchText));
     $search->setQuery($query);
     $results = [];
     foreach ($search->search()->getResults() as $result) {
         $data = $result->getData();
         foreach (['razon_social', 'alias', 'localidad'] as $field) {
             //                $data[$field] = str_replace($searchText, sprintf('<em>%s</em>', $searchText), $data[$field]);
             $data[$field] = preg_replace("/({$searchText})/i", "<em>\$1</em>", $data[$field]);
         }
         //            foreach($result->getHighlights() as $key => $highlighted) {
         //                $data[$key] = $highlighted[0];
         //            }
         $results[] = $data;
     }
     return $results;
 }
 public function applyAction($actionName, $httpVars, $fileVars)
 {
     $messages = ConfService::getMessages();
     $repoId = $this->accessDriver->repository->getId();
     if ($actionName == "search") {
         // TMP
         if (strpos($httpVars["query"], "keyword:") === 0) {
             $parts = explode(":", $httpVars["query"]);
             $this->applyAction("search_by_keyword", array("field" => $parts[1]), array());
             return;
         }
         try {
             $this->loadIndex($repoId, false);
         } catch (Exception $ex) {
             $this->applyAction("index", array(), array());
             throw new Exception($messages["index.lucene.7"]);
         }
         $textQuery = $httpVars["query"];
         if ($this->getFilteredOption("AUTO_WILDCARD") === true && strlen($textQuery) > 0 && ctype_alnum($textQuery)) {
             if ($textQuery[0] == '"' && $textQuery[strlen($textQuery) - 1] == '"') {
                 $textQuery = substr($textQuery, 1, -1);
             } else {
                 if ($textQuery[strlen($textQuery) - 1] != "*") {
                     $textQuery .= "*";
                 }
             }
         }
         $this->currentIndex->open();
         $fieldQuery = new Elastica\Query\QueryString();
         $fieldQuery->setAllowLeadingWildcard(false);
         $fieldQuery->setFuzzyMinSim(0.8);
         if ($textQuery == "*") {
             $fields = array("ajxp_node");
             $fieldQuery->setQuery("yes");
             $fieldQuery->setFields($fields);
         } else {
             if (strpos($textQuery, ":") !== false) {
                 // USE LUCENE DSL DIRECTLY (key1:value1 AND key2:value2...)
                 $textQuery = str_replace("ajxp_meta_ajxp_document_content:", "body:", $textQuery);
                 $textQuery = $this->filterSearchRangesKeywords($textQuery);
                 $fieldQuery->setQuery($textQuery);
             } else {
                 $fields = array("basename", "ajxp_meta_*", "node_*", "body");
                 $fieldQuery->setQuery($textQuery);
                 $fieldQuery->setFields($fields);
             }
         }
         /*
         TODO : READAPT QUERY WITH EACH FIELD
         if ((isSet($this->metaFields) || $this->indexContent) && isSet($httpVars["fields"])) {
              $sParts = array();
              foreach (explode(",",$httpVars["fields"]) as $searchField) {
                  if ($searchField == "filename") {
                      $sParts[] = "basename:".$httpVars["query"];
                  } else if (in_array($searchField, $this->metaFields)) {
                      $sParts[] = "ajxp_meta_".$searchField.":".$httpVars["query"];
                  } else if ($searchField == "ajxp_document_content") {
                      $sParts[] = "title:".$httpVars["query"];
                      $sParts[] = "body:".$httpVars["query"];
                      $sParts[] = "keywords:".$httpVars["query"];
                  }
              }
              $query = implode(" OR ", $sParts);
              $query = "ajxp_scope:shared AND ($query)";
              $this->logDebug("Query : $query");
         } else {
         */
         //}
         /*
            We create this object search because it'll allow us to fetch the number of results we want at once.
            We just have to set some parameters, the query type and the size of the result set.
         */
         $search = new Elastica\Search($this->client);
         $search->addIndex($this->currentIndex)->addType($this->currentType);
         $maxResults = $this->getFilteredOption("MAX_RESULTS");
         if (isset($httpVars['limit'])) {
             $maxResults = intval($httpVars['limit']);
         }
         $searchOptions = array(\Elastica\Search::OPTION_SEARCH_TYPE => \Elastica\Search::OPTION_SEARCH_TYPE_QUERY_THEN_FETCH, \Elastica\Search::OPTION_SIZE => $maxResults);
         $this->logDebug(__FUNCTION__, "Executing query: ", $textQuery);
         $fullQuery = new Elastica\Query();
         $fullQuery->setQuery($fieldQuery);
         $qb = new Elastica\QueryBuilder();
         $fullQuery = new Elastica\Query();
         $fullQuery->setQuery($qb->query()->filtered($fieldQuery, $qb->filter()->bool()->addMust(new Elastica\Filter\Term(array("ajxp_scope" => "shared")))));
         $result = $search->search($fullQuery, $searchOptions);
         $this->logDebug(__FUNCTION__, "Search finished. ");
         $hits = $result->getResults();
         AJXP_XMLWriter::header();
         foreach ($hits as $hit) {
             $source = $hit->getSource();
             if ($source["serialized_metadata"] != null) {
                 $meta = unserialize(base64_decode($source["serialized_metadata"]));
                 $tmpNode = new AJXP_Node(SystemTextEncoding::fromUTF8($source["node_url"]), $meta);
             } else {
                 $tmpNode = new AJXP_Node(SystemTextEncoding::fromUTF8($source["node_url"]), array());
                 $tmpNode->loadNodeInfo();
             }
             if (!file_exists($tmpNode->getUrl())) {
                 $this->currentType->deleteById($hit->getId());
                 continue;
             }
             $tmpNode->search_score = sprintf("%0.2f", $hit->getScore());
             AJXP_XMLWriter::renderAjxpNode($tmpNode);
         }
         AJXP_XMLWriter::close();
     } else {
         if ($actionName == "search_by_keyword") {
             $scope = "user";
             try {
                 $this->loadIndex($repoId, false);
             } catch (Exception $ex) {
                 throw new Exception($messages["index.lucene.7"]);
             }
             $sParts = array();
             $searchField = $httpVars["field"];
             if ($scope == "user") {
                 if (AuthService::usersEnabled() && AuthService::getLoggedUser() == null) {
                     throw new Exception("Cannot find current user");
                 }
                 $sParts[] = "ajxp_scope:user";
                 $sParts[] = "ajxp_user:"******"ajxp_scope:shared";
             }
             $query = implode(" AND ", $sParts);
             $this->logDebug("Query : {$query}");
             $fieldQuery = new Elastica\Query\QueryString();
             $fields = array($searchField);
             $fieldQuery->setQuery($searchField == "ajxp_node" ? "yes" : "true");
             $fieldQuery->setFields($fields);
             $fieldQuery->setAllowLeadingWildcard(false);
             $fieldQuery->setFuzzyMinSim(0.8);
             $search = new Elastica\Search($this->client);
             $search->addIndex($this->currentIndex)->addType($this->currentType);
             $maxResults = $this->getFilteredOption("MAX_RESULTS");
             if (isset($httpVars['limit'])) {
                 $maxResults = intval($httpVars['limit']);
             }
             $searchOptions = array(\Elastica\Search::OPTION_SEARCH_TYPE => \Elastica\Search::OPTION_SEARCH_TYPE_QUERY_THEN_FETCH, \Elastica\Search::OPTION_SIZE => $maxResults);
             // ADD SCOPE FILTER
             $term = new Elastica\Filter\Term();
             $term->setTerm("ajxp_scope", "user");
             $qb = new Elastica\QueryBuilder();
             $fullQuery = new Elastica\Query();
             $fullQuery->setQuery($qb->query()->filtered($fieldQuery, $qb->filter()->bool()->addMust(new Elastica\Filter\Term(array("ajxp_scope" => "user")))->addMust(new Elastica\Filter\Term(array("user" => AuthService::getLoggedUser()->getId())))));
             $result = $search->search($fullQuery, $searchOptions);
             $this->logDebug(__FUNCTION__, "Search finished. ");
             $hits = $result->getResults();
             AJXP_XMLWriter::header();
             foreach ($hits as $hit) {
                 if ($hit->serialized_metadata != null) {
                     $meta = unserialize(base64_decode($hit->serialized_metadata));
                     $tmpNode = new AJXP_Node(SystemTextEncoding::fromUTF8($hit->node_url), $meta);
                 } else {
                     $tmpNode = new AJXP_Node(SystemTextEncoding::fromUTF8($hit->node_url), array());
                     $tmpNode->loadNodeInfo();
                 }
                 if (!file_exists($tmpNode->getUrl())) {
                     $this->currentType->deleteById($hit->id);
                     continue;
                 }
                 $tmpNode->search_score = sprintf("%0.2f", $hit->score);
                 AJXP_XMLWriter::renderAjxpNode($tmpNode);
             }
             AJXP_XMLWriter::close();
         }
     }
 }