Exemplo n.º 1
0
 /**
  * @param mixed  $query
  * @param string $lang
  * @param string $type
  *
  * @return mixed|void
  */
 public function defineSearch($query, $lang, $type)
 {
     $query = \Elastica\Util::escapeTerm($query);
     $elasticaQueryLang = new \Elastica\Query\Term();
     $elasticaQueryLang->setTerm('lang', $lang);
     $elasticaQueryString = new \Elastica\Query\Match();
     $elasticaQueryString->setFieldQuery('content', $query)->setFieldMinimumShouldMatch('content', '80%');
     $elasticaQueryTitle = new \Elastica\Query\QueryString();
     $elasticaQueryTitle->setDefaultField('title')->setBoost(2.0)->setQuery($query);
     $elasticaQueryBool = new \Elastica\Query\BoolQuery();
     $elasticaQueryBool->addMust($elasticaQueryLang)->addShould($elasticaQueryTitle)->addShould($elasticaQueryString)->setMinimumNumberShouldMatch(1);
     $this->applySecurityContext($elasticaQueryBool);
     if (!is_null($type)) {
         $elasticaQueryType = new \Elastica\Query\Term();
         $elasticaQueryType->setTerm('type', $type);
         $elasticaQueryBool->addMust($elasticaQueryType);
     }
     $rootNode = $this->domainConfiguration->getRootNode();
     if (!is_null($rootNode)) {
         $elasticaQueryRoot = new \Elastica\Query\Term();
         $elasticaQueryRoot->setTerm('root_id', $rootNode->getId());
         $elasticaQueryBool->addMust($elasticaQueryRoot);
     }
     $this->query->setQuery($elasticaQueryBool);
     $this->query->setHighlight(array('pre_tags' => array('<strong>'), 'post_tags' => array('</strong>'), 'fields' => array('content' => array('fragment_size' => 150, 'number_of_fragments' => 3))));
 }
 public function findByCriteria(TrackRepositoryCriteria $criteria)
 {
     $boolQuery = new \Elastica\Query\BoolQuery();
     if ($criteria->albumId()) {
         $query = new \Elastica\Query\Term();
         $query->setParam('album.id', $criteria->albumId());
         $boolQuery->addMust($query);
     }
     if ($criteria->albumTitle()) {
         $query = new \Elastica\Query\Match();
         $query->setFieldQuery('album.title', $criteria->albumTitle());
         $query->setFieldFuzziness('album.title', 2);
         $boolQuery->addMust($query);
     }
     if ($criteria->trackName()) {
         $query = new \Elastica\Query\Match();
         $query->setFieldQuery('name', $criteria->trackName());
         $query->setFieldFuzziness('name', 2);
         $boolQuery->addMust($query);
     }
     if ($criteria->composer()) {
         $query = new \Elastica\Query\Match();
         $query->setFieldQuery('composer', $criteria->composer());
         $query->setFieldFuzziness('composer', 2);
         $boolQuery->addMust($query);
     }
     $this->elasticaSearch->setQuery($boolQuery);
     $query = $this->elasticaSearch->getQuery();
     $query->setSize($criteria->size());
     $query->setFrom(($criteria->page() - 1) * $criteria->size());
     $query->addSort(['name_not_analyzed' => ['order' => 'asc']]);
     return $this->buildEntities($this->elasticaSearch->search()->getResults());
 }
 public function getQueryForSearch(ArticleSearch $articleSearch)
 {
     // we create a query to return all the articles
     // but if the criteria title is specified, we use it
     if ($articleSearch->getTitle() !== null && $articleSearch != '') {
         $query = new \Elastica\Query\Match();
         $query->setFieldQuery('article.title', $articleSearch->getTitle());
         $query->setFieldFuzziness('article.title', 0.7);
         $query->setFieldMinimumShouldMatch('article.title', '80%');
     } else {
         $query = new \Elastica\Query\MatchAll();
     }
     // then we create filters depending on the chosen criterias
     $boolQuery = new \Elastica\Query\Bool();
     $boolQuery->addMust($query);
     /*
         Dates filter
         We add this filter only the ispublished filter is not at "false"
     */
     if ("false" != $articleSearch->isPublished() && null !== $articleSearch->getDateFrom() && null !== $articleSearch->getDateTo()) {
         $boolQuery->addMust(new \Elastica\Query\Range('publishedAt', array('gte' => \Elastica\Util::convertDate($articleSearch->getDateFrom()->getTimestamp()), 'lte' => \Elastica\Util::convertDate($articleSearch->getDateTo()->getTimestamp()))));
     }
     // Published or not filter
     if ($articleSearch->isPublished() !== null) {
         $boolQuery->addMust(new \Elastica\Query\Terms('published', array($articleSearch->isPublished())));
     }
     $query = new \Elastica\Query($boolQuery);
     $query->setSort(array($articleSearch->getSort() => array('order' => $articleSearch->getDirection())));
     return $query;
 }
