/**
  * @param $id
  * @param $assignments
  * @param $arguments
  * @return mixed
  */
 protected function getTheRecordSpecified($id, $assignments)
 {
     $connection = $this->getConnection();
     $this->createQuery();
     $escapedID = $this->query->getHelper()->escapeTerm($id);
     $this->query->setQuery('id:' . $escapedID);
     try {
         /** @var \Solarium\Core\Query\Result\ResultInterface $selectResults */
         $selectResults = $connection->execute($this->query);
         if (count($selectResults) > 0) {
             $assignments['results'] = $selectResults;
             $resultSet = $selectResults->getDocuments();
             $assignments['document'] = $resultSet[0];
         } else {
             $message = sprintf('find: »detail« action query for id »%d« returned no results.', $id);
             LoggerUtility::logError($message, ['arguments' => $this->getRequestArguments()]);
         }
     } catch (HttpException $exception) {
         $message = 'find: Solr Exception (Timeout?)';
         LoggerUtility::logError($message, ['arguments' => $this->getRequestArguments(), 'exception' => LoggerUtility::exceptionToArray($exception)]);
     }
     return $assignments;
 }
Example #2
0
 /**
  * @depends testConstructorAndGetters
  *
  * @param PreCreateQuery $event
  */
 public function testSetAndGetQuery($event)
 {
     $query = new Query();
     $query->setQuery('test123');
     $event->setQuery($query);
     $this->assertEquals($query, $event->getQuery());
 }
Example #3
0
 public function testConstructorAndGetters()
 {
     $query = new Query();
     $query->setQuery('test123');
     $event = new PreCreateRequest($query);
     $this->assertEquals($query, $event->getQuery());
     return $event;
 }
/**
 * Lets modules alter the Solarium select query before executing it.
 *
 * @param \Solarium\QueryType\Select\Query\Query $solarium_query
 *   The Solarium query object, as generated from the Search API query.
 * @param \Drupal\search_api\Query\QueryInterface $query
 *   The Search API query object representing the executed search query.
 */
function hook_search_api_solr_query_alter(\Solarium\QueryType\Select\Query\Query $solarium_query, \Drupal\search_api\Query\QueryInterface $query)
{
    if ($query->getOption('foobar')) {
        // If the Search API query has a 'foobar' option, remove all sorting options
        // from the Solarium query.
        $solarium_query->clearSorts();
    }
}
Example #5
0
 public function testBuildWithTimeAllowed()
 {
     $query = new SelectQuery();
     $query->addParam('p1', 'v1');
     $query->addParam('p2', 'v2');
     $query->setTimeAllowed(1400);
     $request = $this->builder->build($query);
     $this->assertEquals('select?omitHeader=true&timeAllowed=1400&p1=v1&p2=v2&wt=json&json.nl=flat', urldecode($request->getUri()));
 }
 public function testBuildWithHeader()
 {
     $query = new SelectQuery();
     $query->addParam('p1', 'v1');
     $query->addParam('p2', 'v2');
     $query->setOmitHeader(false);
     $request = $this->builder->build($query);
     $this->assertEquals('select?omitHeader=false&p1=v1&p2=v2&wt=json', urldecode($request->getUri()));
 }
