Пример #1
0
 /**
  * @group functional
  */
 public function testFilterInsideHasChildSearch()
 {
     $index = $this->prepareSearchData();
     $f = new \Elastica\Filter\Term();
     $f->setTerm('user', 'child1');
     $filter = new HasChild($f, 'child');
     $searchQuery = new \Elastica\Query();
     $searchQuery->setPostFilter($filter);
     $searchResults = $index->search($searchQuery);
     $this->assertEquals(1, $searchResults->count());
     $result = $searchResults->current()->getData();
     $expected = array('id' => 'parent1', 'user' => 'parent1', 'email' => '*****@*****.**');
     $this->assertEquals($expected, $result);
 }
 public function execute()
 {
     $baseName = $this->getOption('baseName', wfWikiId());
     if ($this->hasOption('show-all')) {
         $this->show();
     } elseif ($this->hasOption('update')) {
         $this->update($baseName);
     } else {
         $filter = new \Elastica\Filter\BoolOr();
         foreach ($this->getConnection()->getAllIndexTypes() as $type) {
             $term = new \Elastica\Filter\Term();
             $term->setTerm('_id', $this->getConnection()->getIndexName($baseName, $type));
             $filter->addFilter($term);
         }
         $this->show($filter);
     }
 }
Пример #3
0
 /**
  * @param {Integer} libraryID
  * @param {String} searchText
  * @return {Array<String>|Boolean} An array of item keys, or FALSE if no results
  */
 public static function searchInLibrary($libraryID, $searchText)
 {
     // TEMP: For now, strip double-quotes and make everything a phrase search
     $searchText = str_replace('"', '', $searchText);
     $type = self::getReadType();
     $libraryFilter = new \Elastica\Filter\Term();
     $libraryFilter->setTerm("libraryID", $libraryID);
     $matchQuery = new \Elastica\Query\Match();
     $matchQuery->setFieldQuery('content', $searchText);
     $matchQuery->setFieldType('content', 'phrase');
     $matchQuery = new \Elastica\Query\Filtered($matchQuery, $libraryFilter);
     $start = microtime(true);
     $resultSet = $type->search($matchQuery, ['routing' => $libraryID]);
     StatsD::timing("elasticsearch.client.item_fulltext.search", (microtime(true) - $start) * 1000);
     if ($resultSet->getResponse()->hasError()) {
         throw new Exception($resultSet->getResponse()->getError());
     }
     $results = $resultSet->getResults();
     $keys = array();
     foreach ($results as $result) {
         $keys[] = explode("/", $result->getId())[1];
     }
     return $keys;
 }
 /**
  * Run the search against a sanitized query string via ElasticSearch.
  *
  * @param string $string
  * @param array $scriptProperties The scriptProperties array from the SimpleSearch snippet
  * @return array
  */
 public function search($string, array $scriptProperties = array())
 {
     $fields = $this->modx->getOption('sisea.elastic.search_fields', null, 'pagetitle^20,introtext^10,alias^5,content^1');
     $fields = explode(',', $fields);
     $fields = array_map('trim', $fields);
     $fields = array_keys(array_flip($fields));
     $fields = array_filter($fields);
     if (empty($fields)) {
         return false;
     }
     /** @var \Elastica\Query\MultiMatch $query */
     $query = new \Elastica\Query\MultiMatch();
     $query->setFields($fields);
     $query->setQuery($string);
     $customFilterScore = new \Elastica\Query\CustomFiltersScore();
     $customFilterScore->setQuery($query);
     $searchBoosts = $this->modx->getOption('sisea.elastic.search_boost', null, '');
     $searchBoosts = explode('|', $searchBoosts);
     $searchBoosts = array_map('trim', $searchBoosts);
     $searchBoosts = array_keys(array_flip($searchBoosts));
     $searchBoosts = array_filter($searchBoosts);
     $boosts = array();
     foreach ($searchBoosts as $boost) {
         $arr = array('field' => '', 'value' => '', 'boost' => 1.0);
         $field = explode('=', $boost);
         $field = array_map('trim', $field);
         $field = array_keys(array_flip($field));
         $field = array_filter($field);
         if (count($field) != 2) {
             continue;
         }
         $value = explode('^', $field[1]);
         $value = array_map('trim', $value);
         $value = array_keys(array_flip($value));
         $value = array_filter($value);
         if (count($value) != 2) {
             continue;
         }
         $arr['field'] = $field[0];
         $arr['value'] = $value[0];
         $arr['boost'] = $value[1];
         $boosts[] = $arr;
     }
     if (empty($boosts)) {
         $customFilterScore->addFilter(new \Elastica\Filter\Term(array('type' => 'document')), 1);
     } else {
         foreach ($boosts as $boost) {
             $customFilterScore->addFilter(new \Elastica\Filter\Term(array($boost['field'] => $boost['value'])), $boost['boost']);
         }
     }
     /** @var \Elastica\Query $elasticaQuery */
     $elasticaQuery = new \Elastica\Query();
     $elasticaQuery->setQuery($customFilterScore);
     /* set limit */
     $perPage = $this->modx->getOption('perPage', $scriptProperties, 10);
     if (!empty($perPage)) {
         $offset = $this->modx->getOption('start', $scriptProperties, 0);
         $offsetIndex = $this->modx->getOption('offsetIndex', $scriptProperties, 'sisea_offset');
         if (isset($_REQUEST[$offsetIndex])) {
             $offset = (int) $_REQUEST[$offsetIndex];
         }
         $elasticaQuery->setFrom($offset);
         $elasticaQuery->setSize($perPage);
     }
     $elasticaFilterAnd = new \Elastica\Filter\BoolAnd();
     /* handle hidemenu option */
     $hideMenu = $this->modx->getOption('hideMenu', $scriptProperties, 2);
     if ($hideMenu != 2) {
         $elasticaFilterHideMenu = new \Elastica\Filter\Term();
         $elasticaFilterHideMenu->setTerm('hidemenu', $hideMenu ? 1 : 0);
         $elasticaFilterAnd->addFilter($elasticaFilterHideMenu);
     }
     /* handle contexts */
     $contexts = $this->modx->getOption('contexts', $scriptProperties, '');
     $contexts = !empty($contexts) ? $contexts : $this->modx->context->get('key');
     $contexts = explode(',', $contexts);
     $elasticaFilterContext = new \Elastica\Filter\Terms();
     $elasticaFilterContext->setTerms('context_key', $contexts);
     $elasticaFilterAnd->addFilter($elasticaFilterContext);
     /* handle restrict search to these IDs */
     $ids = $this->modx->getOption('ids', $scriptProperties, '');
     if (!empty($ids)) {
         $idType = $this->modx->getOption('idType', $this->config, 'parents');
         $depth = $this->modx->getOption('depth', $this->config, 10);
         $ids = $this->processIds($ids, $idType, $depth);
         $elasticaFilterId = new \Elastica\Filter\Term();
         $elasticaFilterId->setTerm('id', $ids);
         $elasticaFilterAnd->addFilter($elasticaFilterId);
     }
     /* handle exclude IDs from search */
     $exclude = $this->modx->getOption('exclude', $scriptProperties, '');
     if (!empty($exclude)) {
         $exclude = $this->cleanIds($exclude);
         $exclude = explode(',', $exclude);
         $elasticaFilterExcludeId = new \Elastica\Filter\Term();
         $elasticaFilterExcludeId->setTerm('id', $exclude);
         $elasticaFilterNotId = new \Elastica\Filter\BoolNot($elasticaFilterExcludeId);
         $elasticaFilterAnd->addFilter($elasticaFilterNotId);
     }
     /* basic always-on conditions */
     $elasticaFilterPublished = new \Elastica\Filter\Term();
     $elasticaFilterPublished->setTerm('published', 1);
     $elasticaFilterAnd->addFilter($elasticaFilterPublished);
     $elasticaFilterSearchable = new \Elastica\Filter\Term();
     $elasticaFilterSearchable->setTerm('searchable', 1);
     $elasticaFilterAnd->addFilter($elasticaFilterSearchable);
     $elasticaFilterDeleted = new \Elastica\Filter\Term();
     $elasticaFilterDeleted->setTerm('deleted', 0);
     $elasticaFilterAnd->addFilter($elasticaFilterDeleted);
     $elasticaQuery->setFilter($elasticaFilterAnd);
     /* sorting */
     if (!empty($scriptProperties['sortBy'])) {
         $sortDir = $this->modx->getOption('sortDir', $scriptProperties, 'desc');
         $sortDirs = explode(',', $sortDir);
         $sortBys = explode(',', $scriptProperties['sortBy']);
         $dir = 'desc';
         $sortArray = array();
         for ($i = 0; $i < count($sortBys); $i++) {
             if (isset($sortDirs[$i])) {
                 $dir = $sortDirs[$i];
             }
             $sortArray[] = array($sortBys[$i] => $dir);
         }
         $elasticaQuery->setSort($sortArray);
     }
     /* prepare response array */
     $response = array('total' => 0, 'start' => !empty($offset) ? $offset : 0, 'limit' => $perPage, 'status' => 0, 'query_time' => 0, 'results' => array());
     $elasticaResultSet = $this->index->search($elasticaQuery);
     $elasticaResults = $elasticaResultSet->getResults();
     $totalResults = $elasticaResultSet->getTotalHits();
     if ($totalResults > 0) {
         $response['total'] = $totalResults;
         $response['query_time'] = $elasticaResultSet->getTotalTime();
         $response['status'] = 1;
         $response['results'] = array();
         foreach ($elasticaResults as $doc) {
             $d = $doc->getData();
             /** @var modResource $resource */
             $resource = $this->modx->newObject($d['class_key']);
             if ($resource->checkPolicy('list')) {
                 $response['results'][] = $d;
             }
         }
     }
     return $response;
 }
