Author: Nicolas Ruflin (spam@ruflin.com)
Author: Thibault Duplessis (thibault.duplessis@gmail.com)
Author: Oleg Zinchenko (olegz@default-value.com)
Author: Roberto Nygaard (roberto@nygaard.es)
 /**
  * @param mixed  $query
  * @param string $lang
  * @param string $type
  *
  * @return mixed|void
  */
 public function defineSearch($query, $lang, $type)
 {
     $query = \Elastica\Util::escapeTerm($query);
     $elasticaQueryLang = new \Elastica\Query\Term();
     $elasticaQueryLang->setTerm('lang', $lang);
     $elasticaQueryString = new \Elastica\Query\Match();
     $elasticaQueryString->setFieldQuery('content', $query)->setFieldMinimumShouldMatch('content', '80%');
     $elasticaQueryTitle = new \Elastica\Query\QueryString();
     $elasticaQueryTitle->setDefaultField('title')->setBoost(2.0)->setQuery($query);
     $elasticaQueryBool = new \Elastica\Query\BoolQuery();
     $elasticaQueryBool->addMust($elasticaQueryLang)->addShould($elasticaQueryTitle)->addShould($elasticaQueryString)->setMinimumNumberShouldMatch(1);
     $this->applySecurityContext($elasticaQueryBool);
     if (!is_null($type)) {
         $elasticaQueryType = new \Elastica\Query\Term();
         $elasticaQueryType->setTerm('type', $type);
         $elasticaQueryBool->addMust($elasticaQueryType);
     }
     $rootNode = $this->domainConfiguration->getRootNode();
     if (!is_null($rootNode)) {
         $elasticaQueryRoot = new \Elastica\Query\Term();
         $elasticaQueryRoot->setTerm('root_id', $rootNode->getId());
         $elasticaQueryBool->addMust($elasticaQueryRoot);
     }
     $this->query->setQuery($elasticaQueryBool);
     $this->query->setHighlight(array('pre_tags' => array('<strong>'), 'post_tags' => array('</strong>'), 'fields' => array('content' => array('fragment_size' => 150, 'number_of_fragments' => 3))));
 }
 public function getQueryForSearch(ArticleSearch $articleSearch)
 {
     // we create a query to return all the articles
     // but if the criteria title is specified, we use it
     if ($articleSearch->getTitle() !== null && $articleSearch != '') {
         $query = new \Elastica\Query\Match();
         $query->setFieldQuery('article.title', $articleSearch->getTitle());
         $query->setFieldFuzziness('article.title', 0.7);
         $query->setFieldMinimumShouldMatch('article.title', '80%');
     } else {
         $query = new \Elastica\Query\MatchAll();
     }
     // then we create filters depending on the chosen criterias
     $boolQuery = new \Elastica\Query\Bool();
     $boolQuery->addMust($query);
     /*
         Dates filter
         We add this filter only the ispublished filter is not at "false"
     */
     if ("false" != $articleSearch->isPublished() && null !== $articleSearch->getDateFrom() && null !== $articleSearch->getDateTo()) {
         $boolQuery->addMust(new \Elastica\Query\Range('publishedAt', array('gte' => \Elastica\Util::convertDate($articleSearch->getDateFrom()->getTimestamp()), 'lte' => \Elastica\Util::convertDate($articleSearch->getDateTo()->getTimestamp()))));
     }
     // Published or not filter
     if ($articleSearch->isPublished() !== null) {
         $boolQuery->addMust(new \Elastica\Query\Terms('published', array($articleSearch->isPublished())));
     }
     $query = new \Elastica\Query($boolQuery);
     $query->setSort(array($articleSearch->getSort() => array('order' => $articleSearch->getDirection())));
     return $query;
 }
 /**
  * {@inheritdoc}
  */
 public function filter(ProxyQueryInterface $query, $alias, $field, $data)
 {
     if (!$data || !is_array($data) || !array_key_exists('type', $data) || !array_key_exists('value', $data)) {
         return;
     }
     $data['type'] = !isset($data['type']) ? ChoiceType::TYPE_CONTAINS : $data['type'];
     list($firstOperator, $secondOperator) = $this->getOperators((int) $data['type']);
     if (is_array($data['value'])) {
         if (count($data['value']) == 0) {
             return;
         }
         if (in_array('all', $data['value'], true)) {
             return;
         }
         $queryBuilder = new \Elastica\Query\Builder();
         $queryBuilder->fieldOpen($secondOperator)->field($field, Util::escapeTerm($data['value']))->fieldClose();
         if ($firstOperator == 'must') {
             $query->addMust($queryBuilder);
         } else {
             $query->addMustNot($queryBuilder);
         }
     } else {
         if ($data['value'] === '' || $data['value'] === null || $data['value'] === false || $data['value'] === 'all') {
             return;
         }
         $queryBuilder = new \Elastica\Query\Builder();
         $queryBuilder->fieldOpen($secondOperator)->field($field, Util::escapeTerm(array($data['value'])))->fieldClose();
         if ($firstOperator == 'must') {
             $query->addMust($queryBuilder);
         } else {
             $query->addMustNot($queryBuilder);
         }
     }
 }