Example #7
0
 /**
  * Parse result data into result objects.
  *
  * @param Query             $query
  * @param GroupingComponent $grouping
  * @param array             $data
  *
  * @return Result
  */
 public function parse($query, $grouping, $data)
 {
     $groups = array();
     if (isset($data['grouped'])) {
         // parse field groups
         $valueResultClass = $grouping->getOption('resultvaluegroupclass');
         $documentClass = $query->getOption('documentclass');
         foreach ($grouping->getFields() as $field) {
             if (isset($data['grouped'][$field])) {
                 $result = $data['grouped'][$field];
                 $matches = isset($result['matches']) ? $result['matches'] : null;
                 $groupCount = isset($result['ngroups']) ? $result['ngroups'] : null;
                 $valueGroups = array();
                 foreach ($result['groups'] as $valueGroupResult) {
                     $value = isset($valueGroupResult['groupValue']) ? $valueGroupResult['groupValue'] : null;
                     $numFound = isset($valueGroupResult['doclist']['numFound']) ? $valueGroupResult['doclist']['numFound'] : null;
                     $start = isset($valueGroupResult['doclist']['start']) ? $valueGroupResult['doclist']['start'] : null;
                     $maxScore = isset($valueGroupResult['doclist']['maxScore']) ? $valueGroupResult['doclist']['maxScore'] : null;
                     // create document instances
                     $documents = array();
                     if (isset($valueGroupResult['doclist']['docs']) && is_array($valueGroupResult['doclist']['docs'])) {
                         foreach ($valueGroupResult['doclist']['docs'] as $doc) {
                             $documents[] = new $documentClass($doc);
                         }
                     }
                     $valueGroups[] = new $valueResultClass($value, $numFound, $start, $documents, $maxScore, $query);
                 }
                 $groups[$field] = new FieldGroup($matches, $groupCount, $valueGroups);
             }
         }
         // parse query groups
         $groupResultClass = $grouping->getOption('resultquerygroupclass');
         foreach ($grouping->getQueries() as $groupQuery) {
             if (isset($data['grouped'][$groupQuery])) {
                 $result = $data['grouped'][$groupQuery];
                 // get statistics
                 $matches = isset($result['matches']) ? $result['matches'] : null;
                 $numFound = isset($result['doclist']['numFound']) ? $result['doclist']['numFound'] : null;
                 $start = isset($result['doclist']['start']) ? $result['doclist']['start'] : null;
                 $maxScore = isset($result['doclist']['maxScore']) ? $result['doclist']['maxScore'] : null;
                 // create document instances
                 $documentClass = $query->getOption('documentclass');
                 $documents = array();
                 if (isset($result['doclist']['docs']) && is_array($result['doclist']['docs'])) {
                     foreach ($result['doclist']['docs'] as $doc) {
                         $documents[] = new $documentClass($doc);
                     }
                 }
                 // create a group result object
                 $group = new $groupResultClass($matches, $numFound, $start, $maxScore, $documents, $query);
                 $groups[$groupQuery] = $group;
             }
         }
     }
     return new Result($groups);
 }
Example #8
0
 public function setUp()
 {
     $this->parser = new Parser();
     $this->query = new Query();
     $this->grouping = $this->query->getGrouping();
     $this->grouping->addField('fieldA');
     $this->grouping->addQuery('cat:1');
     $data = array('grouped' => array('fieldA' => array('matches' => 25, 'ngroups' => 12, 'groups' => array(array('groupValue' => 'test value', 'doclist' => array('numFound' => 13, 'docs' => array(array('id' => 1, 'name' => 'test')))))), 'cat:1' => array('matches' => 40, 'doclist' => array('numFound' => 22, 'docs' => array(array('id' => 2, 'name' => 'dummy2'), array('id' => 5, 'name' => 'dummy5'))))));
     $this->result = $this->parser->parse($this->query, $this->grouping, $data);
 }
 public function testConstructorAndGetters()
 {
     $query = new Query();
     $query->setQuery('test123');
     $request = new Request();
     $request->addParam('testparam', 'test value');
     $event = new PostCreateRequest($query, $request);
     $this->assertEquals($query, $event->getQuery());
     $this->assertEquals($request, $event->getRequest());
 }
 public function testConstructorAndGetters()
 {
     $type = 'testtype';
     $options = array('key' => 'value');
     $query = new Query();
     $query->setQuery('test123');
     $event = new PostCreateQuery($type, $options, $query);
     $this->assertEquals($type, $event->getQueryType());
     $this->assertEquals($options, $event->getOptions());
     $this->assertEquals($query, $event->getQuery());
 }
Example #11
0
 public function applySorting($sorting)
 {
     $this->ensureNotExecuted();
     foreach ($sorting as $field => $order) {
         if (is_numeric($field)) {
             $field = $order;
             $order = 'asc';
         }
         $this->selectQuery->addSort($field, $order);
     }
 }
 public function testParseWithoutNumFound()
 {
     $data = array('response' => array('docs' => array(array('fieldA' => 1, 'fieldB' => 'Test'), array('fieldA' => 2, 'fieldB' => 'Test2'))), 'responseHeader' => array('status' => 1, 'QTime' => 13));
     $query = new Query(array('documentclass' => 'Solarium\\QueryType\\Update\\Query\\Document\\Document'));
     $query->getFacetSet();
     $resultStub = $this->getMock('Solarium\\QueryType\\Select\\Result\\Result', array(), array(), '', false);
     $resultStub->expects($this->once())->method('getData')->will($this->returnValue($data));
     $resultStub->expects($this->once())->method('getQuery')->will($this->returnValue($query));
     $parser = new ResponseParser();
     $result = $parser->parse($resultStub);
     $this->assertEquals(1, $result['status']);
     $this->assertEquals(13, $result['queryTime']);
     $this->assertEquals(null, $result['numfound']);
 }