Пример #5
0
 public function getColorAttributes($allArticles, $elasticIndexVariants, $colors)
 {
     foreach ($allArticles as $article) {
         $article_ids[] = $article->getId();
     }
     $boolQuery = new \Elastica\Query\BoolQuery();
     $articleRefQuery = new \Elastica\Query\Terms();
     $articleRefQuery->setTerms('articleRef', $article_ids);
     $boolQuery->addMust($articleRefQuery);
     $query = new \Elastica\Query();
     $query->setQuery($boolQuery);
     $agg2 = new \Elastica\Aggregation\Terms("variantsattr");
     $agg2->setField('variantvalues.otherTerms');
     $agg2->setSize(50);
     $filter = new \Elastica\Filter\Term();
     $filter->setTerm('attributeRef', 1);
     $agg4 = new \Elastica\Aggregation\Filters('filterColor');
     $agg4->addFilter($filter);
     $agg4->addAggregation($agg2);
     $cAgg = new \Elastica\Aggregation\Nested('colors', 'variantvalues');
     $cAgg->addAggregation($agg4);
     $query->addAggregation($cAgg);
     $aggResult = $elasticIndexVariants->search($query);
     $colors = $aggResult->getAggregations();
     $result = [];
     foreach ($colors['colors']['filterColor']['buckets'][0]['variantsattr']['buckets'] as $color) {
         $result[] = $color;
     }
     return $result;
 }
 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();
         }
     }
 }