Esempio n. 4
0
 public function testConvertDateTimeObjectWithoutTimezone()
 {
     $dateTimeObject = new \DateTime();
     $timestamp = $dateTimeObject->getTimestamp();
     $convertedString = Util::convertDateTimeObject($dateTimeObject, false);
     $date = date('Y-m-d\\TH:i:s\\Z', $timestamp);
     $this->assertEquals($convertedString, $date);
 }
 /**
  * @group functional
  */
 public function testSearch()
 {
     $index = $this->_createIndex();
     $index->getSettings()->setNumberOfReplicas(0);
     $type = new Type($index, 'helloworld');
     $doc = new Document(1, array('email' => '*****@*****.**', 'username' => 'test 7/6 123', 'test' => array('2', '3', '5')));
     $type->addDocument($doc);
     // Refresh index
     $index->refresh();
     $queryString = new QueryString(Util::escapeTerm('test 7/6'));
     $resultSet = $type->search($queryString);
     $this->assertEquals(1, $resultSet->count());
 }
Esempio n. 6
0
 /**
  * Makes calls to the elasticsearch server.
  *
  * @param \Elastica\Request $request
  * @param array             $params  Host, Port, ...
  *
  * @throws \Elastica\Exception\ResponseException
  * @throws \Elastica\Exception\InvalidException
  *
  * @return \Elastica\Response Response object
  */
 public function exec(Request $request, array $params)
 {
     $memcache = new \Memcache();
     $memcache->connect($this->getConnection()->getHost(), $this->getConnection()->getPort());
     $data = $request->getData();
     $content = '';
     if (!empty($data) || '0' === $data) {
         if (is_array($data)) {
             $content = JSON::stringify($data);
         } else {
             $content = $data;
         }
         // Escaping of / not necessary. Causes problems in base64 encoding of files
         $content = str_replace('\\/', '/', $content);
     }
     $responseString = '';
     $start = microtime(true);
     switch ($request->getMethod()) {
         case Request::POST:
         case Request::PUT:
             $key = $request->getPath();
             $this->_checkKeyLength($key);
             $memcache->set($key, $content);
             break;
         case Request::GET:
             $key = $request->getPath() . '?source=' . $content;
             $this->_checkKeyLength($key);
             $responseString = $memcache->get($key);
             break;
         case Request::DELETE:
             $key = $request->getPath() . '?source=' . $content;
             $this->_checkKeyLength($key);
             $responseString = $memcache->delete($key);
             break;
         default:
         case Request::HEAD:
             throw new InvalidException('Method ' . $request->getMethod() . ' is not supported in memcache transport');
     }
     $end = microtime(true);
     $response = new Response($responseString);
     if (\Elastica\Util::debugEnabled()) {
         $response->setQueryTime($end - $start);
     }
     if ($response->hasError()) {
         throw new ResponseException($request, $response);
     }
     if ($response->hasFailedShards()) {
         throw new PartialShardFailureException($request, $response);
     }
     return $response;
 }
 public function testConvertRequestToCurlCommand()
 {
     $path = 'test';
     $method = Request::POST;
     $query = array('no' => 'params');
     $data = array('key' => 'value');
     $connection = new Connection();
     $connection->setHost('localhost');
     $connection->setPort('9200');
     $request = new Request($path, $method, $data, $query, $connection);
     $curlCommand = Util::convertRequestToCurlCommand($request);
     $expected = 'curl -XPOST \'http://localhost:9200/test?no=params\' -d \'{"key":"value"}\'';
     $this->assertEquals($expected, $curlCommand);
 }
 public function searchAdvanced($q = '')
 {
     if ($q == '') {
         $baseQuery = new \Elastica\Query\MatchAll();
     } else {
         $baseQuery = new \Elastica\Query\Match();
         $baseQuery->setFieldQuery('description', $q);
         $baseQuery->setFieldFuzziness('description', 0.7);
         $baseQuery->setFieldMinimumShouldMatch('description', '80%');
     }
     $boolFilter = new \Elastica\Filter\BoolFilter();
     $dateFrom = new \DateTime();
     $dateFrom->sub(new \DateInterval('P7D'));
     $dateTo = new \DateTime();
     $dateTo->add(new \DateInterval('P1D'));
     $boolFilter->addMust(new \Elastica\Filter\Range('createdAt', array('gte' => \Elastica\Util::convertDate($dateFrom->getTimestamp()), 'lte' => \Elastica\Util::convertDate($dateTo->getTimestamp()))));
     /*
      * $boolFilter->addMust(
      *     new \Elastica\Filter\Term(array('isPublished' => true))
      * );
      * $boolFilter->addMust(
      *     new \Elastica\Filter\Terms('isPublished', array('1', '2', '3'))
      * );
      */
     /*
      * $baseQuery = new \Elastica\Filter\Bool();
      * $baseQuery->addShould(
      *     new \Elastica\Filter\Term(array('id' => intval($q)))
      * );
      * $baseQuery->addShould(
      *     new \Elastica\Filter\Term(array('amount' => floatval($q)))
      * );
      * $filtered = new \Elastica\Query\Filtered();
      * $filtered->setFilter($baseQuery);
      * return $this->finder->find($filtered);
      */
     /*
      * $baseQuery  = new \Elastica\Query\Bool;
      * $idQueryTerm = new \Elastica\Query\Term;
      * $idQueryTerm->setTerm('id', intval($q));
      * $baseQuery->addShould($idQueryTerm);
      */
     $filtered = new \Elastica\Query\Filtered($baseQuery, $boolFilter);
     $query = \Elastica\Query::create($filtered);
     $query->addSort(array('id' => array('order' => 'asc')));
     $query->setSize(1);
     return $this->find($query);
 }
