public function action_index() { $this->view = new View_Search(); if ($this->request->query('query') !== NULL) { $query = $this->request->query('query'); $queryString = new \Elastica\Query\QueryString(); $queryString->setDefaultOperator('AND'); $queryString->setQuery($query); $elasticaQuery = new \Elastica\Query(); $elasticaQuery->setQuery($queryString); $resultSet = ElasticSearch::instance()->search($elasticaQuery); $results = $resultSet->getResults(); /** @var Kostache $renderer */ $renderer = Kostache::factory(); $out = array(); foreach ($results as $result) { // Attempt to create the avatar instance. try { $refl = new ReflectionClass('View_Search_' . ucfirst($result->getType())); $view = $refl->newInstance(); $view->data = $result->getData(); $out[] = $renderer->render($view); } catch (ReflectionException $ex) { Kohana::$log->add(LOG::ERROR, 'No search view class found for search type ":type".', array(':type' => $result->getType())); } } $this->view->query = $query; $this->view->results = $out; } }
<?php ini_set("display_errors", true); require_once __DIR__ . '/../vendor/autoload.php'; $client = new \Elastica\Client(); $search = new Elastica\Search($client); $search->addIndex('comicbook')->addType('superhero'); $query = new Elastica\Query(); $query->setSize(10)->setSort(['name' => 'asc']); $searchText = "Kent"; $stringQuery = new Elastica\Query\QueryString($searchText); $query->setQuery($stringQuery); $query->setHighlight(array('pre_tags' => array('<strong>'), 'post_tags' => array('</strong>'), 'fields' => array('name' => array('force_source' => true), 'summary' => array('force_source' => true)))); $search->setQuery($query); $resultSet = $search->search(); echo 'Search "' . $searchText . '"<br />' . PHP_EOL; echo 'Founded ' . $resultSet->getTotalHits() . ' records in ' . $resultSet->getTotalTime() . 'ms<br /><br />' . PHP_EOL; foreach ($resultSet as $result) { $data = $result->getData(); foreach ($result->getHighlights() as $key => $value) { $data[$key] = join(PHP_EOL, $value); } echo $data['name'] . ' - ' . $data['summary'] . "<br /><br />" . PHP_EOL; }
public function newsAction(Request $request) { $request = $this->getRequest(); $pageOffset = 0; if ($request->query->get('p')) { $page = $request->query->get('p'); $pageOffset = ($page - 1) * 6; } $finder = $this->container->get('fos_elastica.finder.search.posts'); $boolQuery = new \Elastica\Query\BoolQuery(); if ($request->query->get('q')) { $search = $request->query->get('q'); $fieldQuery = new \Elastica\Query\Match(); $fieldQuery->setFieldQuery('allField', $search); $fieldQuery->setFieldOperator('allField', 'AND'); $fieldQuery->setFieldMinimumShouldMatch('allField', '80%'); $fieldQuery->setFieldAnalyzer('allField', 'custom_search_analyzer'); $boolQuery->addMust($fieldQuery); } else { $fieldQuery = new \Elastica\Query\MatchAll(); } $query = new \Elastica\Query(); $query->setQuery($boolQuery); $query->setSize(1000); $totalpages = ceil(count($finder->find($query)) / 6); $query->setSize(6); $query->setFrom($pageOffset); $posts = $finder->find($query); return $this->render('TeamIndexBundle:News:news.html.twig', array('posts' => $posts, 'totalpages' => $totalpages)); }
public function articlelistAction(Request $request) { $em = $this->getDoctrine()->getManager(); $searchTerm = $request->query->get('q'); $page = 0; $pageOffset = 0; if ($request->query->get('p')) { $page = $request->query->get('p'); $pageOffset = ($page - 1) * 12; } $finder = $this->container->get('fos_elastica.finder.search.article'); $boolQuery = new \Elastica\Query\BoolQuery(); $articles = ""; $totalpages = 0; if ($request->query->get('q') != NULL) { $searchTerm = $request->query->get('q'); $fieldQuery = new \Elastica\Query\Match(); $fieldQuery->setFieldQuery('allField', $searchTerm); $fieldQuery->setFieldOperator('allField', 'AND'); $fieldQuery->setFieldMinimumShouldMatch('allField', '80%'); $fieldQuery->setFieldAnalyzer('allField', 'custom_search_analyzer'); $boolQuery->addMust($fieldQuery); $query = new \Elastica\Query(); $query->setQuery($boolQuery); $query->setSize(10000); $articleCatgeories = $finder->find($query); $totalpages = ceil(count($finder->find($query)) / 12); $query->setSize(12); $query->setFrom($pageOffset); $articles = $finder->find($query); } return $this->render('OrthAdminBundle:Articles:articlelist.html.twig', array('totalpages' => $totalpages, 'articles' => $articles)); }
public function searchActiveCategories() { $query = new \Elastica\Query(new \Elastica\Query\MatchAll()); $publishedQuery = new \Elastica\Query(new \Elastica\Query\Term(array('published' => true))); $hasChildQuery = new \Elastica\Query\HasChild($publishedQuery); $hasChildQuery->setType('article'); $query->setQuery($hasChildQuery); return $this->find($query); }
/** * @param Hackathon_ElasticgentoCore_Model_Resource_Client $searchAdapter * @param string $queryText * @param Mage_CatalogSearch_Model_Query $query * * @return Elastica\ResultSet */ protected function fetchSearchResultFromElasticSearch($searchAdapter, $queryText, $query) { $elasticQuery = new Elastica\Query(); $queryFuzzyLikeThis = new \Elastica\Query\FuzzyLikeThis(); $queryFuzzyLikeThis->addFields(Mage::helper('elasticgento_catalogsearch/data')->getSearchableElasticSearchFieldNames()); $queryFuzzyLikeThis->setLikeText($queryText); $elasticQuery->setQuery($queryFuzzyLikeThis); $returnFields = ['entity_id', 'name']; $elasticQuery->setFields($returnFields); return $searchAdapter->getIndex($query->getStoreId())->search($elasticQuery); }
public function getArticles($user, $searchTerm, $page, $pageOffset, $category, $colors, $finder) { $boolQuery = new \Elastica\Query\BoolQuery(); if ($category != NULL) { $categoryQuery = new \Elastica\Query\Terms(); $categoryQuery->setTerms('custdata.customCatRef', array($category)); $boolQuery->addMust($categoryQuery); } if ($searchTerm) { $fieldQuery = new \Elastica\Query\Match(); $fieldQuery->setFieldQuery('customerRef', $user->getCustomerRef()); $boolQuery->addMust($fieldQuery); $fieldQuery = new \Elastica\Query\Match(); $fieldQuery->setFieldQuery('allField', $searchTerm); $fieldQuery->setFieldOperator('allField', 'AND'); $fieldQuery->setFieldMinimumShouldMatch('allField', '70%'); $fieldQuery->setFieldFuzziness('allField', '0.8'); $fieldQuery->setFieldAnalyzer('allField', 'custom_search_analyzer'); $boolQuery->addMust($fieldQuery); } else { $fieldQuery = new \Elastica\Query\MatchAll(); $boolQuery->addMust($fieldQuery); } $fieldQuery = new \Elastica\Query\Nested(); $fieldQuery->setPath('custdata.custcat.perm'); $boolNested = new \Elastica\Query\BoolQuery(); $fieldNested = new \Elastica\Query\Match(); $fieldNested->setField('custdata.custcat.perm.permStatus', 1); $boolNested->addMust($fieldNested); $fieldNested = new \Elastica\Query\Match(); $fieldNested->setField('custdata.custcat.perm.userRef', $user->getId()); $boolNested->addMust($fieldNested); $fieldQuery->setQuery($boolNested); $boolQuery->addMust($fieldQuery); if ($colors != NULL) { $colorQuery = new \Elastica\Query\Terms(); $colorQuery->setTerms('variants.variantvalues.otherTerms', $colors); $colorNested = new \Elastica\Query\Nested('variants'); $colorNested->setPath('variants.variantvalues'); $colorNested->setQuery($colorQuery); $boolQuery->addMust($colorNested); } $query = new \Elastica\Query(); $query->setQuery($boolQuery); $query->setSize(12); $query->setFrom($pageOffset); $articles = $finder->find($query); $result = array("articles" => $articles, "rQuery" => $query); return $result; }
/** * @Route("/app/users/list", name="app_users_list") */ public function listUsersAction() { $finder = $this->container->get('fos_elastica.finder.app.user'); $query = new \Elastica\Query(); $matchAll = new \Elastica\Query\MatchAll(); $query->setQuery($matchAll); $query->setSize(1000); $results = $finder->findHybrid($query); $elasticaResults = []; foreach ($results as $result) { $elasticaResults[] = [$result->getResult()->getId() => $result->getResult()->getSource()]; } return new Response(json_encode($elasticaResults)); }
public function testTypeInsideHasChildSearch() { $index = $this->prepareSearchData(); $f = new \Elastica\Query\Match(); $f->setField('alt.name', 'testname'); $query = new HasChild($f, 'child'); $searchQuery = new \Elastica\Query(); $searchQuery->setQuery($query); $searchResults = $index->search($searchQuery); $this->assertEquals(1, $searchResults->count()); $result = $searchResults->current()->getData(); $expected = array('id' => 'parent2', 'user' => 'parent2', 'email' => '*****@*****.**'); $this->assertEquals($expected, $result); }
/** * * @return bool */ protected function getTrendExtensions() { $es = $this->app->container->get('elastica.client'); $elasticaQueryString = new \Elastica\Query\QueryString(); $elasticaQueryString->setQuery('*'); $elasticaQuery = new \Elastica\Query(); $elasticaQuery->setQuery($elasticaQueryString); $elasticaQuery->setSort(["stars" => 'desc']); $elasticaIndex = $es->getIndex('packages'); $results = $elasticaIndex->search($elasticaQuery); $hits = []; foreach ($results->getResults() as $result) { $hits[] = $result->getHit(); } return $hits; }
public function searchindexAction($searchTerm) { $client = new \Elastica\Client(array('host' => '192.168.15.102', 'port' => 9200)); $index = $client->getIndex('coolcities'); $multiMatchQuery = new \Elastica\Query\MultiMatch(); $multiMatchQuery->setQuery($searchTerm); $multiMatchQuery->setFields(array('title', 'description', 'city^3')); // Create the actual search object with some data. $esQuery = new \Elastica\Query(); $esQuery->setQuery($multiMatchQuery); //Search on the index. $results = $index->search($esQuery); foreach ($results as $result) { echo "<pre>"; print_r($result); echo "<pre>"; } die; return new Response('index search'); }
public function AetCommunicationSearch($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('title', $searchText); //$fieldQuery->setFieldParam('title', 'analyzer', 'custom_search_analyzer'); $boolQuery->addShould($fieldQuery); $field1Query = new \Elastica\Query\Match(); $field1Query->setFieldQuery('shortDesc', $searchText); $boolQuery->addShould($field1Query); $field1Query = new \Elastica\Query\Match(); $field1Query->setFieldQuery('body', $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); }
/** * @param $searchTerm * @param null $appliedFilters * @param $configuration * @param $preSearchTaxonFilter * @param $types * * @return mixed */ public function compileElasticSearchStringQuery($searchTerm, $appliedFilters = null, $configuration, $preSearchTaxonFilter, $types = null) { $elasticaQuery = new \Elastica\Query(); $boolFilter = new \Elastica\Filter\BoolFilter(); $query = new \Elastica\Query\QueryString($searchTerm); if (!empty($types)) { foreach ($types as $type) { $typeFilter = new \Elastica\Filter\Type($type); $boolFilter->addMust($typeFilter); } $elasticaQuery->setPostFilter($boolFilter); } if ($channel = $this->channelContext->getChannel()) { $channelFilter = new \Elastica\Filter\Terms(); $channelFilter->setTerms('channels', array((string) $channel)); $boolFilter->addMust($channelFilter); $elasticaQuery->setPostFilter($boolFilter); } // this is currently the only pre search filter and it's a taxon // this should be abstracted out if other types of pre search filters are desired if ('all' !== $preSearchTaxonFilter) { $query = new \Elastica\Query\Filtered(); $query->setQuery(new \Elastica\Query\QueryString($searchTerm)); $taxonFromRequestFilter = new \Elastica\Filter\Terms(); $taxonFromRequestFilter->setTerms('taxons', array($preSearchTaxonFilter)); $boolFilter->addMust($taxonFromRequestFilter); $elasticaQuery->setPostFilter($boolFilter); } $elasticaQuery->setQuery($query); return $this->compileElasticsearchQuery($elasticaQuery, $appliedFilters, $configuration); }
/** * 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; }
public function getBestImg($searchTerm, $articleRef, $colors, $finder) { $boolQuery = new \Elastica\Query\BoolQuery(); if ($searchTerm) { $fieldQuery = new \Elastica\Query\Match(); $fieldQuery->setFieldQuery('desc1', $searchTerm); $fieldQuery->setFieldOperator('desc1', 'OR'); $fieldQuery->setFieldMinimumShouldMatch('desc1', '80%'); $fieldQuery->setFieldAnalyzer('desc1', 'custom_search_analyzer'); $boolQuery->addShould($fieldQuery); $fieldQuery = new \Elastica\Query\Match(); $fieldQuery->setFieldQuery('desc2', $searchTerm); $fieldQuery->setFieldOperator('desc2', 'OR'); $fieldQuery->setFieldMinimumShouldMatch('desc2', '80%'); $fieldQuery->setFieldAnalyzer('desc2', 'custom_search_analyzer'); $varTerms = explode(" ", $searchTerm); $boolQuery->addShould($fieldQuery); $colorQuery = new \Elastica\Query\Terms(); $colorQuery->setTerms('variantvalues.otherTerms', $varTerms); $colorNested = new \Elastica\Query\Nested('variantvalues'); $colorNested->setPath('variantvalues'); $colorNested->setQuery($colorQuery); $boolQuery->addShould($colorNested); if ($colors != NULL) { $fieldQuery = new \Elastica\Query\Terms(); $fieldQuery->setTerms('otherTerms', $colors); $boolQuery->addShould($fieldQuery); } } $articleRefQuery = new \Elastica\Query\Terms(); $articleRefQuery->setTerms('articleRef', array($articleRef)); $boolQuery->addMust($articleRefQuery); if ($colors != NULL) { $colorQuery = new \Elastica\Query\Terms(); $colorQuery->setTerms('variantvalues.otherTerms', $colors); $colorNested = new \Elastica\Query\Nested('variantvalues'); $colorNested->setPath('variantvalues'); $colorNested->setQuery($colorQuery); $boolQuery->addMust($colorNested); } $query = new \Elastica\Query(); $query->setQuery($boolQuery); $query->setSize(12); $articleVar = $finder->find($query); return $articleVar; }
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(); } } }
public function searchAction(Request $request) { $em = $this->getDoctrine()->getManager(); $username = $request->query->get('oci_username'); $password = $request->query->get('oci_password'); $hookurl = $request->query->get('hookurl'); $response = new Response(); $response->headers->clearCookie('OCIHOOK'); $response->headers->clearCookie('OrthCookie'); $response->sendHeaders(); $response->send(); $response->headers->setCookie(new Cookie('OCIHOOK', $hookurl)); $cookieValue = uniqid(); $response->headers->setCookie(new Cookie('OrthCookie', uniqid())); $response->sendHeaders(); $response->send(); $query = $em->createQuery("SELECT u FROM Orth\\IndexBundle\\Entity\\Users u WHERE u.email = :username"); $query->setParameter('username', $username); $user = $query->getOneOrNullResult(); if ($user) { // Get the encoder for the users password $encoder_service = $this->get('security.encoder_factory'); $encoder = $encoder_service->getEncoder($user); // Note the difference if ($encoder->isPasswordValid($user->getPassword(), $password, '$2a$12$uWepESKverBsrLAuOPY')) { // Get profile list } else { dump('fail1'); exit; } } else { dump('fail'); exit; } $token = new UsernamePasswordToken($user, null, "default", $user->getRoles()); $this->get("security.context")->setToken($token); //now the user is logged in //now dispatch the login event $request = $this->get("request"); $event = new InteractiveLoginEvent($request, $token); $this->get("event_dispatcher")->dispatch("security.interactive_login", $event); if ($request->query->get('FUNCTION') == NULL) { return $this->redirectToRoute('orth_index_homepage', array(), 301); } $searchTerm = $request->query->get('SEARCHSTRING'); $page = 0; $pageOffset = 0; $catId = $request->query->get('cid'); $finder = $this->container->get('fos_elastica.finder.search.article'); $boolQuery = new \Elastica\Query\BoolQuery(); if ($request->query->get('c') != NULL and $request->query->get('SEARCHSTRING') == NULL) { $catid = $request->query->get('c'); $categoryArray = [$request->query->get('c')]; $rootCategories = $em->getRepository('OrthIndexBundle:Categories')->findBy(array('parentId' => $catid)); foreach ($rootCategories as $childCategory) { $childCategories = $em->getRepository('OrthIndexBundle:Categories')->findBy(array('parentId' => $childCategory->getId())); $categoryArray[] = $childCategory->getId(); foreach ($childCategories as $grandchildCategory) { $categoryArray[] = $grandchildCategory->getId(); } } $categoryQuery = new \Elastica\Query\Terms(); $categoryQuery->setTerms('catRef', $categoryArray); $boolQuery->addMust($categoryQuery); } elseif ($request->query->get('c') != NULL) { $catid = $request->query->get('c'); $categoryQuery = new \Elastica\Query\Terms(); $categoryQuery->setTerms('catRef', array($catid)); $boolQuery->addMust($categoryQuery); } if ($request->query->get('SEARCHSTRING')) { $fieldQuery = new \Elastica\Query\Match(); $fieldQuery->setFieldQuery('allField', $searchTerm); $fieldQuery->setFieldOperator('allField', 'AND'); $fieldQuery->setFieldMinimumShouldMatch('allField', '80%'); $fieldQuery->setFieldAnalyzer('allField', 'custom_search_analyzer'); $boolQuery->addMust($fieldQuery); } $query = new \Elastica\Query(); $query->setQuery($boolQuery); $totalpages = ceil(count($finder->find($query)) / 12); $query->setSize(100); $query->setFrom($pageOffset); $articles = $finder->find($query); foreach ($articles as $article) { $variants = $article->getVariants(); foreach ($variants as $variant) { $price = $em->getRepository('OrthIndexBundle:ArticleSuppliers')->getCustomPrice(array('id' => $variant), $user); $category = $em->getRepository('OrthIndexBundle:Categories')->getRootCategory($article->getCategory()->getId()); $attribute = ""; foreach ($variant->getVariantvalues() as $values) { $attribute .= " " . $values->getAttrname()->getAttributeName() . " " . $values->getAttributeValue() . "" . $values->getAttributeUnit(); } if ($variant->getVariantvalues()) { if ($article->getImages()[0]) { $image = $article->getImages()[0]->getPicName(); } else { $image = 'nopicture_all.jpg'; } $result[] = array('shortName' => $article->getShortName() . "" . $attribute, 'articleNumber' => $variant->getSupplierArticleNumber(), 'price' => $price, 'category' => $category, 'image' => $image); } } } return $this->render('OrthIndexBundle:Oci:ocioutput.html.twig', array('results' => $result, 'page' => $page, 'totalpages' => $totalpages, 'hookurl' => $hookurl)); }
/** * To respect the design, 3 searches will be executed: * 1st: retrieves the main facet (Text / Media / Portfolio / Users / Group) and the count for each of them * 2nd: - retrieves the results of the first non empty facet term for display in the tab * - retrieves the secondary facet to enable / disable the filter items * 3nd: - retrieves the results with all filters applied * @param unknown $query_string * @param unknown $limit * @param unknown $offset * @param unknown $options * @param unknown $mainfacetterm * @param unknown $USER * @return multitype:number boolean unknown Ambigous <boolean, NULL> Ambigous <boolean, unknown> multitype:multitype:string number Ambigous <string, unknown> |multitype:multitype: */ public static function search($query_string, $limit, $offset, $options, $mainfacetterm, $USER) { $result = array('count' => 0, 'limit' => $limit, 'offset' => $offset, 'data' => false, 'selected' => isset($mainfacetterm) && strlen($mainfacetterm) > 0 ? $mainfacetterm : false, 'totalresults' => 0, 'facets' => array(array('term' => "Text", 'count' => 0, 'display' => "Text"), array('term' => "Media", 'count' => 0, 'display' => "Media"), array('term' => "Portfolio", 'count' => 0, 'display' => "Portfolio"), array('term' => "User", 'count' => 0, 'display' => "Users"), array('term' => "Group", 'count' => 0, 'display' => "Group")), 'content-filter' => array(array('term' => "all", 'count' => 0, 'display' => "All"), array('term' => "Audio", 'count' => 0, 'display' => "Audio"), array('term' => "Comment", 'count' => 0, 'display' => "Comment"), array('term' => "Document", 'count' => 0, 'display' => "Document"), array('term' => "Folder", 'count' => 0, 'display' => "Folder"), array('term' => "Forum", 'count' => 0, 'display' => "Forum"), array('term' => "Forumpost", 'count' => 0, 'display' => "Forum post"), array('term' => "Image", 'count' => 0, 'display' => "Image"), array('term' => "Journal", 'count' => 0, 'display' => "Journal"), array('term' => "Journalentry", 'count' => 0, 'display' => "Journal entry"), array('term' => "Note", 'count' => 0, 'display' => "Note"), array('term' => "Plan", 'count' => 0, 'display' => "Plan"), array('term' => "Profile", 'count' => 0, 'display' => "Profile"), array('term' => "Resume", 'count' => 0, 'display' => "Résumé"), array('term' => "Video", 'count' => 0, 'display' => "Video"), array('term' => "Wallpost", 'count' => 0, 'display' => "Wall post"), array('term' => "Collection", 'count' => 0, 'display' => "Collection"), array('term' => "Page", 'count' => 0, 'display' => "Page")), 'content-filter-selected' => isset($options['secfacetterm']) && strlen($options['secfacetterm']) > 0 ? $options['secfacetterm'] : 'all', 'owner-filter' => array(array('term' => "all", 'count' => 0, 'display' => "All"), array('term' => "me", 'count' => 0, 'display' => "Me"), array('term' => "others", 'count' => 0, 'display' => "Others")), 'owner-filter-selected' => isset($options['owner']) && strlen($options['owner']) > 0 ? $options['owner'] : 'all', 'tagsonly' => isset($options['tagsonly']) && $options['tagsonly'] == true ? true : Null, 'sort' => isset($options['sort']) && strlen($options['sort']) > 0 ? $options['sort'] : 'score', 'license' => isset($options['license']) && strlen($options['license']) > 0 ? $options['license'] : 'all'); if (strlen($query_string) <= 0) { return $result; } // 1- Get main facet // ------------------------------------------------------------------------------------------ $records = array(); $elasticaClient = PluginSearchElasticsearch::make_client(); $elasticaIndex = $elasticaClient->getIndex(get_config_plugin('search', 'elasticsearch', 'indexname')); $elasticaQueryString = new \Elastica\Query\QueryString(); $elasticaAnalyzer = get_config_plugin('search', 'elasticsearch', 'analyzer'); $elasticaQueryString->setAnalyzer($elasticaAnalyzer); $elasticaQueryString->setDefaultOperator('AND'); $elasticaQueryString->setQuery($query_string); // if tags only => set fields to tags if ($result['tagsonly'] === true) { $elasticaQueryString->setFields(array('tags')); } // Create the $elasticaQuery object $elasticaQuery = new \Elastica\Query(); $elasticaQuery->setFrom($offset); $elasticaQuery->setLimit($limit); $elasticaQuery->setQuery($elasticaQueryString); $elasticaFilterAnd = new \Elastica\Filter\BoolAnd(); // Apply ACL filters $elasticaFilterACL = new ElasticsearchFilterAcl($USER); $elasticaFilterAnd->addFilter($elasticaFilterACL); $elasticaQuery->setFilter($elasticaFilterAnd); // Define a new facet: mainFacetTerm - WARNING: don't forget to apply the same filter to the facet $elasticaFacet = new \Elastica\Facet\Terms('mainFacetTerm'); $elasticaFacet->setField('mainfacetterm'); $elasticaFacet->setOrder('count'); $elasticaFacet->setFilter($elasticaFilterAnd); $elasticaQuery->addFacet($elasticaFacet); $elasticaResultSet = $elasticaIndex->search($elasticaQuery); $result['totalresults'] = $elasticaResultSet->getTotalHits(); $elasticaFacets = $elasticaResultSet->getFacets(); $facets = self::process_facets($elasticaFacets['mainFacetTerm']['terms']); if (count($facets) == 0) { return $result; } array_walk($result['facets'], 'self::process_tabs', $facets); if ($result['selected'] === false || $facets[$result['selected']] == 0) { $result['selected'] = self::get_selected_facet($result['facets']); } // 2- Retrieve results of selected facet // ------------------------------------------------------------------------------------------ $elasticaFilterType = new \Elastica\Filter\Term(array('mainfacetterm' => $result['selected'])); $elasticaFilterAnd->addFilter($elasticaFilterType); $elasticaQuery->setFilter($elasticaFilterAnd); // Define a new facet: secFacetTerm - WARNING: don't forget to apply the same filter to the facet $elasticaFacet = new \Elastica\Facet\Terms('secFacetTerm'); $elasticaFacet->setField('secfacetterm'); $elasticaFacet->setOrder('count'); $elasticaFacet->setFilter($elasticaFilterAnd); $elasticaQuery->addFacet($elasticaFacet); // Sorting // Sorting is defined on a per field level, so we must make sure the field exists in the mapping $sort = explode('_', $result['sort']); if ($sort[0] == 'score') { $sort[0] = '_score'; } // set the second column to sort by the score (to break any 'ties'). $elasticaQuery->setSort(array(array($sort[0] => array('order' => isset($sort[1]) ? $sort[1] : 'desc')), array('_score' => array('order' => 'desc')))); $elasticaResultSet = $elasticaIndex->search($elasticaQuery); $result['count'] = $elasticaResultSet->getTotalHits(); $elasticaFacets = $elasticaResultSet->getFacets(); $facets = $elasticaFacets['secFacetTerm']['terms']; $facets = self::process_facets($elasticaFacets['secFacetTerm']['terms']); array_walk($result['content-filter'], 'self::process_tabs', $facets); // set the count of "all" to the total hits $result['content-filter'][0]['count'] = $result['count']; // 3- Apply filters and retrieve final results // ------------------------------------------------------------------------------------------ // Apply Content filter if different from "all" if ($result['content-filter-selected'] != 'all') { $elasticaFilterContent = new \Elastica\Filter\Term(array('secfacetterm' => $result['content-filter-selected'])); $elasticaFilterAnd->addFilter($elasticaFilterContent); } // Apply Owner filter if different from "all" if ($result['owner-filter-selected'] != 'all') { $uid = $USER->get('id'); $elasticaFilterOwner = new \Elastica\Filter\Term(array('owner' => $uid)); if ($result['owner-filter-selected'] == 'others') { $elasticaFilterOwner = new \Elastica\Filter\BoolNot($elasticaFilterOwner); } $elasticaFilterAnd->addFilter($elasticaFilterOwner); } // Apply license filter if different from "all" if ($result['license'] != 'all') { $elasticaFilterLicense = new \Elastica\Filter\Term(array('license' => $result['license'])); $elasticaFilterAnd->addFilter($elasticaFilterLicense); } $elasticaQuery->setFilter($elasticaFilterAnd); $elasticaResultSet = $elasticaIndex->search($elasticaQuery); $elasticaResults = $elasticaResultSet->getResults(); $result['count'] = $elasticaResultSet->getTotalHits(); foreach ($elasticaResults as $elasticaResult) { $tmp = array(); $tmp['type'] = $elasticaResult->getType(); $ES_class = 'ElasticsearchType_' . $tmp['type']; $tmp = $tmp + $elasticaResult->getData(); // Get all the data from the DB table $dbrec = $ES_class::getRecordDataById($tmp['type'], $tmp['id']); if ($dbrec) { $tmp['db'] = $dbrec; $tmp['db']->deleted = false; } else { // If the record has been deleted, so just pass the cached data // from the search result. Let the template decide how to handle // it. $tmp['db'] = (object) $tmp; $tmp['db']->deleted = true; } $records[] = $tmp; } $result['data'] = $records; return $result; }
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()); } }
public function catsucheAction($catid, Request $request) { $em = $this->getDoctrine()->getManager(); $mainCat = []; $page = 0; $pageOffset = 0; if ($request->query->get('p')) { $page = $request->query->get('p'); $pageOffset = ($page - 1) * 12; } $finder = $this->container->get('fos_elastica.finder.search.articles'); $boolQuery = new \Elastica\Query\BoolQuery(); if ($request->query->get('q') !== NULL) { $searchTerm = $request->query->get('q'); $fieldQuery = new \Elastica\Query\MultiMatch(); $fieldQuery->setFields(array('shortName', 'shortDescription', 'longDescription')); $fieldQuery->setAnalyzer('custom_search_analyzer'); $fieldQuery->setOperator('AND'); $fieldQuery->setQuery($searchTerm); $boolQuery->addMust($fieldQuery); } $categoryQuery = new \Elastica\Query\Terms(); $categoryQuery->setTerms('catRef', array($catid)); $boolQuery->addMust($categoryQuery); $query = new \Elastica\Query(); $query->setQuery($boolQuery); $query->setSize(10000000); $totalpages = ceil(count($finder->find($query)) / 12); $query->setSize(12); $query->setFrom($pageOffset); $articles = $finder->find($query); return $this->render('OrthIndexBundle:Shop:kategorien.html.twig', array('articles' => $articles, 'page' => $page, 'totalpages' => $totalpages, 'categories' => $mainCat)); }
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); }
/** * @SWG\Api( * path="/posts/:id", * @SWG\Operation( * method="GET", * summary="Gets a post", * nickname="posts_get" * ) * ) */ function getById($id) { $result = array(); $body = $this->getBodyAsArray(); $required_parameters = array(); $optional_parameters = array('post_type'); $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); } $q = new \Elastica\Query\Term(array("_id" => $id)); $boolean->addMust($q); $query->setQuery($boolean); $query->setSize(1); $elasticaResultSet = $index->search($query); $elasticaResults = $elasticaResultSet->getResults(); foreach ($elasticaResults as $elasticaResult) { $result[] = $elasticaResult->getData(); } echo json_encode($result); }
/** * Main method to make a search */ public function search() { $this->getSearchFields(); $word = JRequest::getString('searchword', null, 'get'); $offset = JRequest::getInt('start', 0, 'get'); $limit = JRequest::getInt('limit', 10, 'get'); if ($limit == 0) { // no limit $limit = 10000; } $this->getSearchAreas(); $elasticaQueryString = new \Elastica\Query\QueryString(); // Log search word only on the first page if ($offset == 0) { SearchHelper::logSearch($word); } // Convert accents $word = htmlentities($word, ENT_NOQUOTES, 'utf-8'); $word = preg_replace('#\\&([A-za-z])(?:uml|circ|tilde|acute|grave|cedil|ring)\\;#', '\\1', $word); $word = preg_replace('#\\&([A-za-z]{2})(?:lig)\\;#', '\\1', $word); $word = preg_replace('#\\&[^;]+\\;#', '', $word); // Check if there are quotes ( for exact search ) $exactSearch = false; if (strlen($word) > 1 && $word[0] == '"' && $word[strlen($word) - 1] == '"') { $exactSearch = true; $word = substr($word, 1, strlen($word) - 2); // Remove external " } $word = Elastica\Util::replaceBooleanWordsAndEscapeTerm($word); // Escape ElasticSearch specials char if ($exactSearch) { $word = '"' . $word . '"'; } if ($word == "") { $word = "*"; } $elasticaQueryString->setQuery($word); //Create the actual search object with some data. $elasticaQuery = new Elastica\Query(); $elasticaQuery->setQuery($elasticaQueryString); if (ElasticSearchConfig::getHighLigthEnable()) { $fields = $this->getHighlightFields(); $hlfields = array(); foreach ($fields as $field) { foreach ($field as $highlight) { $hlfields[] = array($highlight => array('fragment_size' => 1000, 'number_of_fragments' => 1)); } } $highlightFields = array('pre_tags' => array(ElasticSearchConfig::getHighLigthPre()), 'post_tags' => array(ElasticSearchConfig::getHighLigthPost()), "order" => "score", 'fields' => $hlfields); $elasticaQuery->setHighlight($highlightFields); } // Set offset and limit for pagination $elasticaQuery->setFrom($offset); $elasticaQuery->setLimit($limit); //Create a filter for _type $elasticaFilterype = $this->createFilterType($this->areas); // Add filter to the search object. $elasticaQuery->setFilter($elasticaFilterype); //Search on the index. $elasticaResultSet = $this->elasticaIndex->search($elasticaQuery); $this->results = $elasticaResultSet->getResults(); $this->totalHits = $elasticaResultSet->getTotalHits(); }
public function searchSample($criteria, $dataset, $sorts = array(), $operator = 'OR') { /*if($limit <= 0) { $limit = Yii::app()->params['es_search']['limits']['default']; }*/ $keyword = $criteria['keyword']; $eQueryString = new \Elastica\Query\QueryString(); $eQueryString->setDefaultOperator($operator); $eQueryString->setQuery($keyword); $eQuery = new \Elastica\Query(); $eQuery->setQuery($eQueryString); //$eQuery->setFrom($offset); //$eQuery->setLimit($limit); $filterAnd = new \Elastica\Filter\BoolAnd(); if (isset($criteria['common_name'])) { $filterAnd->addFilter($this->newTerms('common_name', $criteria['common_name'])); } if (is_array($dataset) && !empty($dataset)) { $ids = new \Elastica\Filter\Ids(); $ids->setIds($dataset); $filterAnd->addFilter($ids); } $arrayAnd = $filterAnd; $arrayAnd = $arrayAnd->toArray(); if (count($arrayAnd['and']) > 0) { $eQuery->setPostFilter($filterAnd); } $sortList = array_merge(array('_score' => array('order' => 'desc')), $sorts); $eQuery->setSort($sortList); $index = Yii::app()->elastic->client->getIndex('gigadb'); $type = $index->getType('sample'); $eResultSet = $type->search($eQuery); $results = $eResultSet->getResults(); $total = $eResultSet->getTotalHits(); $data = array(); foreach ($results as $result) { if ($result) { $data[] = $result->getData(); } } $re = array('data' => $data, 'total' => $total); //Yii::log(print_r($re, true), 'debug'); return $re; }
/** * Get views linked to a particular artefact, applying ACL * This is used to display the list of views in an artefact result, because it's faster to retrieve the info * from Elastic search that running the SQL query. */ public static function views_by_artefact_acl_filter($views = array()) { global $USER; $ret = array(); $elasticaClient = PluginSearchElasticsearch::make_client(); $elasticaIndex = $elasticaClient->getIndex(get_config_plugin('search', 'elasticsearch', 'indexname')); $elasticaQuery = new \Elastica\Query(); // check user access to the views $elasticaFilterAnd = new \Elastica\Filter\BoolAnd(); $elasticaFilterType = new \Elastica\Filter\Term(array('_type' => 'view')); $elasticaFilterAnd->addFilter($elasticaFilterType); $elasticaFilterIds = new \Elastica\Filter\Terms('id', array_keys($views)); $elasticaFilterAnd->addFilter($elasticaFilterIds); // Apply ACL filters $elasticaFilterACL = new ElasticsearchFilterAcl($USER); $elasticaFilterAnd->addFilter($elasticaFilterACL); $elasticaFilteredQuery = new \Elastica\Query\Filtered(null, $elasticaFilterAnd); $elasticaQuery->setQuery($elasticaFilteredQuery); $elasticaResultSet = $elasticaIndex->search($elasticaQuery); $elasticaResults = $elasticaResultSet->getResults(); foreach ($elasticaResults as $elasticaResult) { $data = $elasticaResult->getData(); $ret[$data['id']] = $views[$data['id']]; } return $ret; }