Example #13
0
 /**
  * Fetch the next set of results
  *
  * @return void
  */
 protected function fetchNext()
 {
     $this->query->setStart($this->start)->setRows($this->getPrefetch());
     $this->result = $this->client->execute($this->query, $this->getOption('endpoint'));
     $this->documents = $this->result->getDocuments();
     $this->start += $this->getPrefetch();
 }
Example #14
0
 public function testWithTags()
 {
     $this->query->setTags(array('t1', 't2'));
     $this->query->setQuery('cat:1');
     $request = $this->builder->build($this->query);
     $this->assertEquals('{!tag=t1,t2}cat:1', $request->getParam('q'));
 }
Example #15
0
 /**
  * Prepare query for to run
  * 
  * @param array $fields to be selected
  * 
  * @return self
  */
 public function prepare(array $fields = null)
 {
     if ($fields !== null) {
         $this->query->setFields($fields);
     }
     $this->query->setQuery($this->rawQuery);
     return $this;
 }
 /**
  * @param Query $query
  * @param callable $transform
  * @param null $readEndpoint
  * @param null $writeEndpoint
  * @param bool $commit
  * @internal param null $endpoint
  */
 public function updateBufferedNoPlugin(Query $query, callable $transform, $readEndpoint = null, $writeEndpoint = null, $commit = true)
 {
     $nbRows = count($this->solarium->execute($query->setRows(0), $readEndpoint));
     $update = $this->solarium->createUpdate();
     for ($offset = 0; $offset <= $nbRows; $offset += $this->buffer) {
         $query->setStart($offset)->setRows($this->buffer);
         $documents = $this->solarium->execute($query, $readEndpoint);
         foreach ($documents as $document) {
             $update->addDocument($transform($document));
         }
         $this->solarium->execute($update, $writeEndpoint);
         $update = $this->solarium->createUpdate();
     }
     if ($nbRows > 0 && $commit === true) {
         $this->solarium->execute($update->addCommit(), $writeEndpoint);
     }
 }
 /**
  * Parse result data into result objects
  *
  * @param  Query                 $query
  * @param  MoreLikeThisComponent $moreLikeThis
  * @param  array                 $data
  * @return MoreLikeThis
  */
 public function parse($query, $moreLikeThis, $data)
 {
     $results = array();
     if (isset($data['moreLikeThis'])) {
         $documentClass = $query->getOption('documentclass');
         $searchResults = $data['moreLikeThis'];
         foreach ($searchResults as $key => $result) {
             // create document instances
             $docs = array();
             foreach ($result['docs'] as $fields) {
                 $docs[] = new $documentClass($fields);
             }
             $results[$key] = new Result($result['numFound'], $result['maxScore'], $docs);
         }
     }
     return new MoreLikeThisResult($results);
 }
Example #18
0
 public function testPostCreateRequest()
 {
     // create a very long query
     $fq = '';
     for ($i = 1; $i <= 1000; $i++) {
         $fq .= ' OR price:' . $i;
     }
     $fq = substr($fq, 4);
     $this->query->createFilterQuery('fq')->setQuery($fq);
     $requestOutput = $this->client->createRequest($this->query);
     $requestInput = clone $requestOutput;
     $event = new PostCreateRequestEvent($this->query, $requestOutput);
     $this->plugin->postCreateRequest($event);
     $this->assertEquals(Request::METHOD_GET, $requestInput->getMethod());
     $this->assertEquals(Request::METHOD_POST, $requestOutput->getMethod());
     $this->assertEquals($requestInput->getQueryString(), $requestOutput->getRawData());
     $this->assertEquals('', $requestOutput->getQueryString());
 }
 protected function init()
 {
     parent::init();
     // set a query (all prices starting from 12)
     $this->setQuery('price:[12 TO *]');
     // set start and rows param (comparable to SQL limit) using fluent interface
     $this->setStart(2)->setRows(20);
     // set fields to fetch (this overrides the default setting 'all fields')
     $this->setFields(array('id', 'name', 'price'));
     // sort the results by price ascending
     $this->addSort('price', self::SORT_ASC);
 }
Example #20
0
 protected function init()
 {
     parent::init();
     // basic params
     $this->setQuery('*:*');
     $this->setStart(2)->setRows(20);
     $this->setFields(array('id', 'name', 'price'));
     $this->addSort('price', self::SORT_ASC);
     // create a facet field instance and set options
     $facetSet = $this->getFacetSet();
     $facetSet->createFacetField('stock')->setField('inStock');
 }