Esempio n. 9
0
 /**
  * Makes calls to the elasticsearch server.
  *
  * All calls that are made to the server are done through this function
  *
  * @param \Elastica\Request $elasticaRequest
  * @param array             $params          Host, Port, ...
  *
  * @throws \Elastica\Exception\ConnectionException
  * @throws \Elastica\Exception\ResponseException
  * @throws \Elastica\Exception\Connection\HttpException
  *
  * @return \Elastica\Response Response object
  */
 public function exec(ElasticaRequest $elasticaRequest, array $params)
 {
     $connection = $this->getConnection();
     if ($timeout = $connection->getTimeout()) {
         $this->httpAdapter->getConfiguration()->setTimeout($timeout);
     }
     $httpAdapterRequest = $this->_createHttpAdapterRequest($elasticaRequest, $connection);
     $start = microtime(true);
     $httpAdapterResponse = $this->httpAdapter->sendRequest($httpAdapterRequest);
     $end = microtime(true);
     $elasticaResponse = $this->_createElasticaResponse($httpAdapterResponse, $connection);
     if (\Elastica\Util::debugEnabled()) {
         $elasticaResponse->setQueryTime($end - $start);
     }
     $elasticaResponse->setTransferInfo(array('request_header' => $httpAdapterRequest->getMethod(), 'http_code' => $httpAdapterResponse->getStatusCode()));
     if ($elasticaResponse->hasError()) {
         throw new ResponseException($elasticaRequest, $elasticaResponse);
     }
     if ($elasticaResponse->hasFailedShards()) {
         throw new PartialShardFailureException($elasticaRequest, $elasticaResponse);
     }
     return $elasticaResponse;
 }