Пример #7
0
 public function newTerm($key, $val)
 {
     $termFilter = new \Elastica\Filter\Term();
     $termFilter->setTerm($key, $val);
     return $termFilter;
 }
Пример #8
0
 public function searchLoans($conditions = array(), $page = 1, $limit = 20)
 {
     $conditions += ['search' => false];
     $search = $conditions['search'];
     unset($conditions['search']);
     $queryString = new \Elastica\Query\QueryString();
     $loanIndex = $this->getLoanIndex();
     $query = new \Elastica\Query();
     if ($search) {
         $queryString->setDefaultOperator('AND');
         $queryString->setQuery($search);
         $query->setQuery($queryString);
     }
     $filterAnd = new \Elastica\Filter\BoolAnd();
     foreach ($conditions as $field => $value) {
         $termFilter = new \Elastica\Filter\Term();
         $termFilter->setTerm($field, $value);
         $filterAnd->addFilter($termFilter);
     }
     if ($conditions) {
         $query->setFilter($filterAnd);
     }
     $query->setFrom(($page - 1) * $limit);
     $query->setSize($page * $limit);
     $results = $loanIndex->search($query);
     $ids = [];
     foreach ($results as $result) {
         $data = $result->getData();
         $ids[$data['id']] = $data['id'];
     }
     $loans = LoanQuery::create()->filterById($ids)->find();
     $sortedLoans = $ids;
     foreach ($loans as $loan) {
         $sortedLoans[$loan->getId()] = $loan;
     }
     $sortedLoans = array_filter($sortedLoans, function ($l) {
         return !is_scalar($l);
     });
     $paginatorFactory = \App::make('paginator');
     return $paginatorFactory->make($sortedLoans, $results->getTotalHits(), $limit);
 }