Exemplo n.º 4
0
 public function searchTags($searchphrase)
 {
     $fieldQuery = new \Elastica\Query\Match();
     $fieldQuery->setFieldQuery('slug', $searchphrase);
     $fieldQuery->setFieldParam('slug', 'analyzer', 'my_analyzer');
     return $this->tagFinder->find($fieldQuery);
 }
Exemplo n.º 5
0
 /**
  *
  * @Route("", name="centrale_lille_searchuser")
  * @Method("GET")
  */
 public function searchAction(Request $request)
 {
     $search = new SearchString();
     $searchForm = $this->get('form.factory')->createNamed('', 'string_search_type', $search, array('action' => $this->generateUrl('centrale_lille_searchuser'), 'method' => 'GET'));
     $searchForm->handleRequest($request);
     $search = $searchForm->getData();
     if (is_null($search->getStringSearch())) {
         $result_machine = [];
         $result_user = [];
     } else {
         //Recherche User
         $typeUser = $this->get('fos_elastica.index.fablab.User');
         $query_part_user = new \Elastica\Query\BoolQuery();
         $fieldQuery = new \Elastica\Query\Match();
         $fieldQuery2 = new \Elastica\Query\Match();
         $fieldQuery->setFieldQuery('email', $search->getStringSearch());
         $fieldQuery->setFieldQuery('email', $search->getStringSearch());
         $fieldQuery->setFieldFuzziness('email', 0.7);
         $query_part_user->addShould($fieldQuery);
         $fieldQuery2->setFieldQuery('username', $search->getStringSearch());
         $fieldQuery2->setFieldQuery('username', $search->getStringSearch());
         $fieldQuery2->setFieldFuzziness('username', 0.7);
         $query_part_user->addShould($fieldQuery2);
         $filters = new \Elastica\Filter\Bool();
         $query_user = new \Elastica\Query\Filtered($query_part_user, $filters);
         $result_user = $typeUser->search($query_user);
         //Recherche Machine
         $typeMachine = $this->get('fos_elastica.index.fablab.Machine');
         $query_part_machine = new \Elastica\Query\Bool();
         $fieldQuery3 = new \Elastica\Query\Match();
         $fieldQuery4 = new \Elastica\Query\Match();
         $fieldQuery3->setFieldQuery('machine_name', $search->getStringSearch());
         $fieldQuery3->setFieldFuzziness('machine_name', 0.7);
         $fieldQuery3->setFieldMinimumShouldMatch('machine_name', '80%');
         $query_part_machine->addShould($fieldQuery3);
         $fieldQuery4->setFieldQuery('description', $search->getStringSearch());
         $fieldQuery4->setFieldFuzziness('description', 2);
         $fieldQuery4->setFieldMinimumShouldMatch('description', '100%');
         $query_part_machine->addShould($fieldQuery4);
         $filters = new \Elastica\Filter\Bool();
         $query_machine = new \Elastica\Query\Filtered($query_part_machine, $filters);
         $result_machine = $typeMachine->search($query_machine);
         //Recherche Machine
         $typeMachine = $this->get('fos_elastica.index.fablab.Machine');
         $query_part_machine = new \Elastica\Query\Bool();
         $fieldQuery3 = new \Elastica\Query\Match();
         $fieldQuery4 = new \Elastica\Query\Match();
         $fieldQuery3->setFieldQuery('machine_name', $search->getStringSearch());
         // $fieldQuery3->setFieldFuzziness('machine.machine_name', 0.7);
         //$fieldQuery3->setFieldMinimumShouldMatch('machine_name', '80%');
         $query_part_machine->addShould($fieldQuery3);
         $fieldQuery4->setFieldQuery('description', $search->getStringSearch());
         // $fieldQuery4->setFieldFuzziness('machine.machine_name', 0.7);
         //$fieldQuery4->setFieldMinimumShouldMatch('machine_name', '100%');
         $query_part_machine->addShould($fieldQuery4);
     }
     return $this->render('CentraleLilleSearchBundle:Default:search.html.twig', array('result_user' => $result_user, 'result_machine' => $result_machine, 'form' => $searchForm->createView(), 'search' => $search->getStringSearch()));
 }