Esempio n. 10
0
 public function AetUserSearch($searchText)
 {
     //$finder = $this->container->get('fos_elastica.finder.aetsite.aetusers');
     $baseQuery = new \Elastica\Query();
     $boolQuery = new \Elastica\Query\Bool();
     if (strlen($searchText) == 4 && ctype_digit($searchText)) {
         // Your Convert logic
         $boolFilter = new \Elastica\Filter\Bool();
         $from = new \DateTime('01/01/' . $searchText);
         $to = new \DateTime('12/31/' . $searchText);
         $boolFilter->addMust(new \Elastica\Filter\Range('promotion', array('gte' => \Elastica\Util::convertDate($from->getTimestamp()), 'lte' => \Elastica\Util::convertDate($to->getTimestamp()))));
         $baseQuery->setPostFilter($boolFilter);
     } else {
         $fieldQuery = new \Elastica\Query\Match();
         $fieldQuery->setFieldQuery('firstname', $searchText);
         //$fieldQuery->setFieldParam('title', 'analyzer', 'custom_search_analyzer');
         $boolQuery->addShould($fieldQuery);
         $field1Query = new \Elastica\Query\Match();
         $field1Query->setFieldQuery('lastname', $searchText);
         $boolQuery->addShould($field1Query);
         $field1Query = new \Elastica\Query\Match();
         $field1Query->setFieldQuery('pays', $searchText);
         $boolQuery->addShould($field1Query);
         $field1Query = new \Elastica\Query\Match();
         $field1Query->setFieldQuery('ville', $searchText);
         $boolQuery->addShould($field1Query);
         $field1Query = new \Elastica\Query\Match();
         $field1Query->setFieldQuery('codePostale', $searchText);
         $boolQuery->addShould($field1Query);
         $field1Query = new \Elastica\Query\Match();
         $field1Query->setFieldQuery('activitePrincipale', $searchText);
         $boolQuery->addShould($field1Query);
         $baseQuery->setQuery($boolQuery);
     }
     // Option 1. Returns all users who have example.net in any of their mapped fields
     return $this->find($baseQuery);
 }
Esempio n. 11
0
 /**
  * Param's name
  * Picks the last part of the class name and makes it snake_case
  * You can override this method if you want to change the name.
  *
  * @return string name
  */
 protected function _getBaseName()
 {
     return Util::getParamName($this);
 }
