/** * * MyItems filter * @see FacetFilter */ protected function getBoolFilter() { $docOwner = new \Elastica\Filter\Term(array('doc_owner' => $this->userId)); $filter = new \Elastica\Filter\Bool(); $filter->addShould($docOwner); return $filter; }
/** * generic method for to do a filter * @return bool|\Elastica\Filter\Bool */ public function getFilter() { if (!empty($this->getValue())) { $filter = new \Elastica\Filter\Bool(); $filter->addMust(new \Elastica\Filter\Terms($this->getField(), [$this->getValue()])); return $filter; } return false; }
/** * * @see FacetInterface::getFacet */ public function getFacet($fieldName, \Elastica\Filter\AbstractFilter $mainFilter) { // encapsulate mainFilter and the facet filter $master = new \Elastica\Filter\Bool(); $master->addMust($mainFilter); $master->addMust($this->getBoolFilter()); // attach master filter to facet $facet = new \Elastica\Facet\Filter($fieldName); $facet->setFilter($master); return $facet; }
/** * @param $searchText * @return array<Article> */ public function findSousTitres($searchText) { $query_part = new \Elastica\Query\Bool(); $query_part->addShould(new \Elastica\Query\Term(array('value' => array('value' => $searchText, 'boost' => 3)))); $query_part->addShould(new \Elastica\Query\Term(array('intitule' => array('value' => $searchText)))); $filters = new \Elastica\Filter\Bool(); $filters->addMust(new \Elastica\Filter\Term(array('langue' => 'fr'))); $query = new \Elastica\Query\Filtered($query_part, $filters); // return $this->findHybrid($query); pour avoir aussi un ES Result $res = $this->find($query); return $res; }
/** * @see FacetInterface::getFilter */ public function getFilter($fieldName, array $values) { // combine selected filters in an or clause $filter = new \Elastica\Filter\Bool(); $rangeDefs = $this->getRangeDefinitions(); foreach ($values as $filterId) { if (isset($rangeDefs[$filterId])) { $rangeFilter = new \Elastica\Filter\Range(); $rangeFilter->addField($fieldName, $rangeDefs[$filterId]); $filter->addShould($rangeFilter); } } return $filter; }
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); }
/** * Small unit test to check if also the old object name works. * * @group unit * @expectedException \Elastica\Exception\InvalidException */ public function testOldObject() { if (version_compare(phpversion(), 7, '>=')) { self::markTestSkipped('These objects are not supported in PHP 7'); } $filter = new \Elastica\Filter\Bool(); $filter->addShould('fail!'); }
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; }
public function getArticles($user, $searchTerm, $page, $pageOffset, $category, $orderby, $colors, $finder, $elasticIndex) { $boolQuery = new \Elastica\Query\BoolQuery(); if ($category != NULL) { $query = $this->getEntityManager()->createQuery("SELECT c.id FROM OrthIndexBundle:Categories c WHERE c.id LIKE :category")->setParameter('category', $category . "%"); $queryResult = $query->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); foreach ($queryResult as $categoryId) { $categoryArray[] = $categoryId['id']; } $categoryQuery = new \Elastica\Query\Terms(); $categoryQuery->setTerms('catRef', $categoryArray); $boolQuery->addMust($categoryQuery); } if ($searchTerm) { $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); } 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); } $agg = new \Elastica\Aggregation\Terms("catRef"); $agg->setSize(5000); $agg->setField('catRef'); $boolFilter = new \Elastica\Filter\Bool(); if ($user == "anon.") { $boolFilter->addShould(new \Elastica\Filter\Terms('customized', array(0))); } else { $boolFilter->addShould(new \Elastica\Filter\Terms('customized', array(0, $user->getCustomerRef()))); } $filtered = new \Elastica\Query\Filtered($boolQuery, $boolFilter); $query = new \Elastica\Query(); $query->setQuery($filtered); //if( $colors != NULL) { // $query->setFilter($colorNested); //} if ($orderby == 'desc') { $query->setSort(array('variants.price' => array('order' => 'desc'))); } elseif ($orderby == 'asc') { $query->setSort(array('variants.price' => array('order' => 'asc'))); } $query->addAggregation($agg); $query->setSize(12); $query->setFrom($pageOffset); $articles = $finder->find($query); $aggregations = $elasticIndex->search($query); $result = array("articles" => $articles, "aggs" => $aggregations, "rQuery" => $query); return $result; }
/** * Update the indexes for other wiki that also store information about $titles. * @param Title[] $titles array of titles in other indexes to update */ public function updateOtherIndex($titles) { global $wgCirrusSearchWikimediaExtraPlugin; if (!isset($wgCirrusSearchWikimediaExtraPlugin['super_detect_noop'])) { $this->logFailure($titles, 'super_detect_noop plugin not enabled'); return; } $updates = array(); // Build multisearch to find ids to update $findIdsMultiSearch = new \Elastica\Multi\Search($this->connection->getClient()); $findIdsClosures = array(); foreach ($titles as $title) { foreach (OtherIndexes::getExternalIndexes($title) as $otherIndex) { if ($otherIndex === null) { continue; } $type = $this->connection->getPageType($otherIndex); $bool = new \Elastica\Filter\Bool(); // Note that we need to use the keyword indexing of title so the analyzer gets out of the way. $bool->addMust(new \Elastica\Filter\Term(array('title.keyword' => $title->getText()))); $bool->addMust(new \Elastica\Filter\Term(array('namespace' => $title->getNamespace()))); $filtered = new \Elastica\Query\Filtered(new \Elastica\Query\MatchAll(), $bool); $query = new \Elastica\Query($filtered); $query->setFields(array()); // We only need the _id so don't load the _source $query->setSize(1); $findIdsMultiSearch->addSearch($type->createSearch($query)); $findIdsClosures[] = function ($id) use($otherIndex, &$updates, $title) { $updates[$otherIndex][] = array('id' => $id, 'ns' => $title->getNamespace(), 'dbKey' => $title->getDBkey()); }; } } $findIdsClosuresCount = count($findIdsClosures); if ($findIdsClosuresCount === 0) { // No other indexes to check. return; } // Look up the ids and run all closures to build the list of updates $this->start("searching for {numIds} ids in other indexes", array('numIds' => $findIdsClosuresCount)); $findIdsMultiSearchResult = $findIdsMultiSearch->search(); try { $this->success(); for ($i = 0; $i < $findIdsClosuresCount; $i++) { $results = $findIdsMultiSearchResult[$i]->getResults(); if (count($results) === 0) { continue; } $result = $results[0]; call_user_func($findIdsClosures[$i], $result->getId()); } } catch (\Elastica\Exception\ExceptionInterface $e) { $this->failure($e); return; } if (!$updates) { return; } // These are split into a job per index so one index // being frozen doesn't block updates to other indexes // in the same update. foreach ($updates as $indexName => $actions) { $job = new Job\ElasticaWrite(reset($titles), array('clientSideTimeout' => false, 'method' => 'sendOtherIndexUpdates', 'arguments' => array($this->localSite, $indexName, $actions), 'cluster' => $this->writeToClusterName)); $job->run(); } }
public function facet($filter, $sort = 'membership') { $boolQuery = new \Elastica\Query\Bool(); $queryStatus = new \Elastica\Query\Match(); $queryStatus->setFieldQuery('place.status', StatusType::VALIDATED); $boolQuery->addMust($queryStatus); if ($filter->getCategory()) { $queryCategory = new \Elastica\Query\Match(); $queryCategory->setFieldQuery('place.categories.slug', $filter->getCategory()->getSlug()); $boolQuery->addMust($queryCategory); } $queryCity = new \Elastica\Query\Match(); $queryCity->setFieldQuery('place.city.slug', $filter->getCity()->getSlug()); $boolQuery->addMust($queryCity); ##AGGREGATION - FACETED## $now = new \DateTime(); $this->addCollections($boolQuery, $filter); $boolFilter = new \Elastica\Filter\Bool(); //Filters $businessHoursDayFilter = new \Elastica\Filter\Term(['businessHours.day' . date('l') => true]); $businessHoursStartsAtFilter = new \Elastica\Filter\Range('businessHours.startsAtFormatted', array('lte' => $now->format('H:i:s'))); $businessHoursEndsAtFilter = new \Elastica\Filter\Range('businessHours.endsAtFormatted', array('gte' => $now->format('H:i:s'))); $businessHoursIs24HFilter = new \Elastica\Filter\Term(['is24h' => true]); $businessHoursExceptionDateFilter = new \Elastica\Filter\Term(['businessHoursException.dayFormatted' => date('Y-m-d')]); $businessHoursExceptionStartsAtFilter = new \Elastica\Filter\Range('businessHoursException.startsAtFormatted', array('lte' => $now->format('H:i:s'))); $businessHoursExceptionEndsAtFilter = new \Elastica\Filter\Range('businessHoursException.endsAtFormatted', array('gte' => $now->format('H:i:s'))); $businessHoursExceptionStartsAtMissingFilter = new \Elastica\Filter\Missing('businessHoursException.startsAtFormatted'); $businessHoursExceptionEndsAtMissingFilter = new \Elastica\Filter\Missing('businessHoursException.endsAtFormatted'); $businessHoursExceptionDateTimeFilter = new \Elastica\Filter\Bool(); $businessHoursExceptionDateTimeFilter->addMust($businessHoursExceptionDateFilter)->addMust($businessHoursExceptionStartsAtFilter)->addMust($businessHoursExceptionEndsAtFilter); $businessHoursExceptionAllDayClosedFilter = new \Elastica\Filter\Bool(); $businessHoursExceptionAllDayClosedFilter->addMust($businessHoursExceptionDateFilter)->addMust($businessHoursExceptionStartsAtMissingFilter)->addMust($businessHoursExceptionEndsAtMissingFilter); $businessHoursDayTimeFilter = new \Elastica\Filter\Bool(); $businessHoursDayTimeFilter->addMust($businessHoursDayFilter)->addMust($businessHoursStartsAtFilter)->addMust($businessHoursEndsAtFilter); #BusinessHours Filter $businessHoursFilter = new \Elastica\Filter\Bool(); $businessHoursFilter->addShould($businessHoursDayTimeFilter); #BusinessHoursException Filter $businessHoursExceptionFilter = new \Elastica\Filter\Bool(); $businessHoursExceptionFilter->addShould($businessHoursExceptionDateTimeFilter); $businessHoursNestedFilter = new \Elastica\Filter\Nested(); $businessHoursNestedFilter->setFilter($businessHoursFilter)->setPath('place.businessHours'); $businessHoursExceptionNestedFilter = new \Elastica\Filter\Nested(); $businessHoursExceptionNestedFilter->setFilter($businessHoursExceptionFilter)->setPath('place.businessHoursException'); $businessHoursExceptionMissingNestedFilter = new \Elastica\Filter\Nested(); $businessHoursExceptionMissingNestedFilter->setFilter($businessHoursExceptionAllDayClosedFilter)->setPath('place.businessHoursException'); $workingNowFilter = new \Elastica\Filter\Bool(); $workingNowFilter->addShould($businessHoursNestedFilter)->addShould($businessHoursExceptionNestedFilter)->addShould($businessHoursIs24HFilter)->addMustNot($businessHoursExceptionMissingNestedFilter); if ($filter->getBusinessHours()) { foreach ($filter->getBusinessHours() as $value) { if ($value == 'workingNow') { $boolFilter->addMust($workingNowFilter); } if ($value == '24/7') { $boolFilter->addMust($businessHoursIs24HFilter); } } } //Aggregation $aggregFilters = new \Elastica\Aggregation\Terms('filters'); $aggregFilters->setField('placeFilterValues.slug'); //$aggregFilters->setSize(0); $aggregCategories = new \Elastica\Aggregation\Terms('categories'); $aggregCategories->setField('categories.slug'); // $aggregBusinessHoursDay = new \Elastica\Aggregation\Filter('businessHoursDay'); // $aggregBusinessHoursDay->setFilter($businessHoursDayFilter); // // $aggregBusinessHoursStartsAt = new \Elastica\Aggregation\Filter('businessHoursStartsAt'); // $aggregBusinessHoursStartsAt->setFilter($businessHoursStartsAtFilter); // // $aggregBusinessHoursEndsAtFilter = new \Elastica\Aggregation\Filter('businessHoursEndsAt'); // $aggregBusinessHoursEndsAtFilter->setFilter($businessHoursEndsAtFilter); // // $aggregBusinessHoursStartsAt->addAggregation($aggregBusinessHoursEndsAtFilter); // $aggregBusinessHoursDay->addAggregation($aggregBusinessHoursStartsAt); $aggregBusinessHours = new \Elastica\Aggregation\Filters('businessHours'); $aggregBusinessHours->addFilter($workingNowFilter, 'workingNow'); $aggregBusinessHours->addFilter($businessHoursIs24HFilter, '24/7'); $filtered = new \Elastica\Query\Filtered($boolQuery, $boolFilter); $query = \Elastica\Query::create($filtered); //set aggregations type foreach ($filter->getAggregations() as $aggregation) { $aggtype = 'aggreg' . ucfirst($aggregation); $query->addAggregation(${$aggtype}); } //$query->addAggregation($aggregFilters); //$query->addAggregation($aggregBusinessHours); $sortMembership = array('membershipSubscriptions.membership.score' => array('nested_filter' => array('term' => array('membershipSubscriptions.m_status' => MembershipStatusType::ACTIVE)), 'order' => 'desc')); $sortRating = array('rating' => array('order' => 'desc')); $viewsCount = array('viewsCount' => array('order' => 'desc')); $sortTypes = array('membership' => array($sortMembership, $sortRating), 'rating' => array($sortRating), 'views' => array($viewsCount)); // if(!isset($sortTypes[$sort])){ // $sort = 'membership'; // } foreach ($sortTypes[$sort] as $s) { $query->addSort($s); } //$query->setFrom(4); //$query->addSort(array('rating' => array('order' => 'desc'))); //var_dump(json_encode($query->getQuery(), JSON_PRETTY_PRINT));die(); return $this->findPaginated($query); }
/** * This function constructs and returns main filter for elasticsearch query. * * @return \Elastica\Filter\BoolOr */ protected function constructMainFilter($finalTypes, $options = array()) { $mainFilter = new \Elastica\Filter\Bool(); foreach ($finalTypes as $module) { $moduleFilter = $this->constructModuleLevelFilter($module, $options); // if we want myitems add more to the module filter if (isset($options['my_items']) && $options['my_items'] !== false) { $moduleFilter = $this->constructMyItemsFilter($moduleFilter); } if (isset($options['filter']) && $options['filter']['type'] == 'range') { $moduleFilter = $this->constructRangeFilter($moduleFilter, $options['filter']); } // we only want JUST favorites if the option is 2 // if the option is 1 that means we want all including favorites, // which in FTS is a normal search parameter if (isset($options['favorites']) && $options['favorites'] == 2) { $moduleFilter = $this->constructMyFavoritesFilter($moduleFilter); } $mainFilter->addShould($moduleFilter); } return $mainFilter; }
/** * Small unit test to check if also the old object name works. * * @group unit * @expectedException \Elastica\Exception\InvalidException */ public function testOldObject() { if (version_compare(phpversion(), 7, '>=')) { self::markTestSkipped('These objects are not supported in PHP 7'); } $err = array(); set_error_handler(function () use(&$err) { $err[] = func_get_args(); }); $filter = new \Elastica\Filter\Bool(); restore_error_handler(); $this->assertCount(1, $err); $this->assertEquals(E_USER_DEPRECATED, $err[0][0]); $filter->addShould('fail!'); }
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; }
/** * @param $appliedFilters * @param $elasticaQuery * * @return array */ public function applyFilterToElasticaQuery($appliedFilters, $elasticaQuery) { $termFilters = new \Elastica\Filter\Terms(); $rangeFilters = new \Elastica\Filter\Range(); $boolFilter = new \Elastica\Filter\Bool(); $filters = array(); foreach ($appliedFilters as $facet) { if (strpos($facet[key($facet)], "|") !== false) { $filters[key($facet)][] = array('range' => explode('|', $facet[key($facet)])); } else { $filters[key($facet)][] = $facet[key($facet)]; } } foreach ($filters as $name => $value) { if (is_array($value[0])) { foreach ($value as $range) { $rangeFilters->addField($name, array('gte' => $range['range'][0], 'lte' => $range['range'][1])); $boolFilter->addShould($rangeFilters); } } else { $termFilters->setTerms($name, $value); $boolFilter->addShould($termFilters); } } $elasticaQuery->setFilter($boolFilter); return array($termFilters, $rangeFilters, $boolFilter, $filters); }
/** * @param $term * @param $locale * * @return Query */ protected function getI18NQuery($term, $locale) { $filters = new \Elastica\Filter\Bool(); $filters->addMust(new \Elastica\Filter\Term(['locale' => $locale])); $filteredQuery = new \Elastica\Query\Filtered(new QueryString($term), $filters); return new Query($filteredQuery); }
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()); } }