Exemplo n.º 6
0
 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;
 }
 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);
 }
Exemplo n.º 8
0
 public function searchAdvanced($q = '')
 {
     if ($q == '') {
         $baseQuery = new \Elastica\Query\MatchAll();
     } else {
         $baseQuery = new \Elastica\Query\Match();
         $baseQuery->setFieldQuery('description', $q);
         $baseQuery->setFieldFuzziness('description', 0.7);
         $baseQuery->setFieldMinimumShouldMatch('description', '80%');
     }
     $boolFilter = new \Elastica\Filter\BoolFilter();
     $dateFrom = new \DateTime();
     $dateFrom->sub(new \DateInterval('P7D'));
     $dateTo = new \DateTime();
     $dateTo->add(new \DateInterval('P1D'));
     $boolFilter->addMust(new \Elastica\Filter\Range('createdAt', array('gte' => \Elastica\Util::convertDate($dateFrom->getTimestamp()), 'lte' => \Elastica\Util::convertDate($dateTo->getTimestamp()))));
     /*
      * $boolFilter->addMust(
      *     new \Elastica\Filter\Term(array('isPublished' => true))
      * );
      * $boolFilter->addMust(
      *     new \Elastica\Filter\Terms('isPublished', array('1', '2', '3'))
      * );
      */
     /*
      * $baseQuery = new \Elastica\Filter\Bool();
      * $baseQuery->addShould(
      *     new \Elastica\Filter\Term(array('id' => intval($q)))
      * );
      * $baseQuery->addShould(
      *     new \Elastica\Filter\Term(array('amount' => floatval($q)))
      * );
      * $filtered = new \Elastica\Query\Filtered();
      * $filtered->setFilter($baseQuery);
      * return $this->finder->find($filtered);
      */
     /*
      * $baseQuery  = new \Elastica\Query\Bool;
      * $idQueryTerm = new \Elastica\Query\Term;
      * $idQueryTerm->setTerm('id', intval($q));
      * $baseQuery->addShould($idQueryTerm);
      */
     $filtered = new \Elastica\Query\Filtered($baseQuery, $boolFilter);
     $query = \Elastica\Query::create($filtered);
     $query->addSort(array('id' => array('order' => 'asc')));
     $query->setSize(1);
     return $this->find($query);
 }
 /**
  * @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;
 }
Exemplo n.º 10
0
 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));
 }
Exemplo n.º 11
0
 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 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);
 }
 protected function parseQueryString($queryString, array $opts)
 {
     $fields = $highlights = array();
     $terms = preg_split('/\\s+/', $queryString);
     $match = $opts['match'];
     $case = $opts['case'];
     // Map each word in the query string with its corresponding field
     foreach ($terms as $term) {
         $prefix = strstr($term, '*', true);
         if ($prefix) {
             // For wildcard search
             $fields['content.prefix_complete'][] = $prefix;
         } elseif ($case === '1') {
             // For case sensitive search
             $fields['content.case_sensitive'][] = $term;
         } else {
             $fields['content'][] = $term;
         }
     }
     // Allow searching either by message content or message id (page name
     // without language subpage) with exact match only.
     $searchQuery = new \Elastica\Query\Bool();
     foreach ($fields as $analyzer => $words) {
         foreach ($words as $word) {
             $boolQuery = new \Elastica\Query\Bool();
             $contentQuery = new \Elastica\Query\Match();
             $contentQuery->setFieldQuery($analyzer, $word);
             $boolQuery->addShould($contentQuery);
             $messageQuery = new \Elastica\Query\Term();
             $messageQuery->setTerm('localid', $word);
             $boolQuery->addShould($messageQuery);
             if ($match === 'all') {
                 $searchQuery->addMust($boolQuery);
             } else {
                 $searchQuery->addShould($boolQuery);
             }
             // Fields for highlighting
             $highlights[$analyzer] = array('number_of_fragments' => 0);
             // Allow searching by exact message title (page name with
             // language subpage).
             $title = Title::newFromText($word);
             if (!$title) {
                 continue;
             }
             $handle = new MessageHandle($title);
             if ($handle->isValid() && $handle->getCode() !== '') {
                 $localid = $handle->getTitleForBase()->getPrefixedText();
                 $boolQuery = new \Elastica\Query\Bool();
                 $messageId = new \Elastica\Query\Term();
                 $messageId->setTerm('localid', $localid);
                 $boolQuery->addMust($messageId);
                 $searchQuery->addShould($boolQuery);
             }
         }
     }
     return array($searchQuery, $highlights);
 }
Exemplo n.º 14
0
 $search = new Elastica\Search($elasticaClient);
 $searchThrough = $search->addIndex($_GET['index']);
 if (isset($_GET['collection']) && $_GET['collection'] != 'all') {
     $boolQuery = new Elastica\Query\Bool();
     $query_collection = new Elastica\Query\Match();
     $query_collection->setFieldQuery('content_type', $_GET['collection']);
     $elasticaTypeOfFilter = new Elastica\Filter\Query();
     $elasticaTypeOfFilter->setQuery($query_collection);
     $elasticaFilterAnd = new Elastica\Filter\BoolAnd();
     $elasticaFilterAnd->addFilter($elasticaTypeOfFilter);
     $filteredQuery = new Elastica\Query\Filtered($queryString, $elasticaFilterAnd);
 }
 $query = new Elastica\Query($filteredQuery);
 if (isset($_GET['speaker'])) {
     $boolQuery = new Elastica\Query\Bool();
     $query_collection = new Elastica\Query\Match();
     $query_collection->setFieldQuery('speaker', $_GET['speaker'])->setFieldParam('speaker', 'type', 'phrase');
     $elasticaTypeOfFilter = new Elastica\Filter\Query();
     $elasticaTypeOfFilter->setQuery($query_collection);
     $elasticaFilterAnd = new Elastica\Filter\BoolAnd();
     $elasticaFilterAnd->addFilter($elasticaTypeOfFilter);
     $filteredQuery = new Elastica\Query\Filtered($queryString, $elasticaFilterAnd);
     $query = new Elastica\Query($filteredQuery);
 }
 //SORT BY
 if (isset($_GET['sort-by'])) {
     if (isset($_GET['sort-by-direction'])) {
         $sortdirection = $_GET['sort-by-direction'];
     } else {
         $sortdirection = "desc";
     }
Exemplo n.º 15
0
 /**
  * @param {Integer} libraryID
  * @param {String} searchText
  * @return {Array<String>|Boolean} An array of item keys, or FALSE if no results
  */
 public static function searchInLibrary($libraryID, $searchText)
 {
     // TEMP: For now, strip double-quotes and make everything a phrase search
     $searchText = str_replace('"', '', $searchText);
     $type = self::getReadType();
     $libraryFilter = new \Elastica\Filter\Term();
     $libraryFilter->setTerm("libraryID", $libraryID);
     $matchQuery = new \Elastica\Query\Match();
     $matchQuery->setFieldQuery('content', $searchText);
     $matchQuery->setFieldType('content', 'phrase');
     $matchQuery = new \Elastica\Query\Filtered($matchQuery, $libraryFilter);
     $start = microtime(true);
     $resultSet = $type->search($matchQuery, ['routing' => $libraryID]);
     StatsD::timing("elasticsearch.client.item_fulltext.search", (microtime(true) - $start) * 1000);
     if ($resultSet->getResponse()->hasError()) {
         throw new Exception($resultSet->getResponse()->getError());
     }
     $results = $resultSet->getResults();
     $keys = array();
     foreach ($results as $result) {
         $keys[] = explode("/", $result->getId())[1];
     }
     return $keys;
 }