Esempio n. 12
0
 public function search(Category $currentCategory, CategorySearch $categorySearch)
 {
     // We create a query to return all the products
     $baseQuery = new \Elastica\Query\MatchAll();
     // Then we create filters depending on the chosen criterias
     // Filter products
     $productTypeFilter = new \Elastica\Filter\Type();
     $productTypeFilter->setType('product');
     // Filter for products with available courses
     $nestedFilter = new \Elastica\Filter\Nested();
     $nestedFilter->setPath('courses');
     $nestedFilter->setQuery(new \Elastica\Query\Range('beginDate', array('gte' => \Elastica\Util::convertDate((new \DateTime())->getTimestamp()))));
     // Create a bool filter to put everything together
     $boolFilter = new \Elastica\Filter\Bool();
     $boolFilter->addMust($productTypeFilter);
     $boolFilter->addMust($nestedFilter);
     // Show only products
     // Filter type
     if ($categorySearch->getIsProduct() || $categorySearch->getIsInfoEvent()) {
         // Create OR filter to put together the types
         $typeOrFilter = new \Elastica\Filter\BoolOr();
         // Filter products
         if ($categorySearch->getIsProduct()) {
             $productAndFilter = new \Elastica\Filter\BoolAnd();
             $productAndFilter->addFilter($productTypeFilter);
             $infoFilter = new \Elastica\Filter\Term(array('infoVa' => false));
             $productAndFilter->addFilter($infoFilter);
             $typeOrFilter->addFilter($productAndFilter);
         }
         // Filter info events if isProduct is not selected
         if ($categorySearch->getIsInfoEvent()) {
             $productAndFilter = new \Elastica\Filter\BoolAnd();
             $productAndFilter->addFilter($productTypeFilter);
             $infoFilter = new \Elastica\Filter\Term(array('infoVa' => true));
             $productAndFilter->addFilter($infoFilter);
             $typeOrFilter->addFilter($productAndFilter);
         }
         $boolFilter->addMust($typeOrFilter);
     }
     // Filter product type
     if ($categorySearch->getProductType()) {
         $productTypeFilter = new \Elastica\Filter\Nested();
         $productTypeFilter->setPath('productType');
         $productTypeFilter->setFilter(new \Elastica\Filter\Term(array('productType._id' => $categorySearch->getProductType()->getId())));
         $boolFilter->addMust($productTypeFilter);
     }
     // Filter day time
     if ($categorySearch->getDayTime()) {
         $dayTimeFilter = new \Elastica\Filter\Nested();
         $dayTimeFilter->setPath('courses');
         $dayTimeFilter->setFilter(new \Elastica\Filter\Term(array('courses.dayTimes' => $categorySearch->getDayTime())));
         $boolFilter->addMust($dayTimeFilter);
     }
     // Filter categories
     $categoryIds = array();
     if ($categorySearch->getSubcategories() instanceof \Traversable) {
         foreach ($categorySearch->getSubcategories() as $category) {
             if (is_object($category)) {
                 $categoryIds[] = $category->getId();
             } else {
                 $categoryIds[] = $category;
             }
         }
     }
     if (empty($categoryIds)) {
         $categoryIds[] = $currentCategory->getId();
         foreach ($currentCategory->getChildren() as $child) {
             $categoryIds[] = $child->getId();
         }
     }
     $categoryFilter = new \Elastica\Filter\BoolOr();
     $mainCategoryFilter = new \Elastica\Filter\Nested();
     $mainCategoryFilter->setPath('category');
     $mainCategoryFilter->setFilter(new \Elastica\Filter\Terms('category._id', array($categoryIds)));
     $subCategoryFilter = new \Elastica\Filter\Nested();
     $subCategoryFilter->setPath('subcategory');
     $subCategoryFilter->setFilter(new \Elastica\Filter\Terms('subcategory._id', array($categoryIds)));
     $additionalCategoryFilter = new \Elastica\Filter\Nested();
     $additionalCategoryFilter->setPath('additionalCategories');
     $additionalCategoryFilter->setFilter(new \Elastica\Filter\Terms('additionalCategories._id', array($categoryIds)));
     $categoryFilter->addFilter($mainCategoryFilter);
     $categoryFilter->addFilter($subCategoryFilter);
     $categoryFilter->addFilter($additionalCategoryFilter);
     $boolFilter->addMust($categoryFilter);
     $filtered = new \Elastica\Query\Filtered($baseQuery, $boolFilter);
     $query = \Elastica\Query::create($filtered);
     $sort = $categorySearch->getSort();
     if (!empty($sort)) {
         $sort = explode(' ', $sort);
         $query->setSort(array($sort[0] => array('order' => $sort[1]), "_score" => array('order' => 'desc')));
     }
     $paginated = $this->finder->findPaginated($query);
     $paginated->setMaxPerPage($categorySearch->getPerPage())->setCurrentPage($categorySearch->getPage());
     return $paginated;
 }
Esempio n. 13
0
 /**
  * Converts given time to format: 1995-12-31T23:59:59Z.
  *
  * This is the lucene date format
  *
  * @param int $date Date input (could be string etc.) -> must be supported by strtotime
  *
  * @return string Converted date string
  */
 public function convertDate($date)
 {
     return Util::convertDate($date);
 }