Example #21
0
 protected function createFilterQuery(Query $query)
 {
     if ($this->expression === NULL) {
         return NULL;
     }
     $this->expression = $this->doInverse($this->expression);
     if (($queryString = $this->expression->build()) !== NULL) {
         $key = $this->key ?: md5($queryString);
         $fq = $query->createFilterQuery($key)->setQuery($queryString);
         if ($this->expression instanceof FieldExpression) {
             $fq->addTag($this->expression->getField());
         }
         if ($this->key !== NULL) {
             $fq->addTag($this->key);
         }
     } else {
         $fq = NULL;
     }
     $this->expression = $this->doInverse($this->expression);
     //return to original state
     return $fq;
 }
Example #22
0
 public function testCreateQueryWithOverridingPlugin()
 {
     $type = Client::QUERY_SELECT;
     $options = array('query' => 'test789');
     $expectedQuery = new SelectQuery();
     $expectedQuery->setQuery('test789');
     $expectedEvent = new PreCreateQueryEvent($type, $options);
     $expectedEvent->setDispatcher($this->client->getEventDispatcher());
     $expectedEvent->setName(Events::PRE_CREATE_QUERY);
     $test = $this;
     $this->client->getEventDispatcher()->addListener(Events::PRE_CREATE_QUERY, function (PreCreateQueryEvent $event) use($test, $expectedQuery, $expectedEvent) {
         $test->assertEquals($expectedEvent, $event);
         $event->setQuery($expectedQuery);
     });
     $returnedQuery = $this->client->createQuery($type, $options);
     $this->assertEquals($expectedQuery, $returnedQuery);
 }
Example #23
0
 public function testSetTags()
 {
     $this->query->addTags(array('t1', 't2'));
     $this->query->setTags(array('t3', 't4'));
     $this->assertEquals(array('t3', 't4'), $this->query->getTags());
 }
Example #24
0
 /**
  * Add a facet result for a range facet
  *
  * @param  Query            $query
  * @param  QueryFacetRange  $facet
  * @param  array            $data
  * @return ResultFacetRange
  */
 protected function facetRange($query, $facet, $data)
 {
     $key = $facet->getKey();
     if (isset($data['facet_counts']['facet_ranges'][$key])) {
         $data = $data['facet_counts']['facet_ranges'][$key];
         $before = isset($data['before']) ? $data['before'] : null;
         $after = isset($data['after']) ? $data['after'] : null;
         $between = isset($data['between']) ? $data['between'] : null;
         $start = isset($data['start']) ? $data['start'] : null;
         $end = isset($data['end']) ? $data['end'] : null;
         $gap = isset($data['gap']) ? $data['gap'] : null;
         if ($query->getResponseWriter() == $query::WT_JSON) {
             $data['counts'] = $this->convertToKeyValueArray($data['counts']);
         }
         return new ResultFacetRange($data['counts'], $before, $after, $between, $start, $end, $gap);
     }
 }
Example #25
0
 public function setGrouping(Query $solarium_query, QueryInterface $query, $grouping_options = array(), $index_fields = array(), $field_names = array())
 {
     $group_params['group'] = 'true';
     // We always want the number of groups returned so that we get pagers done
     // right.
     $group_params['group.ngroups'] = 'true';
     if (!empty($grouping_options['truncate'])) {
         $group_params['group.truncate'] = 'true';
     }
     if (!empty($grouping_options['group_facet'])) {
         $group_params['group.facet'] = 'true';
     }
     foreach ($grouping_options['fields'] as $collapse_field) {
         $type = $index_fields[$collapse_field]['type'];
         // Only single-valued fields are supported.
         if ($this->getSolrVersion() < 4) {
             // For Solr 3.x, only string and boolean fields are supported.
             if (!SearchApiUtility::isTextType($type, array('string', 'boolean', 'uri'))) {
                 $warnings[] = $this->t('Grouping is not supported for field @field. ' . 'Only single-valued fields of type "String", "Boolean" or "URI" are supported.', array('@field' => $index_fields[$collapse_field]['name']));
                 continue;
             }
         } else {
             if (SearchApiUtility::isTextType($type)) {
                 $warnings[] = $this->t('Grouping is not supported for field @field. ' . 'Only single-valued fields not indexed as "Fulltext" are supported.', array('@field' => $index_fields[$collapse_field]['name']));
                 continue;
             }
         }
         $group_params['group.field'][] = $field_names[$collapse_field];
     }
     if (empty($group_params['group.field'])) {
         unset($group_params);
     } else {
         if (!empty($grouping_options['group_sort'])) {
             foreach ($grouping_options['group_sort'] as $group_sort_field => $order) {
                 if (isset($fields[$group_sort_field])) {
                     $f = $fields[$group_sort_field];
                     if (substr($f, 0, 3) == 'ss_') {
                         $f = 'sort_' . substr($f, 3);
                     }
                     $order = strtolower($order);
                     $group_params['group.sort'][] = $f . ' ' . $order;
                 }
             }
             if (!empty($group_params['group.sort'])) {
                 $group_params['group.sort'] = implode(', ', $group_params['group.sort']);
             }
         }
         if (!empty($grouping_options['group_limit']) && $grouping_options['group_limit'] != 1) {
             $group_params['group.limit'] = $grouping_options['group_limit'];
         }
     }
     foreach ($group_params as $param_id => $param_value) {
         $solarium_query->addParam($param_id, $param_value);
     }
 }