Exemplo n.º 16
0
 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;
 }
Exemplo n.º 17
0
 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));
 }
Exemplo n.º 18
0
 public function search($category)
 {
     // we create a query to return all the articles
     // but if the criteria title is specified, we use it
     $boolQuery = new \Elastica\Query\Bool();
     /*Fetch only VALIDATED place*/
     $queryStatus = new \Elastica\Query\Match();
     $queryStatus->setFieldQuery('event.status', StatusType::VALIDATED);
     $boolQuery->addMust($queryStatus);
     if ($category !== null) {
         $queryCategory = new \Elastica\Query\Match();
         $queryCategory->setFieldQuery('event.categories.slug', $category);
         $boolQuery->addMust($queryCategory);
     } else {
         $query = new \Elastica\Query\MatchAll();
     }
     $baseQuery = $boolQuery;
     // then we create filters depending on the chosen criterias
     $boolFilter = new \Elastica\Filter\Bool();
     /*
         Dates filter
         We add this filter only the getIspublished filter is not at "false"
     */
     //        if("false" != $articleSearch->getIsPublished()
     //           && null !== $articleSearch->getDateFrom()
     //           && null !== $articleSearch->getDateTo())
     //        {
     //            $boolFilter->addMust(new \Elastica\Filter\Range('publishedAt',
     //                array(
     //                    'gte' => \Elastica\Util::convertDate($articleSearch->getDateFrom()->getTimestamp()),
     //                    'lte' => \Elastica\Util::convertDate($articleSearch->getDateTo()->getTimestamp())
     //                )
     //            ));
     //        }
     //
     // Published or not filter
     //        if($placeSearch->getIs24h() !== null && $placeSearch->getIs24h()){
     //                        //var_dump($placeSearch->getIs24h());die();
     //            $boolFilter->addMust(
     //                new \Elastica\Filter\Term(['is24h' => $placeSearch->getIs24h()])
     //                //new \Elastica\Filter\Term(['isWifi' => $placeSearch->getIsWifi()])
     //            );
     //
     //            //$boolFilter->addMust('is24h', $placeSearch->getIs24h());
     //        }
     //
     //        if($placeSearch->getIsWifi() !== null && $placeSearch->getIsWifi()){
     //            $boolFilter->addMust(
     //                new \Elastica\Filter\Term(['isWifi' => $placeSearch->getIsWifi()])
     //            );
     //        }
     //
     //        if($placeSearch->getIsDelivery() !== null && $placeSearch->getIsDelivery()){
     //            $boolFilter->addMust(
     //                new \Elastica\Filter\Term(['isDelivery' => $placeSearch->getIsDelivery()])
     //            );
     //        }
     $filtered = new \Elastica\Query\Filtered($baseQuery, $boolFilter);
     $query = \Elastica\Query::create($filtered);
     return $this->find($query);
 }
 /**
  *
  * @Route("", name="centrale_lille_search")
  */
 public function searchAction()
 {
     $jsonContentUser = '';
     $jsonContentMachine = '';
     $jsonContentProjet = '';
     $jsonContentSkills = '';
     $jsonTotal = '';
     $datauser = [];
     $dataprojet = [];
     $dataskills = [];
     $datamachine = [];
     $search = $this->get('request')->query->get('searchForm');
     if (is_null($search)) {
         $result_machine = [];
         $result_user = [];
         $result_skills = [];
         $result_projet = [];
     } else {
         //User Json
         $queryall = new \Elastica\Query\MatchAll();
         $typeUser = $this->get('fos_elastica.index.fablab.User');
         $result_alluser = $typeUser->search($queryall)->getResults();
         foreach ($result_alluser as $result) {
             $source = $result->getSource();
             $datauser[] = array('name' => $source['username'], 'link' => 'userId');
         }
         $jsonContentUser = new JsonResponse($datauser, 200, array('Cache-Control' => 'no-cache'));
         //Project Json
         $queryall = new \Elastica\Query\MatchAll();
         $typeProjet = $this->get('fos_elastica.index.fablab.Projet');
         $result_allprojet = $typeProjet->search($queryall)->getResults();
         foreach ($result_allprojet as $result) {
             $source = $result->getSource();
             $dataprojet[] = array('name' => $source['name'], 'link' => 'projectId');
         }
         $jsonContentProjet = new JsonResponse($dataprojet, 200, array('Cache-Control' => 'no-cache'));
         //Skills Json
         $queryall = new \Elastica\Query\MatchAll();
         $typeSkills = $this->get('fos_elastica.index.fablab.Competence');
         $result_allskills = $typeSkills->search($queryall)->getResults();
         foreach ($result_allskills as $result) {
             $source = $result->getSource();
             $dataskills[] = array('name' => $source['name'], 'link' => 'skillsId');
         }
         $jsonContentSkills = new JsonResponse($dataskills, 200, array('Cache-Control' => 'no-cache'));
         //Machine Json
         $queryall = new \Elastica\Query\MatchAll();
         $typeMachine = $this->get('fos_elastica.index.fablab.Machine');
         $result_allmachine = $typeMachine->search($queryall)->getResults();
         foreach ($result_allmachine as $result) {
             $source = $result->getSource();
             $type = $result->getType();
             $datamachine[] = array('name' => $source['name'], 'link' => 'machineId');
         }
         $jsonContentMachine = new JsonResponse($datamachine, 200, array('Cache-Control' => 'no-cache'));
         $jsonContentMachine = '"machine": ' . substr($jsonContentMachine, 83);
         $jsonContentUser = '******' . substr($jsonContentUser, 83);
         $jsonContentSkills = '"competence": ' . substr($jsonContentSkills, 83);
         $jsonContentProjet = '"projet": ' . substr($jsonContentProjet, 83);
         $jsonTotal = '{' . $jsonContentUser . ',' . $jsonContentMachine . ',' . $jsonContentProjet . ',' . $jsonContentSkills . '}';
         //Recherche User
         $typeUser = $this->get('fos_elastica.index.fablab.User');
         $query_part_user = new \Elastica\Query\BoolQuery();
         $fieldQuery = new \Elastica\Query\Match();
         $fieldQuery2 = new \Elastica\Query\Match();
         $fieldQuery9 = new \Elastica\Query\Match();
         $fieldQuery10 = new \Elastica\Query\Match();
         $fieldQuery->setFieldQuery('email', $search);
         $fieldQuery->setFieldFuzziness('email', 0.2);
         $query_part_user->addShould($fieldQuery);
         $fieldQuery9->setFieldQuery('firstname', $search);
         $fieldQuery9->setFieldFuzziness('firstname', 0.2);
         $query_part_user->addShould($fieldQuery9);
         $fieldQuery10->setFieldQuery('lastname', $search);
         $fieldQuery10->setFieldFuzziness('lastname', 0.2);
         $query_part_user->addShould($fieldQuery10);
         $fieldQuery2->setFieldQuery('username', $search);
         $fieldQuery2->setFieldFuzziness('username', 0.2);
         $query_part_user->addShould($fieldQuery2);
         $filters = new \Elastica\Filter\Bool();
         $query_user = new \Elastica\Query\Filtered($query_part_user, $filters);
         $result_user = $typeUser->search($query_user);
         //Recherche Machine
         $typeMachine = $this->get('fos_elastica.index.fablab.Machine');
         $query_part_machine = new \Elastica\Query\Bool();
         $fieldQuery3 = new \Elastica\Query\Match();
         $fieldQuery4 = new \Elastica\Query\Match();
         $fieldQuery3->setFieldQuery('name', $search);
         $fieldQuery3->setFieldFuzziness('name', 0.2);
         $fieldQuery3->setFieldMinimumShouldMatch('name', '80%');
         $query_part_machine->addShould($fieldQuery3);
         $fieldQuery4->setFieldQuery('description', $search);
         $fieldQuery4->setFieldFuzziness('description', 2);
         $fieldQuery4->setFieldMinimumShouldMatch('description', '100%');
         $query_part_machine->addShould($fieldQuery4);
         $filters = new \Elastica\Filter\Bool();
         $query_machine = new \Elastica\Query\Filtered($query_part_machine, $filters);
         $result_machine = $typeMachine->search($query_machine);
         //Recherche Skills
         $typeSkills = $this->get('fos_elastica.index.fablab.Competence');
         $query_part_skills = new \Elastica\Query\Bool();
         $fieldQuery5 = new \Elastica\Query\Match();
         $fieldQuery5->setFieldQuery('name', $search);
         $fieldQuery5->setFieldFuzziness('name', 2);
         $fieldQuery5->setFieldMinimumShouldMatch('name', '40%');
         $query_part_skills->addShould($fieldQuery5);
         $filters = new \Elastica\Filter\Bool();
         $query_skills = new \Elastica\Query\Filtered($query_part_skills, $filters);
         $result_skills = $typeSkills->search($query_skills);
         //Recherche projet
         $typeProjet = $this->get('fos_elastica.index.fablab.Projet');
         $query_part_projet = new \Elastica\Query\Bool();
         $fieldQuery6 = new \Elastica\Query\Match();
         $fieldQuery7 = new \Elastica\Query\Match();
         $fieldQuery6->setFieldQuery('name', $search);
         $fieldQuery6->setFieldFuzziness('name', 0.2);
         $fieldQuery6->setFieldMinimumShouldMatch('name', '80%');
         $query_part_projet->addShould($fieldQuery6);
         $fieldQuery7->setFieldQuery('summary', $search);
         $fieldQuery7->setFieldFuzziness('summary', 2);
         $fieldQuery7->setFieldMinimumShouldMatch('summary', '100%');
         $query_part_projet->addShould($fieldQuery7);
         $filters = new \Elastica\Filter\Bool();
         $query_projet = new \Elastica\Query\Filtered($query_part_projet, $filters);
         $result_projet = $typeProjet->search($query_projet);
         //
         $encoder = array(new JsonEncoder());
         $normalizer = array(new ObjectNormalizer());
         $serializer = new Serializer($normalizer, $encoder);
     }
     return $this->render('CentraleLilleSearchBundle:Default:search.html.twig', array('result_user' => $result_user, 'result_machine' => $result_machine, 'result_competence' => $result_skills, 'result_project' => $result_projet, 'search' => $search, 'userjson' => $jsonContentUser, 'machinejson' => $jsonContentMachine, 'jsonTotal' => $jsonTotal));
 }
 /**
  * Builds a simple match query.
  *
  * @param array $boostedField the boostedField
  * @param string $queryString the query
  * @param string $minShouldMatch the MinimumShouldMatch value
  * @return \Elastica\Query\Match
  */
 private function buildSimpleMatch($boostedField, $queryString, $minShouldMatch)
 {
     $match = new \Elastica\Query\Match();
     $match->setField($boostedField['field'], array('query' => $queryString, 'minimum_should_match' => $minShouldMatch, 'boost' => $boostedField['boost']));
     return $match;
 }
 public function append(FunctionScore $functionScore)
 {
     if (!$this->boostTemplates) {
         return;
     }
     foreach ($this->boostTemplates as $name => $weight) {
         $match = new \Elastica\Query\Match();
         $match->setFieldQuery('template', $name);
         $filterQuery = new \Elastica\Filter\Query($match);
         $filterQuery->setCached(true);
         $functionScore->addWeightFunction($weight * $this->weight, $filterQuery);
     }
 }