Esempio n. 14
0
 /**
  * Makes calls to the elasticsearch server.
  *
  * All calls that are made to the server are done through this function
  *
  * @param \Elastica\Request $request
  * @param array             $params  Host, Port, ...
  *
  * @throws \Elastica\Exception\ConnectionException
  * @throws \Elastica\Exception\ResponseException
  * @throws \Elastica\Exception\Connection\HttpException
  *
  * @return \Elastica\Response Response object
  */
 public function exec(Request $request, array $params)
 {
     $connection = $this->getConnection();
     $conn = $this->_getConnection($connection->isPersistent());
     // If url is set, url is taken. Otherwise port, host and path
     $url = $connection->hasConfig('url') ? $connection->getConfig('url') : '';
     if (!empty($url)) {
         $baseUri = $url;
     } else {
         $baseUri = $this->_scheme . '://' . $connection->getHost() . ':' . $connection->getPort() . '/' . $connection->getPath();
     }
     $baseUri .= $request->getPath();
     $query = $request->getQuery();
     if (!empty($query)) {
         $baseUri .= '?' . http_build_query($query);
     }
     curl_setopt($conn, CURLOPT_URL, $baseUri);
     curl_setopt($conn, CURLOPT_TIMEOUT, $connection->getTimeout());
     curl_setopt($conn, CURLOPT_FORBID_REUSE, 0);
     /* @see Connection::setConnectTimeout() */
     $connectTimeout = $connection->getConnectTimeout();
     if ($connectTimeout > 0) {
         curl_setopt($conn, CURLOPT_CONNECTTIMEOUT, $connectTimeout);
     }
     $proxy = $connection->getProxy();
     // See: https://github.com/facebook/hhvm/issues/4875
     if (is_null($proxy) && defined('HHVM_VERSION')) {
         $proxy = getenv('http_proxy') ?: null;
     }
     if (!is_null($proxy)) {
         curl_setopt($conn, CURLOPT_PROXY, $proxy);
     }
     $this->_setupCurl($conn);
     $headersConfig = $connection->hasConfig('headers') ? $connection->getConfig('headers') : array();
     if (!empty($headersConfig)) {
         $headers = array();
         while (list($header, $headerValue) = each($headersConfig)) {
             array_push($headers, $header . ': ' . $headerValue);
         }
         curl_setopt($conn, CURLOPT_HTTPHEADER, $headers);
     }
     // TODO: REFACTOR
     $data = $request->getData();
     $httpMethod = $request->getMethod();
     if (!empty($data) || '0' === $data) {
         if ($this->hasParam('postWithRequestBody') && $this->getParam('postWithRequestBody') == true) {
             $httpMethod = Request::POST;
         }
         if (is_array($data)) {
             $content = JSON::stringify($data, 'JSON_ELASTICSEARCH');
         } else {
             $content = $data;
         }
         // Escaping of / not necessary. Causes problems in base64 encoding of files
         $content = str_replace('\\/', '/', $content);
         curl_setopt($conn, CURLOPT_POSTFIELDS, $content);
     } else {
         curl_setopt($conn, CURLOPT_POSTFIELDS, '');
     }
     curl_setopt($conn, CURLOPT_NOBODY, $httpMethod == 'HEAD');
     curl_setopt($conn, CURLOPT_CUSTOMREQUEST, $httpMethod);
     if (\Elastica\Util::debugEnabled()) {
         // Track request headers when in debug mode
         curl_setopt($conn, CURLINFO_HEADER_OUT, true);
     }
     $start = microtime(true);
     // cURL opt returntransfer leaks memory, therefore OB instead.
     ob_start();
     curl_exec($conn);
     $responseString = ob_get_clean();
     $end = microtime(true);
     // Checks if error exists
     $errorNumber = curl_errno($conn);
     $response = new Response($responseString, curl_getinfo($this->_getConnection(), CURLINFO_HTTP_CODE));
     if (\Elastica\Util::debugEnabled()) {
         $response->setQueryTime($end - $start);
     }
     $response->setTransferInfo(curl_getinfo($conn));
     if ($response->hasError()) {
         throw new ResponseException($request, $response);
     }
     if ($response->hasFailedShards()) {
         throw new PartialShardFailureException($request, $response);
     }
     if ($errorNumber > 0) {
         throw new HttpException($errorNumber, $request, $response);
     }
     return $response;
 }
 protected function _getFilterName($filter)
 {
     return Util::getParamName($filter);
 }