Пример #9
0
 /**
  * @SWG\Api(
  *   path="/posts/search",
  *   @SWG\Operation(
  *     method="POST",
  *     summary="Search items in posts",
  *     nickname="posts_search",
  *      @SWG\Parameter(
  *           name="post_type",
  *           required=false,
  *           type="string"
  *         ),
  *      @SWG\Parameter(
  *           name="filters",
  *           description="filter values, eg. [{my_parameter: 'mustmatchthis'}]
  *           required=false,
  *           type="array[]"
  *         ),
  *      @SWG\Parameter(
  *           name="search_phrase",
  *           required=false,
  *           type="string"
  *         ),
  *      @SWG\Parameter(
  *           name="sort",
  *           description="sort configuration, eg [{'post_name':{'order':'asc'}}]",
  *           required=false,
  *           type="array[]"
  *         ),
  *      @SWG\Parameter(
  *           name="limit",
  *           description="Max number of documents in return",
  *           required=false,
  *           type="integer"
  *         )
  *   )
  * )
  */
 function search()
 {
     $result = array();
     $body = $this->getBodyAsArray();
     $required_parameters = array();
     $optional_parameters = array('post_type', 'filters', 'search_phrase', 'sort', 'limit', 'size', 'from');
     $this->check_req_opt_param($required_parameters, $optional_parameters, $body);
     $index = $this->elastica->getIndex($this->getElasticsearchIndex());
     $query = new \Elastica\Query();
     $boolean = new \Elastica\Query\Bool();
     $added = false;
     $type = isset($body['post_type']) ? $body['post_type'] : null;
     if ($type) {
         $q = new \Elastica\Query\Term(array('_type' => $type));
         $boolean->addMust($q);
         $added = true;
     }
     $filters = isset($body['filters']) ? (array) $body['filters'] : array();
     $filters = array_filter($filters);
     $filterAnd = '';
     if ($filters) {
         foreach ($filters as $key => $vals) {
             if (!is_array($vals)) {
                 $vals = array($vals);
             }
             if (strpos(implode('', $vals), '*')) {
                 foreach ($vals as $val) {
                     $extraQuery = new \Elastica\Query\SimpleQueryString($val, array($key));
                     $boolean->addMust($extraQuery);
                 }
             } else {
                 $filterOr = new \Elastica\Filter\BoolOr();
                 foreach ($vals as $val) {
                     $filter = new \Elastica\Filter\Term();
                     $filter->setTerm($key, $val);
                     $filterOr->addFilter($filter);
                 }
                 if (!$filterAnd) {
                     $filterAnd = new \Elastica\Filter\BoolAnd();
                 }
                 $filterAnd->addFilter($filterOr);
             }
         }
     }
     $search_phrase = isset($body['search_phrase']) ? $body['search_phrase'] : null;
     if (isset($search_phrase) && !empty($search_phrase)) {
         $word = strtolower($search_phrase) . '*';
         $elasticaQueryString = new \Elastica\Query\SimpleQueryString($word);
         $boolean->addMust($elasticaQueryString);
         $added = true;
     }
     if ($added) {
         $query->setQuery($boolean);
     }
     if ($filterAnd) {
         $query->setPostFilter($filterAnd);
     }
     $limit = isset($body['limit']) ? (int) $body['limit'] : null;
     if ($limit) {
         $query->setSize($limit);
     }
     $sort = isset($body['sort']) ? (array) $body['sort'] : null;
     if ($sort) {
         $query->setSort($sort);
         // example: array( 'post_date' => array( 'order' => 'desc' ) )
     }
     $body['from'] = isset($body['from']) && $body['from'] ? $body['from'] : 0;
     $body['size'] = isset($body['size']) && $body['size'] ? $body['size'] : 1000;
     $elasticaResultSet = $index->search($query, ['from' => $body['from'], 'size' => $body['size']]);
     foreach ($elasticaResultSet->getResults() as $elasticaResult) {
         $result[] = $elasticaResult->getData();
     }
     echo json_encode(array('hits' => $result, 'count' => $index->count($query)));
 }