Exemplo n.º 22
0
 public function mutipleSearchWithElasticSearch($searchedTerm, $selectedTerm)
 {
     if ($selectedTerm == "") {
         $selectedTerm = $searchedTerm;
     }
     function auto_fuzzy($term)
     {
         if (mb_strlen($term) <= 2) {
             $fuzzy_int = 0;
         } elseif (mb_strlen($term) < 10) {
             $fuzzy_int = 1;
         } elseif (mb_strlen($term) < 17) {
             $fuzzy_int = 2;
         } elseif (mb_strlen($term) <= 23) {
             $fuzzy_int = 3;
         } else {
             $fuzzy_int = 4;
         }
         return $fuzzy_int;
     }
     $terms = array();
     $finder = $this->container->get('fos_elastica.finder.shlml.word');
     // On explose le string d'entrée en tableau, en séparant les mots espacés par un espace
     $terms = explode(" ", $searchedTerm);
     // Je ne retiens que les trois premiers mots
     $terms = array_slice($terms, 0, 3);
     // Je trouve les mots "similaires" grâce à Elasticsearch
     $found = array();
     for ($i = 0; $i < sizeof($terms); $i++) {
         $query = new \Elastica\Query\Fuzzy();
         $query->setField("content", $terms[$i]);
         $fuzzy_int = auto_fuzzy($terms[$i]);
         $query->setFieldOption("fuzziness", $fuzzy_int);
         array_push($found, $finder->find($query, 10000000));
     }
     // Choisir le type de recherche en fonction du nombre de combinaisons pour éviter l'explosion combinatoire
     $nb_combi = 1;
     foreach ($found as $tab) {
         $nb_combi = $nb_combi * sizeof($tab);
     }
     // J'effectue toutes les combinaisons possibles
     $combinations = array();
     if ($nb_combi < 1000) {
         for ($i = 0; $i < sizeof($found[0]); $i++) {
             array_push($combinations, $found[0][$i]->getContent());
         }
         for ($i = 1; $i < sizeof($found); $i++) {
             $temp = array();
             for ($j = 0; $j < sizeof($found[$i]); $j++) {
                 for ($k = 0; $k < sizeof($combinations); $k++) {
                     array_push($temp, $combinations[$k] . " " . $found[$i][$j]->getContent());
                 }
             }
             $combinations = $temp;
         }
     } else {
         // Je ne fais varier que un seul mot
         for ($i = 0; $i < sizeof($found); $i++) {
             for ($j = 0; $j < sizeof($found[$i]); $j++) {
                 $temp = "";
                 for ($k = 0; $k < sizeof($found); $k++) {
                     if ($i != $k) {
                         $temp = $temp . " " . $terms[$k];
                     } else {
                         $temp = $temp . " " . $found[$k][$j]->getContent();
                     }
                 }
                 array_push($combinations, substr($temp, 1));
             }
         }
     }
     // On cherche les combinaisons qui sont effectivement dans les documents
     $finder = $this->container->get('fos_elastica.finder.shlml.document');
     $results = array();
     for ($i = 0; $i < sizeof($combinations); $i++) {
         $query = new \Elastica\Query\Match();
         $query->setFieldQuery('content', $combinations[$i]);
         $query->setFieldType('content', 'phrase');
         if ($combinations[$i] == $selectedTerm) {
             $docs = $finder->find($query, 100);
         } else {
             $docs = $finder->find($query, 1);
         }
         if ($docs != null) {
             $results[$combinations[$i]] = array();
             for ($j = 0; $j < sizeof($docs); $j++) {
                 if ($this->get('security.context')->isGranted('ROLE_USER') || $docs[$j]->getPublic()) {
                     array_push($results[$combinations[$i]], $docs[$j]->getPath());
                 }
             }
         }
     }
     $wordList = array_keys($results);
     $selectedDocList = null;
     //var_dump($results);
     if (empty($results)) {
         $selectedDocList = array("mot_introuvable.pdf");
         $wordList = array($searchedTerm);
         if ($searchedTerm != $selectedTerm) {
             array_push($wordList, $selectedTerm);
         }
     } else {
         if (array_key_exists($searchedTerm, $results)) {
             unset($wordList[array_search($searchedTerm, $wordList)]);
             array_unshift($wordList, $searchedTerm);
             $selectedDocList = $results[$searchedTerm];
         } else {
             array_unshift($wordList, $searchedTerm);
         }
         if (array_key_exists($selectedTerm, $results)) {
             $selectedDocList = $results[$selectedTerm];
         }
         if ($selectedDocList == null) {
             $selectedDocList = array("mot_introuvable.pdf");
         }
     }
     $res = array($selectedDocList, $wordList);
     return $res;
 }
Exemplo n.º 23
0
 protected function addCollections($query, $filter)
 {
     //        foreach($filter->getProperties() as $k => $v){
     //            $method = 'get' . ucfirst($k);
     //            var_dump($method);
     //            if($filter->$method() != null && !$filter->$method()->isEmpty()){
     //                foreach ($filter->$method() as $item){
     //                    $term = new \Elastica\Query\Match();
     //                    $term->setFieldQuery($k . '.slug', $item->getSlug());
     //                    $query->addMust($term);
     //                }
     //            }
     //        }
     //        foreach($filter->getProperties() as $k => $v){
     //            $method = 'get' . ucfirst($k);
     //var_dump($filter);die();
     if ($filter->getFilters() != null && !empty($filter->getFilters())) {
         foreach ($filter->getFilters() as $item) {
             $term = new \Elastica\Query\Match();
             $term->setFieldQuery('placeFilterValues.slug', $item);
             $query->addMust($term);
         }
     }
     //        }
 }