Esempio n. 16
0
 public function search(SiteSearch $siteSearch)
 {
     // We create a query to return all the articles but if the criteria text is specified, we use it
     if ($siteSearch->getText() != null && $siteSearch != '') {
         $baseQuery = new \Elastica\Query\MultiMatch();
         $baseQuery->setQuery($siteSearch->getText())->setFields(array('title', 'subtitle', 'courseContent', 'content'));
         $baseQuery->setFuzziness(0.7);
         $baseQuery->setMinimumShouldMatch('80%');
     } else {
         $baseQuery = new \Elastica\Query\MatchAll();
     }
     // Then we create filters depending on the chosen criterias
     // Filter courses only if type is not "product"
     $productTypeFilter = new \Elastica\Filter\Type();
     $productTypeFilter->setType('product');
     $productNotFilter = new \Elastica\Filter\BoolNot($productTypeFilter);
     // Filter for products with available courses
     $nestedFilter = new \Elastica\Filter\Nested();
     $nestedFilter->setPath('courses');
     $nestedFilter->setQuery(new \Elastica\Query\Range('beginDate', array('gte' => \Elastica\Util::convertDate((new \DateTime())->getTimestamp()))));
     // Filter not(products) OR products with available courses
     $orFilter = new \Elastica\Filter\BoolOr();
     $orFilter->addFilter($productNotFilter);
     $orFilter->addFilter($nestedFilter);
     // Create a bool filter to put everything together
     $boolFilter = new \Elastica\Filter\Bool();
     $boolFilter->addMust($orFilter);
     // Filter type
     if ($siteSearch->getIsProduct() || $siteSearch->getIsInfoEvent() || $siteSearch->getIsContent()) {
         // Create OR filter to put together the types
         $typeOrFilter = new \Elastica\Filter\BoolOr();
         // Filter products
         if ($siteSearch->getIsProduct()) {
             $productAndFilter = new \Elastica\Filter\BoolAnd();
             $productAndFilter->addFilter($productTypeFilter);
             $infoFilter = new \Elastica\Filter\Term(array('infoVa' => false));
             $productAndFilter->addFilter($infoFilter);
             $typeOrFilter->addFilter($productAndFilter);
         }
         // Filter info events if isProduct is not selected
         if ($siteSearch->getIsInfoEvent()) {
             $productAndFilter = new \Elastica\Filter\BoolAnd();
             $productAndFilter->addFilter($productTypeFilter);
             $infoFilter = new \Elastica\Filter\Term(array('infoVa' => true));
             $productAndFilter->addFilter($infoFilter);
             $typeOrFilter->addFilter($productAndFilter);
         }
         // Filter content
         if ($siteSearch->getIsContent()) {
             $typeOrFilter->addFilter($productNotFilter);
         }
         $boolFilter->addMust($typeOrFilter);
     }
     // Filter product type
     if ($siteSearch->getProductType()) {
         $productTypeFilter = new \Elastica\Filter\Nested();
         $productTypeFilter->setPath('productType');
         $productTypeFilter->setFilter(new \Elastica\Filter\Term(array('productType._id' => $siteSearch->getProductType()->getId())));
         $boolFilter->addMust($productTypeFilter);
     }
     // Filter day time
     if ($siteSearch->getDayTime()) {
         $dayTimeFilter = new \Elastica\Filter\Nested();
         $dayTimeFilter->setPath('courses');
         $dayTimeFilter->setFilter(new \Elastica\Filter\Term(array('courses.dayTimes' => $siteSearch->getDayTime())));
         $boolFilter->addMust($dayTimeFilter);
     }
     // Filter category
     if ($siteSearch->getCategory()) {
         $categoryFilter = new \Elastica\Filter\BoolOr();
         $mainCategoryFilter = new \Elastica\Filter\Nested();
         $mainCategoryFilter->setPath('category');
         $mainCategoryFilter->setFilter(new \Elastica\Filter\Term(array('category._id' => $siteSearch->getCategory()->getId())));
         $subCategoryFilter = new \Elastica\Filter\Nested();
         $subCategoryFilter->setPath('subcategory');
         $subCategoryFilter->setFilter(new \Elastica\Filter\Term(array('subcategory._id' => $siteSearch->getCategory()->getId())));
         $additionalCategoryFilter = new \Elastica\Filter\Nested();
         $additionalCategoryFilter->setPath('additionalCategories');
         $additionalCategoryFilter->setFilter(new \Elastica\Filter\Term(array('additionalCategories._id' => $siteSearch->getCategory()->getId())));
         $categoryFilter->addFilter($mainCategoryFilter);
         $categoryFilter->addFilter($subCategoryFilter);
         $categoryFilter->addFilter($additionalCategoryFilter);
         $boolFilter->addMust($categoryFilter);
     }
     $filtered = new \Elastica\Query\Filtered($baseQuery, $boolFilter);
     $query = \Elastica\Query::create($filtered);
     $sort = $siteSearch->getSort();
     if (!empty($sort)) {
         $sort = explode(' ', $sort);
         $query->setSort(array($sort[0] => array('order' => $sort[1]), "_score" => array('order' => 'desc')));
     }
     $paginated = $this->finder->findPaginated($query);
     $paginated->setMaxPerPage($siteSearch->getPerPage())->setCurrentPage($siteSearch->getPage());
     return $paginated;
 }