Пример #10
0
 /**
  * @return Hackathon_ElasticgentoCore_Model_Resource_Collection
  */
 protected function _renderFiltersBefore()
 {
     //apply category filters
     if (true === isset($this->_productLimitationFilters['category_id']) && (int) $this->_productLimitationFilters['category_id'] > 0) {
         //check if category is anchor
         if (false === isset($this->_productLimitationFilters['category_is_anchor'])) {
             $filter = new Elastica\Filter\BoolOr();
             $filterAnchors = new Elastica\Filter\Term();
             $filterAnchors->setTerm('anchors', $this->_productLimitationFilters['category_id']);
         }
         $filterCategory = new Elastica\Filter\Term();
         $filterCategory->setTerm('categories', $this->_productLimitationFilters['category_id']);
         if (false === isset($this->_productLimitationFilters['category_is_anchor'])) {
             $filter->addFilter($filterCategory);
             $filter->addFilter($filterAnchors);
             $filter->setName('category');
             $this->_queryAttributeFilters['category'] = $filter;
         } else {
             $filterCategory->setName('category');
             $this->_queryAttributeFilters['category'] = $filterCategory;
         }
     }
     //apply visibility filters
     if (true === isset($this->_productLimitationFilters['visibility'])) {
         if (true === is_array($this->_productLimitationFilters['visibility'])) {
             $visibilityFilters = new Elastica\Filter\BoolOr();
             foreach ($this->_productLimitationFilters['visibility'] as $visibility) {
                 $visibilityFilter = new Elastica\Filter\Term();
                 $visibilityFilter->setTerm('visibility', $visibility);
                 $visibilityFilters->addFilter($visibilityFilter);
             }
             $visibilityFilters->setName('visibility');
             $this->_queryAttributeFilters['visibility'] = $visibilityFilters;
         }
     }
     return parent::_renderFiltersBefore();
 }
Пример #11
0
 /**
  * @return \Elastica\Filter\AbstractFilter
  * @throws ErrorException
  */
 public function getElasticaFilter()
 {
     switch ($this->condition) {
         case self::CONDITION_EQ:
         case self::CONDITION_NOT_EQ:
             $filter = new \Elastica\Filter\Term();
             $filter->addParam($this->parameter, $this->value);
             break;
         case self::CONDITION_GTE:
             $filter = new \Elastica\Filter\Range();
             $filter->addField($this->parameter, ['gte' => $this->value]);
             break;
         case self::CONDITION_GT:
             $filter = new \Elastica\Filter\Range();
             $filter->addField($this->parameter, ['gt' => $this->value]);
             break;
         case self::CONDITION_LTE:
             $filter = new \Elastica\Filter\Range();
             $filter->addField($this->parameter, ['lte' => $this->value]);
             break;
         case self::CONDITION_LT:
             $filter = new \Elastica\Filter\Range();
             $filter->addField($this->parameter, ['lt' => $this->value]);
             break;
         case self::CONDITION_RANGE:
             $filter = new \Elastica\Filter\Range($this->parameter, $this->getRangeArgs());
             break;
         default:
             throw new ErrorException('Unknown aggregation type');
     }
     return $filter;
 }
 /**
  * Construct a favorites filter
  * @param object $moduleFilter
  * @return \Elastica\Filter\Term $moduleFilter
  */
 protected function constructMyFavoritesFilter($moduleFilter)
 {
     $ownerTermFilter = new \Elastica\Filter\Term();
     // same bug as team set id, looking into a fix in elastic search to allow -'s without tokenizing
     $ownerTermFilter->setTerm('user_favorites', $GLOBALS['current_user']->id);
     $moduleFilter->addMust($ownerTermFilter);
     return $moduleFilter;
 }
