function getElasticaTitleEn($querystring) { if ($querystring != null && $querystring != '') { $query = new \Elastica\Query\MultiMatch(); $query->setFields(array('title_en', 'name')); // $query->setFieldFuzziness('title_en', 0.7); // $query->setFieldMinimumShouldMatch('title_en', '80%'); // } else { $query = new \Elastica\Query\MatchAll(); } return $query; }
public function searchRelatedEpisodes(Episode $episode, $numberResults = 5) { $tagtext = implode(" ", $episode->getTags()->toArray()); $boolQuery = new \Elastica\Query\BoolQuery(); $multiquery = new \Elastica\Query\MultiMatch(); $multiquery->setFields(['name', 'description', 'series']); $multiquery->setQuery($tagtext); $multiquery->setType(\Elastica\Query\MultiMatch::TYPE_MOST_FIELDS); $boolQuery->addMust($multiquery); $activeQuery = new \Elastica\Query\Term(); $activeQuery->setTerm('is_active', true); $boolQuery->addMust($activeQuery); $excludeEpisodeQuery = new \Elastica\Query\Term(); $excludeEpisodeQuery->setTerm('id', $episode->getId()); $boolQuery->addMustNot($excludeEpisodeQuery); return $this->episodeFinder->find($boolQuery, $numberResults); }
/** * @param $ort string * @param $items string[] * @return SearchResult */ public function search($ort, $items) { $result = new SearchResult(); $ortQuery = new \Elastica\Query\MultiMatch(); $ortQuery->setFields(["ORT", "PLZ"]); $ortQuery->setFuzziness(1); $ortQuery->setQuery($ort); $result->setOrte($this->marktFinder->find($ortQuery)); $results = array(); foreach ($items as $item) { $artikelQuery = new \Elastica\Query\Match(); $artikelQuery->setFieldQuery("slugs", $item); $artikelQuery->setFieldFuzziness("slugs", 1.5); $results[] = $this->artikelFinder->find($artikelQuery); } $result->setItems($results); return $result; }
/** * @Route("/app/search", name="search") * @Template("AppBundle::search.html.twig") */ public function searchAction(Request $request) { $q = $request->query->get('q'); $finder = $this->get('fos_elastica.finder.app'); $tenantHelper = $this->get('multi_tenant.helper'); $boolQuery = new \Elastica\Query\BoolQuery(); $fieldQuery = new \Elastica\Query\MultiMatch(); $fieldQuery->setQuery($q); $fieldQuery->setFields(['_all']); $boolQuery->addMust($fieldQuery); $tenantQuery = new \Elastica\Query\Term(); $tenantQuery->setTerm('id', $tenantHelper->getCurrentTenant()->getId()); $nestedQuery = new \Elastica\Query\Nested(); $nestedQuery->setPath('tenant'); $nestedQuery->setQuery($tenantQuery); $boolQuery->addMust($nestedQuery); $results = $finder->findPaginated($boolQuery); return ['results' => $results, 'query' => $q]; }
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 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; }
/** * 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 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)); }
/** * Builds a multi match query with the cross_field type. * * @param array $boostedField of boosted fields * @param string $queryString the query * @param string $minShouldMatch the MinimumShouldMatch value * @return \Elastica\Query\MultiMatch */ private function buildCrossFields(array $boostedFields, $queryString, $minShouldMatch) { $fields = array(); foreach ($boostedFields as $f) { $fields[] = $f['field'] . '^' . $f['boost']; } $cross = new \Elastica\Query\MultiMatch(); $cross->setQuery($queryString); $cross->setFields($fields); $cross->setType('cross_fields'); $cross->setMinimumShouldMatch($minShouldMatch); return $cross; }