Esempio n. 17
0
 /**
  * Makes calls to the elasticsearch server.
  *
  * All calls that are made to the server are done through this function
  *
  * @param \Elastica\Request $request
  * @param array             $params  Host, Port, ...
  *
  * @throws \Elastica\Exception\ConnectionException
  * @throws \Elastica\Exception\ResponseException
  * @throws \Elastica\Exception\Connection\HttpException
  *
  * @return \Elastica\Response Response object
  */
 public function exec(Request $request, array $params)
 {
     $connection = $this->getConnection();
     $client = $this->_getGuzzleClient($this->_getBaseUrl($connection), $connection->isPersistent());
     $options = array('exceptions' => false);
     if ($connection->getTimeout()) {
         $options['timeout'] = $connection->getTimeout();
     }
     $proxy = $connection->getProxy();
     // See: https://github.com/facebook/hhvm/issues/4875
     if (is_null($proxy) && defined('HHVM_VERSION')) {
         $proxy = getenv('http_proxy') ?: null;
     }
     if (!is_null($proxy)) {
         $options['proxy'] = $proxy;
     }
     $req = $client->createRequest($request->getMethod(), $this->_getActionPath($request), $options);
     $req->setHeaders($connection->hasConfig('headers') ? $connection->getConfig('headers') : array());
     $data = $request->getData();
     if (!empty($data) || '0' === $data) {
         if ($req->getMethod() == Request::GET) {
             $req->setMethod(Request::POST);
         }
         if ($this->hasParam('postWithRequestBody') && $this->getParam('postWithRequestBody') == true) {
             $request->setMethod(Request::POST);
             $req->setMethod(Request::POST);
         }
         if (is_array($data)) {
             $content = JSON::stringify($data, 'JSON_ELASTICSEARCH');
         } else {
             $content = $data;
         }
         $req->setBody(Stream::factory($content));
     }
     try {
         $start = microtime(true);
         $res = $client->send($req);
         $end = microtime(true);
     } catch (TransferException $ex) {
         throw new GuzzleException($ex, $request, new Response($ex->getMessage()));
     }
     $response = new Response((string) $res->getBody(), $res->getStatusCode());
     if (\Elastica\Util::debugEnabled()) {
         $response->setQueryTime($end - $start);
     }
     $response->setTransferInfo(array('request_header' => $request->getMethod(), 'http_code' => $res->getStatusCode()));
     if ($response->hasError()) {
         throw new ResponseException($request, $response);
     }
     if ($response->hasFailedShards()) {
         throw new PartialShardFailureException($request, $response);
     }
     return $response;
 }
Esempio n. 18
0
 /**
  * Makes calls to the elasticsearch server.
  *
  * @param \Elastica\Request $request
  * @param array             $params  Host, Port, ...
  *
  * @throws \Elastica\Exception\Connection\ThriftException
  * @throws \Elastica\Exception\ResponseException
  *
  * @return \Elastica\Response Response object
  */
 public function exec(Request $request, array $params)
 {
     $connection = $this->getConnection();
     $sendTimeout = $connection->hasConfig('sendTimeout') ? $connection->getConfig('sendTimeout') : null;
     $recvTimeout = $connection->hasConfig('recvTimeout') ? $connection->getConfig('recvTimeout') : null;
     $framedTransport = $connection->hasConfig('framedTransport') ? (bool) $connection->getConfig('framedTransport') : false;
     try {
         $client = $this->_getClient($connection->getHost(), $connection->getPort(), $sendTimeout, $recvTimeout, $framedTransport);
         $restRequest = new RestRequest();
         $restRequest->method = array_search($request->getMethod(), Method::$__names);
         $restRequest->uri = $request->getPath();
         $query = $request->getQuery();
         if (!empty($query)) {
             $restRequest->parameters = $query;
         }
         $data = $request->getData();
         if (!empty($data) || '0' === $data) {
             if (is_array($data)) {
                 $content = JSON::stringify($data);
             } else {
                 $content = $data;
             }
             $restRequest->body = $content;
         }
         /* @var $result RestResponse */
         $start = microtime(true);
         $result = $client->execute($restRequest);
         $response = new Response($result->body);
         $end = microtime(true);
     } catch (TException $e) {
         $response = new Response('');
         throw new ThriftException($e, $request, $response);
     }
     if (\Elastica\Util::debugEnabled()) {
         $response->setQueryTime($end - $start);
     }
     if ($response->hasError()) {
         throw new ResponseException($request, $response);
     }
     if ($response->hasFailedShards()) {
         throw new PartialShardFailureException($request, $response);
     }
     return $response;
 }