Пример #13
0
require_once '../vendor/autoload.php';
$param_key = array('message', 'aid', 'rid', 'date_from', 'date_to');
$param = array();
foreach ($param_key as $key) {
    if (isset($_GET[$key])) {
        $param[$key] = $_GET[$key];
    }
}
$client = new Elastica\Client(array('url' => 'http://localhost:9200/'));
$chat_type = $client->getIndex('cw')->getType('chat');
// create search parameter
$query = new Elastica\Query\MatchAll();
$filter = new Elastica\Filter\BoolAnd();
$filter_list = array();
if (!empty($param['message'])) {
    $chat_filter = new Elastica\Filter\Term();
    $chat_filter->setTerm('message', $param['message']);
    $filter_list[] = $chat_filter;
}
if (!empty($param['rid'])) {
    $rid_filter = new Elastica\Filter\Terms();
    $rid = explode(',', $param['rid']);
    $rid_filter->setTerms('rid', $rid);
    $filter_list[] = $rid_filter;
}
if (!empty($param['aid'])) {
    $aid_filter = new Elastica\Filter\Terms();
    $aid = explode(',', $param['aid']);
    $aid_filter->setTerms('aid', $aid);
    $filter_list[] = $aid_filter;
}
 public function search($queryString, $opts, $highlight)
 {
     $query = new \Elastica\Query();
     list($searchQuery, $highlights) = $this->parseQueryString($queryString, $opts);
     $query->setQuery($searchQuery);
     $language = new \Elastica\Facet\Terms('language');
     $language->setField('language');
     $language->setSize(500);
     $query->addFacet($language);
     $group = new \Elastica\Facet\Terms('group');
     $group->setField('group');
     // Would like to prioritize the top level groups and not show subgroups
     // if the top group has only few hits, but that doesn't seem to be possile.
     $group->setSize(500);
     $query->addFacet($group);
     $query->setSize($opts['limit']);
     $query->setFrom($opts['offset']);
     // BoolAnd filters are executed in sequence per document. Bool filters with
     // multiple must clauses are executed by converting each filter into a bit
     // field then anding them together. The latter is normally faster if either
     // of the subfilters are reused. May not make a difference in this context.
     $filters = new \Elastica\Filter\Bool();
     $language = $opts['language'];
     if ($language !== '') {
         $languageFilter = new \Elastica\Filter\Term();
         $languageFilter->setTerm('language', $language);
         $filters->addMust($languageFilter);
     }
     $group = $opts['group'];
     if ($group !== '') {
         $groupFilter = new \Elastica\Filter\Term();
         $groupFilter->setTerm('group', $group);
         $filters->addMust($groupFilter);
     }
     // Check that we have at least one filter to avoid invalid query errors.
     if ($language !== '' || $group !== '') {
         $query->setPostFilter($filters);
     }
     list($pre, $post) = $highlight;
     $query->setHighlight(array('pre_tags' => array($pre), 'post_tags' => array($post), 'fields' => $highlights));
     try {
         return $this->getType()->getIndex()->search($query);
     } catch (\Elastica\Exception\ExceptionInterface $e) {
         throw new TTMServerException($e->getMessage());
     }
 }