Example #26
0
 public function testJoinDereferenced()
 {
     $this->assertEquals('{!join from=$deref_1 to=$deref_2}', $this->helper->join('manu_id', 'id', true));
     $this->assertEquals(array('deref_1' => 'manu_id', 'deref_2' => 'id'), $this->query->getParams());
 }
 /**
  * Set the query keywords.
  *
  * @param Query $solarium_query
  * @param string $keywords
  */
 private function set_keywords(Query $solarium_query, $keywords)
 {
     $solarium_query->setQuery(WpSolrSchema::_FIELD_NAME_DEFAULT_QUERY . ':' . !empty($keywords) ? $keywords : '*');
 }
 /**
  * @param \Solarium\QueryType\Select\Query\Query $select
  * @return string
  */
 public function getSolrQueryStr($select)
 {
     foreach ($this->krits as $krit) {
         switch ($krit["typ"]) {
             case "betreff":
                 $helper = $select->getHelper();
                 return "antrag_betreff:" . $helper->escapeTerm($krit["suchbegriff"]);
                 break;
             case "antrag_typ":
                 return "antrag_typ:" . $krit["suchbegriff"];
                 break;
             case "antrag_wahlperiode":
                 return "antrag_wahlperiode:" . $krit["suchbegriff"];
                 break;
             case "ba":
                 return "dokument_bas:" . $krit["ba_nr"];
                 break;
             case "volltext":
                 return $krit["suchbegriff"];
                 break;
             case "geo":
                 $helper = $select->getHelper();
                 return $helper->geofilt("geo", $krit["lat"], $krit["lng"], $krit["radius"] / 1000);
                 break;
             case "referat":
                 return "referat_id:" . $krit["referat_id"];
                 break;
             case "antrag_nr":
                 return "*" . $krit["antrag_nr"] . "*";
                 break;
         }
     }
     return "";
 }
Example #29
0
 public static function addNoExcludeFacet(Query $query, $key)
 {
     return $query->getFacetSet()->createFacetField(['field' => $key, 'key' => $key . self::NO_EXCLUDE_SUFFIX]);
 }
Example #30
0
 /**
  * Parse collation data into a result object
  *
  * @param  Query     $queryObject
  * @param  array     $values
  * @return Collation[]
  */
 protected function parseCollation($queryObject, $values)
 {
     $collations = array();
     if (is_string($values)) {
         $collations[] = new Collation($values, null, array());
     } elseif (is_array($values) && isset($values[0]) && is_string($values[0]) && $values[0] !== 'collationQuery') {
         foreach ($values as $value) {
             $collations[] = new Collation($value, null, array());
         }
     } else {
         if ($queryObject->getResponseWriter() == $queryObject::WT_JSON) {
             if (is_array(current($values))) {
                 foreach ($values as $key => $value) {
                     $values[$key] = $this->convertToKeyValueArray($value);
                 }
             } else {
                 $values = array($this->convertToKeyValueArray($values));
             }
         }
         foreach ($values as $collationValue) {
             $query = null;
             $hits = null;
             $correctionResult = null;
             foreach ($collationValue as $key => $value) {
                 switch ($key) {
                     case 'collationQuery':
                         $query = $value;
                         break;
                     case 'hits':
                         $hits = $value;
                         break;
                     case 'misspellingsAndCorrections':
                         $correctionResult = $value;
                         break;
                 }
             }
             $corrections = array();
             if ($correctionResult !== null) {
                 if ($queryObject->getResponseWriter() == $queryObject::WT_JSON) {
                     $correctionResult = $this->convertToKeyValueArray($correctionResult);
                 }
                 foreach ($correctionResult as $input => $correction) {
                     $corrections[$input] = $correction;
                 }
             }
             $collations[] = new Collation($query, $hits, $corrections);
         }
     }
     return $collations;
 }