/** * @param Pimple\Container $container [description] */ public function register(Container $container) { $container['solr'] = function ($c) { if (isset($c['config']['solr']['endpoint'])) { $solrService = new \Solarium\Client($c['config']['solr']); $solrService->setDefaultEndpoint('localhost'); return $solrService; } else { return null; } }; $container['solr.ready'] = function ($c) { if (null !== $c['solr']) { // create a ping query $ping = $c['solr']->createPing(); // execute the ping query try { $c['solr']->ping($ping); return true; } catch (\Exception $e) { return false; } } else { return false; } }; $container['solr.search.nodeSource'] = function ($c) { if ($c['solr.ready']) { return new FullTextSearchHandler($c['solr'], $c['em']); } else { return null; } }; return $container; }
protected function execute(InputInterface $input, OutputInterface $output) { $client = new \Solarium\Client($this->getContainer()->getParameter('xrow_ez_publish_solr_docs.solrserverconfig')); try { $output->writeln("Creating a new Article and do commit."); $repository = $this->getContainer()->get('ezpublish.solrapi.repository'); $contentService = $repository->getContentService(); $locationService = $repository->getLocationService(); $contentTypeService = $repository->getContentTypeService(); $repository->setCurrentUser($repository->getUserService()->loadUser(14)); $parentLocationId = 2; // instantiate a location create struct from the parent location $locationCreateStruct = $locationService->newLocationCreateStruct($parentLocationId); $contentTypeIdentifier = "s_artikel"; $contentType = $contentTypeService->loadContentTypeByIdentifier($contentTypeIdentifier); $contentCreateStruct = $contentService->newContentCreateStruct($contentType, 'ger-DE'); $titel = "Ein neuer Artikel " . rand(2, 9876987); $veroeffentlichungsdatum = 1409131877; $vorspann = "<p>Dieser Artikel hat einen relativ langen Vorspann. Wie eigentlich auch immer.</p>"; $haupttext = "<p>Dieser Artikel hat einen relativ <b>kurzen</b> Haupttext. Dieser Artikel hat einen relativ <b>kurzen</b> Haupttext.\nDieser Artikel hat einen relativ <b>kurzen</b> Haupttext. Dieser Artikel hat einen relativ <b>kurzen</b> Haupttext. Dieser Artikel hat einen relativ <b>kurzen</b> Haupttext.\nDieser Artikel hat einen relativ <b>kurzen</b> Haupttext. Dieser Artikel hat einen relativ <b>kurzen</b> Haupttext. Dieser Artikel hat einen relativ <b>kurzen</b> Haupttext. Dieser Artikel hat einen relativ <b>kurzen</b> Haupttext. \nDieser Artikel hat einen relativ <b>kurzen</b> Haupttext. \n</p>"; $schlagwoerter = array("Solr", "neuer Artikel", "Gewitter"); $rubriken = array("Nachrichten", "Meinung"); $url = "http://www.test.de/Nachrichten/Lokales/Hannover"; $contentCreateStruct->setField('titel', $titel); $contentCreateStruct->setField('veroeffentlichungsdatum', $veroeffentlichungsdatum); $contentCreateStruct->setField('vorspann', $vorspann); $contentCreateStruct->setField('haupttext', $haupttext); $contentCreateStruct->setField('schlagwoerter', $schlagwoerter); $contentCreateStruct->setField('rubriken', $rubriken); $contentCreateStruct->setField('url', $url); $draft = $contentService->createContent($contentCreateStruct, array($locationCreateStruct)); $update = $client->createUpdate(); $update->addCommit(); $result = $client->update($update); #$content = $contentService->publishVersion( $draft->versionInfo ); $output->writeln("Done."); } catch (\eZ\Publish\API\Repository\Exceptions\NotFoundException $e) { $output->writeln($e->getMessage()); } catch (\eZ\Publish\API\Repository\Exceptions\ContentFieldValidationException $e) { $output->writeln($e->getMessage()); } catch (\eZ\Publish\API\Repository\Exceptions\ContentValidationException $e) { $output->writeln($e->getMessage()); } }
<?php require __DIR__ . '/init.php'; htmlHeader(); // This example shows how to manually execute the query flow. // By doing this manually you can customize data in between any step (although a plugin might be better for this) // And you can use only a part of the flow. You could for instance use the query object and request builder, // but execute the request in your own code. // create a client instance $client = new Solarium\Client($config); // create a select query instance $query = $client->createSelect(); // manually create a request for the query $request = $client->createRequest($query); // you can now use the request object for getting an uri (ie. to use in you own code) // or you could modify the request object echo 'Request URI: ' . $request->getUri() . '<br/>'; // you can still execute the request using the client and get a 'raw' response object $response = $client->executeRequest($request); // and finally you can convert the response into a result $result = $client->createResult($query, $response); // display the total number of documents found by solr echo 'NumFound: ' . $result->getNumFound(); // show documents using the resultset iterator foreach ($result as $document) { echo '<hr/><table>'; // the documents are also iterable, to get all fields foreach ($document as $field => $value) { // this converts multivalue fields to a comma-separated string if (is_array($value)) { $value = implode(', ', $value);
<?php require __DIR__ . '/init.php'; htmlHeader(); // create a client instance $client = new Solarium\Client($config); // get a select query instance $query = $client->createQuery($client::QUERY_SELECT); // this executes the query and returns the result $resultset = $client->execute($query); // display the total number of documents found by solr echo 'NumFound: ' . $resultset->getNumFound(); // show documents using the resultset iterator foreach ($resultset as $document) { echo '<hr/><table>'; // the documents are also iterable, to get all fields foreach ($document as $field => $value) { // this converts multivalue fields to a comma-separated string if (is_array($value)) { $value = implode(', ', $value); } echo '<tr><th>' . $field . '</th><td>' . $value . '</td></tr>'; } echo '</table>'; } htmlFooter();
{ $this->timer('postExecute'); } public function preCreateQuery() { $this->timer('preCreateResult'); } public function postCreateQuery() { $this->timer('postCreateResult'); } } htmlHeader(); // create a client instance and register the plugin $plugin = new BasicDebug(); $client = new Solarium\Client($config); $client->registerPlugin('debugger', $plugin); // execute a select query and display the results $query = $client->createSelect(); $resultset = $client->select($query); echo 'NumFound: ' . $resultset->getNumFound(); foreach ($resultset as $document) { echo '<hr/><table>'; foreach ($document as $field => $value) { if (is_array($value)) { $value = implode(', ', $value); } echo '<tr><th>' . $field . '</th><td>' . $value . '</td></tr>'; } echo '</table>'; }
/** * Finds content objects for the given query. * * @todo define structs for the field filters * * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException if query is not valid * * @param \eZ\Publish\API\Repository\Values\Content\Query $query * @param array $fieldFilters - a map of filters for the returned fields. * Currently supported: <code>array("languages" => array(<language1>,..))</code>. * @param boolean $filterOnUserPermissions if true only the objects which is the user allowed to read are returned. * * @return \eZ\Publish\API\Repository\Values\Content\Search\SearchResult */ public function findContent(Query $query, array $fieldFilters = array(), $filterOnUserPermissions = true) { $solrserverconfig = Globals::getSolrServerConfig(); $solrglobalconfig = Globals::getSolrGlobalConfig(); $client = new \Solarium\Client($solrserverconfig); $query = clone $query; $query->filter = $query->filter ?: new Criterion\MatchAll(); $this->validateContentCriteria(array($query->query), "\$query"); $this->validateContentCriteria(array($query->filter), "\$query"); $this->validateContentSortClauses($query); $this->validateSortClauses($query); if ($query->limit === null) { $query->limit = 2; } $criterion = $query->query; $queries = array("" . $criterion->value); foreach ($criterion->boost as $field => $boost) { $fields = $this->fieldMap->getFieldTypes($criterion); if (!isset($fields[$field])) { continue; } foreach ($fields[$field] as $fieldNames) { foreach ($fieldNames as $fieldName) { $queries[] = $fieldName . ":" . $criterion->value . "^" . $boost; } } } $abfrage = "(" . implode(') OR (', array_map(function ($search) use($criterion) { return $search . ($criterion->fuzziness < 1 ? sprintf("~%.1f", $criterion->fuzziness) : ""); }, $queries)) . ")"; if ($query->offset !== null) { $parameters["start"] = $query->offset; } if ($query->limit !== null) { $parameters["rows"] = $query->limit; } // @todo: Extract method $solrquery = $client->createQuery($client::QUERY_SELECT); $solrquery->createFilterQuery('solrdocs')->setQuery("is_solrdoc_b:true AND " . $abfrage); $result = $client->select($solrquery); // @todo: Extract method $result = new SearchResult(array('time' => $data->responseHeader->QTime / 1000, 'maxScore' => $data->response->maxScore, 'totalCount' => $data->response->numFound)); foreach ($result as $doc) { $searchHit = new SearchHit(array('score' => $doc->score, 'valueObject' => $doc)); #'valueObject' => $this->contentHandler->load( $doc->id, $doc->version_id ) $result->searchHits[] = $searchHit; } if (isset($data->facet_counts)) { foreach ($data->facet_counts->facet_fields as $field => $facet) { $result->facets[] = $this->facetBuilderVisitor->map($field, $facet); } } var_dump($result); die("Stop"); return $result; }
<?php require_once 'Zend/Loader/Autoloader.php'; $loader = Zend_Loader_Autoloader::getInstance(); require __DIR__ . '/init.php'; htmlHeader(); // create a client instance $client = new Solarium\Client($config); // set the adapter to curl $client->setAdapter('Solarium\\Core\\Client\\Adapter\\Http'); // get a select query instance $query = $client->createSelect(); // this executes the query and returns the result $resultset = $client->select($query); // display the total number of documents found by solr echo 'NumFound: ' . $resultset->getNumFound(); // show documents using the resultset iterator foreach ($resultset as $document) { echo '<hr/><table>'; // the documents are also iterable, to get all fields foreach ($document as $field => $value) { // this converts multivalue fields to a comma-separated string if (is_array($value)) { $value = implode(', ', $value); } echo '<tr><th>' . $field . '</th><td>' . $value . '</td></tr>'; } echo '</table>'; } htmlFooter();
<?php require __DIR__ . '/init.php'; htmlHeader(); // create a client instance $client = new Solarium\Client($config); // enable the filter plugin and get a query instance $filter = $client->getPlugin('minimumscorefilter'); $query = $client->createQuery($filter::QUERY_TYPE); $query->setRows(50); $query->setFields(array('id', 'name', 'score')); $query->setQuery('memory'); $query->setFilterRatio(0.8); $query->setFilterMode($query::FILTER_MODE_MARK); // get grouping component and set a field to group by $groupComponent = $query->getGrouping(); $groupComponent->addField('inStock'); // maximum number of items per group $groupComponent->setLimit(10); // get a group count $groupComponent->setNumberOfGroups(true); // this executes the query and returns the result $resultset = $client->select($query); $groups = $resultset->getGrouping(); foreach ($groups as $groupKey => $fieldGroup) { echo '<h1>' . $groupKey . '</h1>'; echo 'Matches: ' . $fieldGroup->getMatches() . '<br/>'; echo 'Number of groups: ' . $fieldGroup->getNumberOfGroups(); foreach ($fieldGroup as $valueGroup) { echo '<h2>' . (int) $valueGroup->getValue() . '</h2>'; foreach ($valueGroup as $document) {
<?php require __DIR__ . '/init.php'; htmlHeader(); // create a client instance and autoload the postbigrequest plugin $client = new Solarium\Client($config); $client->getPlugin('postbigrequest'); // create a basic query to execute $query = $client->createSelect(); // add a huge filterquery to create a very long query string // note: normally you would use a range for this, it's just an easy way to create a very big querystring as a test $fq = ''; for ($i = 1; $i <= 1000; $i++) { $fq .= ' OR price:' . $i; } $fq = substr($fq, 4); $query->createFilterQuery('fq')->setQuery($fq); // without the plugin this query would fail as it is bigger than the default servlet container header buffer $resultset = $client->select($query); // display the total number of documents found by solr echo 'NumFound: ' . $resultset->getNumFound(); // show documents using the resultset iterator foreach ($resultset as $document) { echo '<hr/><table>'; // the documents are also iterable, to get all fields foreach ($document as $field => $value) { // this converts multivalue fields to a comma-separated string if (is_array($value)) { $value = implode(', ', $value); } echo '<tr><th>' . $field . '</th><td>' . $value . '</td></tr>';
<?php require __DIR__ . '/init.php'; htmlHeader(); // create a client instance $client = new Solarium\Client($config); // get an analysis document query $query = $client->createAnalysisField(); $query->setShowMatch(true); $query->setFieldName('cat,title'); $query->setFieldType('text_general'); $query->setFieldValue('Apple 60 GB iPod with Video Playback Black'); $query->setQuery('ipod'); // this executes the query and returns the result $results = $client->analyze($query); // show the results foreach ($results as $result) { echo '<hr><h2>Result list: ' . $result->getName() . '</h2>'; foreach ($result as $item) { echo '<h3>Item: ' . $item->getName() . '</h3>'; $indexAnalysis = $item->getIndexAnalysis(); if (!empty($indexAnalysis)) { echo '<h4>Index Analysis</h4>'; foreach ($indexAnalysis as $classes) { echo '<h5>' . $classes->getName() . '</h5>'; foreach ($classes as $result) { echo 'Text: ' . $result->getText() . '<br/>'; echo 'Raw text: ' . $result->getRawText() . '<br/>'; echo 'Start: ' . $result->getStart() . '<br/>'; echo 'End: ' . $result->getEnd() . '<br/>'; echo 'Position: ' . $result->getPosition() . '<br/>';
<?php require __DIR__ . '/init.php'; htmlHeader(); // create a client instance $client = new Solarium\Client($config); // get a suggester query instance $query = $client->createSuggester(); $query->setQuery('ap ip v'); //multiple terms $query->setDictionary('suggest'); $query->setOnlyMorePopular(true); $query->setCount(10); $query->setCollate(true); // this executes the query and returns the result $resultset = $client->suggester($query); echo '<b>Query:</b> ' . $query->getQuery() . '<hr/>'; // display results for each term foreach ($resultset as $term => $termResult) { echo '<h3>' . $term . '</h3>'; echo 'NumFound: ' . $termResult->getNumFound() . '<br/>'; echo 'StartOffset: ' . $termResult->getStartOffset() . '<br/>'; echo 'EndOffset: ' . $termResult->getEndOffset() . '<br/>'; echo 'Suggestions:<br/>'; foreach ($termResult as $result) { echo '- ' . $result . '<br/>'; } echo '<hr/>'; } // display collation echo 'Collation: ' . $resultset->getCollation();
<?php require __DIR__ . '/init.php'; // check solarium version available echo 'Solarium library version: ' . Solarium\Client::VERSION . ' - '; // create a client instance $client = new Solarium\Client($config); // create a ping query $ping = $client->createPing(); // execute the ping query try { $result = $client->ping($ping); echo 'Ping query successful'; echo '<br/><pre>'; var_dump($result->getData()); echo '</pre>'; } catch (Solarium\Exception $e) { echo 'Ping query failed'; }
<?php require __DIR__ . '/init.php'; htmlHeader(); // create a client instance $client = new Solarium\Client($config); // get an extract query instance and add settings $query = $client->createExtract(); $query->addFieldMapping('content', 'text'); $query->setUprefix('attr_'); $query->setFile(__DIR__ . '/index.html'); $query->setCommit(true); $query->setOmitHeader(false); // add document $doc = $query->createDocument(); $doc->id = 'extract-test'; $doc->some = 'more fields'; $query->setDocument($doc); // this executes the query and returns the result $result = $client->extract($query); echo '<b>Extract query executed</b><br/>'; echo 'Query status: ' . $result->getStatus() . '<br/>'; echo 'Query time: ' . $result->getQueryTime(); htmlFooter();
protected function execute(InputInterface $input, OutputInterface $output) { $client = new \Solarium\Client($this->getContainer()->getParameter('xrow_ez_publish_solr_docs.solrserverconfig')); try { $repository = $this->getContainer()->get('ezpublish.solrapi.repository'); $contentService = $repository->getContentService(); $locationService = $repository->getLocationService(); $contentTypeService = $repository->getContentTypeService(); $repository->setCurrentUser($repository->getUserService()->loadUser(14)); $parentLocationId = 2; // instantiate a location create struct from the parent location $locationCreateStruct = $locationService->newLocationCreateStruct($parentLocationId); # Creating s_artikel $output->writeln("Creating a new Article and do commit."); $contentTypeIdentifier = "s_artikel"; $contentType = $contentTypeService->loadContentTypeByIdentifier($contentTypeIdentifier); $contentCreateStruct = $contentService->newContentCreateStruct($contentType, 'ger-DE'); $titel = "Circus Halligalli " . rand(2, 9876987); $veroeffentlichungsdatum = 1409131877; $vorspann = "<p>Es war einmal in einem tiefen dunklen Wald..</p>"; $haupttext = "<p>Hier lebte die Bärenfamilie..</p>"; $schlagwoerter = array("Bär", "Wald"); $rubriken = array("News", "Winter"); $url = "http://www.halligalli.de/Nachrichten/Lokales/"; $contentCreateStruct->setField('titel', $titel); $contentCreateStruct->setField('veroeffentlichungsdatum', $veroeffentlichungsdatum); $contentCreateStruct->setField('vorspann', $vorspann); $contentCreateStruct->setField('haupttext', $haupttext); $contentCreateStruct->setField('schlagwoerter', $schlagwoerter); $contentCreateStruct->setField('rubriken', $rubriken); $contentCreateStruct->setField('url', $url); $draft = $contentService->createContent($contentCreateStruct, array($locationCreateStruct)); $update = $client->createUpdate(); $update->addCommit(); $result = $client->update($update); $output->writeln("Artikel erzeugt."); # Creating s_artikel $output->writeln("Creating a new Foto and do commit."); $contentTypeIdentifier = "s_foto"; $contentType = $contentTypeService->loadContentTypeByIdentifier($contentTypeIdentifier); $contentCreateStruct = $contentService->newContentCreateStruct($contentType, 'ger-DE'); $data = array(); $data["veroeffentlichungsdatum"] = 1409141879; $data["titel"] = "Ein neues Foto Nr." . rand(2, 9876987); $data["schlagwoerter"] = array("Fotolia", "Wald"); $data["rubriken"] = array("Fotostrecke", "Sommer"); $data["url"] = "http://www.xrow.de/Keyword"; $contentCreateStruct->setField('veroeffentlichungsdatum', $data["veroeffentlichungsdatum"]); $contentCreateStruct->setField('titel', $data["titel"]); $contentCreateStruct->setField('schlagwoerter', $data["schlagwoerter"]); $contentCreateStruct->setField('rubriken', $data["rubriken"]); $contentCreateStruct->setField('url', $data["url"]); $draft = $contentService->createContent($contentCreateStruct, array($locationCreateStruct)); $update = $client->createUpdate(); $update->addCommit(); $result = $client->update($update); $output->writeln("Foto erzeugt erzeugt."); # Creating s_artikel $output->writeln("Creating a new Veranstaltung and do commit."); $contentTypeIdentifier = "s_veranstaltung"; $contentType = $contentTypeService->loadContentTypeByIdentifier($contentTypeIdentifier); $contentCreateStruct = $contentService->newContentCreateStruct($contentType, 'ger-DE'); $data = array(); $data["veranstaltungsbeginn"] = 1409141879; $data["veranstaltungsende"] = 1409241879; $data["titel"] = "Eine neue Veranstaltung Nr." . rand(2, 9876987); $data["teaser"] = "Veranstaltung im neuen Rathaus"; $data["haupttext"] = "<p>Im neuen Rathaus findet am 3.10.2014 eine ganz tolle Veranstaltung statt. Seien Sie dabei.</p>"; $data["homepage_veranstaltung"] = "http://www.hannover.de"; $data["homepage_staette"] = "http://www.neuesrathaus-hannover.de"; $data["staette"] = array("Neues Rathaus"); $data["stadt"] = "Hannover"; $data["geodaten"] = array("longitude" => 42.117629, "latitude" => -70.956766, "address" => "Abington, MA"); $data["rubriken"] = array("Veranstaltung", "Herbst"); $data["url"] = "http://www.veranstaltung.de"; $data["bild_url"] = "http://upload.wikimedia.org/wikipedia/commons/c/ce/Neues_Rathaus_Hannover_001.JPG"; $contentCreateStruct->setField('veranstaltungsbeginn', $data["veranstaltungsbeginn"]); $contentCreateStruct->setField('veranstaltungsende', $data["veranstaltungsende"]); $contentCreateStruct->setField('titel', $data["titel"]); $contentCreateStruct->setField('teaser', $data["teaser"]); $contentCreateStruct->setField('haupttext', $data["haupttext"]); $contentCreateStruct->setField('homepage_veranstaltung', $data["homepage_veranstaltung"]); $contentCreateStruct->setField('homepage_staette', $data["homepage_staette"]); $contentCreateStruct->setField('staette', $data["staette"]); $contentCreateStruct->setField('stadt', $data["stadt"]); $contentCreateStruct->setField('geodaten', $data["geodaten"]); $contentCreateStruct->setField('rubriken', $data["rubriken"]); $contentCreateStruct->setField('url', $data["url"]); $contentCreateStruct->setField('bild_url', $data["bild_url"]); $draft = $contentService->createContent($contentCreateStruct, array($locationCreateStruct)); $update = $client->createUpdate(); $update->addCommit(); $result = $client->update($update); $output->writeln("Veranstaltung erzeugt erzeugt."); $output->writeln("Done."); } catch (\eZ\Publish\API\Repository\Exceptions\NotFoundException $e) { $output->writeln($e->getMessage()); } catch (\eZ\Publish\API\Repository\Exceptions\ContentFieldValidationException $e) { $output->writeln($e->getMessage()); } catch (\eZ\Publish\API\Repository\Exceptions\ContentValidationException $e) { $output->writeln($e->getMessage()); } }
<?php require __DIR__ . '/init.php'; htmlHeader(); // create a client instance $client = new Solarium\Client($config); // get a morelikethis query instance $query = $client->createMoreLikeThis(); $query->setQuery('electronics memory'); $query->setQueryStream(true); $query->setMltFields('manu,cat'); $query->setMinimumDocumentFrequency(1); $query->setMinimumTermFrequency(1); $query->createFilterQuery('stock')->setQuery('inStock:true'); $query->setInterestingTerms('details'); $query->setMatchInclude(true); // this executes the query and returns the result $resultset = $client->select($query); echo 'Document used for matching:<br/><table>'; foreach ($resultset->getMatch() as $field => $value) { // this converts multivalue fields to a comma-separated string if (is_array($value)) { $value = implode(', ', $value); } echo '<tr><th>' . $field . '</th><td>' . $value . '</td></tr>'; } echo '</table><hr/>'; // display the total number of MLT documents found by solr echo 'Number of MLT matches found: ' . $resultset->getNumFound() . '<br/><br/>'; echo '<b>Listing of matched docs:</b>'; // show MLT documents using the resultset iterator
/** * @param Solarium\Client $solr * @param BenutzerIn $benutzerIn * @return \Solarium\QueryType\Select\Query\Query */ protected function getAlleSuchergebnisse(&$solr, $benutzerIn) { $select = $solr->createSelect(); $select->addSort('sort_datum', $select::SORT_DESC); $select->setRows(100); /** @var Solarium\QueryType\Select\Query\Component\DisMax $dismax */ $dismax = $select->getDisMax(); $dismax->setQueryParser('edismax'); $dismax->setQueryFields("text text_ocr"); $benachrichtigungen = $benutzerIn->getBenachrichtigungen(); $krits_solr = []; foreach ($benachrichtigungen as $ben) { $krits_solr[] = "(" . $ben->getSolrQueryStr($select) . ")"; } $querystr = implode(" OR ", $krits_solr); $select->setQuery($querystr); /** @var Solarium\QueryType\Select\Query\Component\Highlighting\Highlighting $hl */ $hl = $select->getHighlighting(); $hl->setFields('text, text_ocr, antrag_betreff'); $hl->setSimplePrefix('<b>'); $hl->setSimplePostfix('</b>'); return $select; }
<?php require __DIR__ . '/init.php'; htmlHeader(); // create a client instance $client = new Solarium\Client($config); // get an analysis document query $query = $client->createAnalysisDocument(); $query->setShowMatch(true); $query->setQuery('ipod'); $doc = new Solarium\QueryType\Update\Query\Document(array('id' => 'MA147LL', 'name' => 'Apple 60 GB iPod with Video Playback Black', 'manu' => 'Apple Computer Inc.', 'cat' => 'electronics', 'cat' => 'music', 'features' => 'iTunes, Podcasts, Audiobooks', 'features' => 'Stores up to 15,000 songs, 25,000 photos, or 150 hours of video', 'features' => '2.5-inch, 320x240 color TFT LCD display with LED backlight', 'features' => 'Up to 20 hours of battery life', 'features' => 'Plays AAC, MP3, WAV, AIFF, Audible, Apple Lossless, H.264 video', 'features' => 'Notes, Calendar, Phone book, Hold button, Date display, Photo wallet, Built-in games, ' . 'JPEG photo playback, Upgradeable firmware, USB 2.0 compatibility, Playback speed control, ' . 'Rechargeable capability, Battery level indication', 'includes' => 'earbud headphones, USB cable', 'weight' => 5.5, 'price' => 399.0, 'popularity' => 10, 'inStock' => true)); $query->addDocument($doc); // this executes the query and returns the result $result = $client->analyze($query); // show the results foreach ($result as $document) { echo '<hr><h2>Document: ' . $document->getName() . '</h2>'; foreach ($document as $field) { echo '<h3>Field: ' . $field->getName() . '</h3>'; $indexAnalysis = $field->getIndexAnalysis(); if (!empty($indexAnalysis)) { echo '<h4>Index Analysis</h4>'; foreach ($indexAnalysis as $classes) { echo '<h5>' . $classes->getName() . '</h5>'; foreach ($classes as $result) { echo 'Text: ' . $result->getText() . '<br/>'; echo 'Raw text: ' . $result->getRawText() . '<br/>'; echo 'Start: ' . $result->getStart() . '<br/>'; echo 'End: ' . $result->getEnd() . '<br/>'; echo 'Position: ' . $result->getPosition() . '<br/>'; echo 'Position history: ' . implode(', ', $result->getPositionHistory()) . '<br/>';
<?php require __DIR__ . '/init.php'; htmlHeader(); // create a client instance and autoload the customize request plugin $client = new Solarium\Client($config); $customizer = $client->getPlugin('customizerequest'); // add a persistent HTTP header (using array input values) $customizer->createCustomization(array('key' => 'auth', 'type' => 'header', 'name' => 'X-my-auth', 'value' => 'mypassword', 'persistent' => true)); // add a persistent GET param (using fluent interface) $customizer->createCustomization('session')->setType('param')->setName('ssid')->setValue('md7Nhd86adye6sad46d')->setPersistent(true); // add a GET param thats only used for a single request (the default setting is no persistence) $customizer->createCustomization('id')->setType('param')->setName('id')->setValue(4576); // create a basic query to execute $query = $client->createSelect(); // execute query (you should be able to see the extra params in the solr log file) $resultset = $client->select($query); // display the total number of documents found by solr echo 'NumFound: ' . $resultset->getNumFound() . '<br/>'; // execute the same query again (this time the 'id' param should no longer show up in the logs) $resultset = $client->select($query); // display the total number of documents found by solr echo 'NumFound: ' . $resultset->getNumFound(); htmlFooter();
<?php require_once 'Zend/Loader/Autoloader.php'; $loader = Zend_Loader_Autoloader::getInstance(); require __DIR__ . '/init.php'; htmlHeader(); // create a client instance $client = new Solarium\Client($config); // set the adapter to zendhttp and get a zendhttp client instance reference $client->setAdapter('Solarium\\Core\\Client\\Adapter\\ZendHttp'); $zendHttp = $client->getAdapter()->getZendHttp(); // you can use any of the zend_http features, like http-authentication $zendHttp->setAuth('user', 'password!', Zend_Http_Client::AUTH_BASIC); // get a select query instance $query = $client->createSelect(); // this executes the query and returns the result $resultset = $client->select($query); // display the total number of documents found by solr echo 'NumFound: ' . $resultset->getNumFound(); // show documents using the resultset iterator foreach ($resultset as $document) { echo '<hr/><table>'; // the documents are also iterable, to get all fields foreach ($document as $field => $value) { // this converts multivalue fields to a comma-separated string if (is_array($value)) { $value = implode(', ', $value); } echo '<tr><th>' . $field . '</th><td>' . $value . '</td></tr>'; } echo '</table>';
<?php require __DIR__ . '/init.php'; htmlHeader(); // create a client instance $client = new Solarium\Client($config); // get an update query instance $update = $client->createUpdate(); // create a new document $id = time(); $doc1 = $update->createDocument(); $doc1->id = $id; $doc1->name = 'realtime-get-test-' . date('Y-m-d H:i:s'); // set a very long commitWithin time and add it to solr $update->addDocument($doc1, null, 1000000); $client->update($update); // try to get the document using a normal select, this should return 0 results $query = $client->createSelect(); $query->setQuery('id:%1%', array($id)); $resultset = $client->select($query); echo 'NumFound with standard select: ' . $resultset->getNumFound() . '<br/>'; // now with realtime get, this should return 1 result $query = $client->createRealtimeGet(); $query->addId($id); $result = $client->realtimeGet($query); echo 'NumFound with realtime get: ' . $result->getNumFound() . '<br/>'; // Display the document echo '<hr/><table>'; foreach ($result->getDocument() as $field => $value) { echo '<tr><th>' . $field . '</th><td>' . $value . '</td></tr>'; }
<?php require __DIR__ . '/init.php'; htmlHeader(); // create a client instance $client = new Solarium\Client($config); // get a select query instance $query = $client->createSelect(); $query->setFields(array('id')); // get a plugin instance and apply settings $prefetch = $client->getPlugin('prefetchiterator'); $prefetch->setPrefetch(2); //fetch 2 rows per query (for real world use this can be way higher) $prefetch->setQuery($query); // display the total number of documents found by solr echo 'NumFound: ' . count($prefetch); // show document IDs using the resultset iterator foreach ($prefetch as $document) { echo '<hr/>ID: ' . $document->id; } htmlFooter();
protected function execute(InputInterface $input, OutputInterface $output) { $client = new \Solarium\Client($this->getContainer()->getParameter('xrow_ez_publish_solr_docs.solrserverconfig')); try { $output->writeln("Start..."); $this->startTiming("start"); #$update = $client->createUpdate(); #$update->addCommit(); #$result = $client->update($update); #die("Alles committed"); #$update = $client->createUpdate(); #$update->addDeleteQuery('meta_class_name_ms:"Video"'); #$update->addDeleteQuery('*:*'); #$update->addCommit(); #$result = $client->update($update); #die("alles is weck"); #$output->writeln( "Time until solr cleaned:" . $this->getTimingToNow( "start" ) ); /** @var $repository \eZ\Publish\API\Repository\Repository */ #$repository = $this->getContainer()->get( 'ezpublish.api.repository' ); $repository = $this->getContainer()->get('ezpublish.solrapi.repository'); $output->writeln("Time until repo loaded:" . $this->getTimingToNow("start")); $contentService = $repository->getContentService(); $locationService = $repository->getLocationService(); $contentTypeService = $repository->getContentTypeService(); $repository->setCurrentUser($repository->getUserService()->loadUser(14)); $parentLocationId = 2; // instantiate a location create struct from the parent location $locationCreateStruct = $locationService->newLocationCreateStruct($parentLocationId); $this->startTiming("contentcreation_all"); $onlycreatemilliseconds = 0; for ($i = 1; $i <= 10; $i++) { $this->startTiming("contentcreation_item"); $contentTypeIdentifier = "s_artikel"; $contentType = $contentTypeService->loadContentTypeByIdentifier($contentTypeIdentifier); $contentCreateStruct = $contentService->newContentCreateStruct($contentType, 'ger-DE'); $titel = "Titel neuer Solr Artikel Nr. {$i} " . rand(2, 9876987); $veroeffentlichungsdatum = 1409131877; $vorspann = "<p>Dieser Artikel hat einen relativ langen Vorspann. Wie eigentlich auch immer.</p>"; $haupttext = "<p>Dieser Artikel hat einen relativ <b>kurzen</b> Haupttext. Dieser Artikel hat einen relativ <b>kurzen</b> Haupttext.\nDieser Artikel hat einen relativ <b>kurzen</b> Haupttext. Dieser Artikel hat einen relativ <b>kurzen</b> Haupttext. Dieser Artikel hat einen relativ <b>kurzen</b> Haupttext.\nDieser Artikel hat einen relativ <b>kurzen</b> Haupttext. Dieser Artikel hat einen relativ <b>kurzen</b> Haupttext. Dieser Artikel hat einen relativ <b>kurzen</b> Haupttext. Dieser Artikel hat einen relativ <b>kurzen</b> Haupttext. \nDieser Artikel hat einen relativ <b>kurzen</b> Haupttext. \n</p>"; $schlagwoerter = array("Solr", "neuer Artikel", "Gewitter"); $rubriken = array("Nachrichten", "Meinung"); $url = "http://www.test.de/Nachrichten/Lokales/Hannover"; $contentCreateStruct->setField('titel', $titel); $contentCreateStruct->setField('veroeffentlichungsdatum', $veroeffentlichungsdatum); $contentCreateStruct->setField('vorspann', $vorspann); $contentCreateStruct->setField('haupttext', $haupttext); $contentCreateStruct->setField('schlagwoerter', $schlagwoerter); $contentCreateStruct->setField('rubriken', $rubriken); $contentCreateStruct->setField('url', $url); #$contentCreateStruct->setField( 'my_integer', rand(2, 9876987) ); #$contentCreateStruct->setField( 'my_xml', $meinXML ); #$contentCreateStruct->setField( 'my_text', $body ); #$contentCreateStruct->setField( 'my_int', 12 ); #$contentCreateStruct->setField( 'my_keyword', array("Nachrichten","Gewitter" )); #$contentCreateStruct->setField( 'my_boolean', true ); #$contentCreateStruct->setField( 'my_time', 1245253245 ); #$contentCreateStruct->setField( 'my_datetime', 326325600 ); #$contentCreateStruct->setField( 'my_float', 5.2214 ); #$contentCreateStruct->setField( 'my_geo', array( "longitude" => 42.117629, "latitude" => -70.956766, "address" => "Abington, MA" )); // create a draft using the content and location create struct and publish it $startmillimeasure = microtime(true); $draft = $contentService->createContent($contentCreateStruct, array($locationCreateStruct)); $endmillimeasure = microtime(true); $onlycreatemilliseconds = $onlycreatemilliseconds + ($endmillimeasure - $startmillimeasure) * 1000; $output->writeln("Time for item " . $i . " :" . $this->getTimingToNow("contentcreation_item")); } $output->writeln("Time for contentcreation:" . $this->getTimingToNow("contentcreation_all")); $this->startTiming("addcommitattheend"); $update = $client->createUpdate(); $update->addCommit(); $result = $client->update($update); $output->writeln("Time for COMMIT:" . $this->getTimingToNow("addcommitattheend")); $output->writeln("Time until end:" . $this->getTimingToNow("start")); $output->writeln("Time only for create:" . number_format($onlycreatemilliseconds / 1000, 1, '.', '') . " sec"); # We do not publish, creation is done while creating draft since NO versioning #$content = $contentService->publishVersion( $draft->versionInfo ); } catch (\eZ\Publish\API\Repository\Exceptions\NotFoundException $e) { $output->writeln($e->getMessage()); } catch (\eZ\Publish\API\Repository\Exceptions\ContentFieldValidationException $e) { $output->writeln($e->getMessage()); } catch (\eZ\Publish\API\Repository\Exceptions\ContentValidationException $e) { $output->writeln($e->getMessage()); } }
<?php require __DIR__ . '/init.php'; htmlHeader(); // create a client instance and create endpoints $client = new Solarium\Client($config); $endpoint1 = $client->createEndpoint('local1'); //normally you would add endpoint specific settings... $endpoint2 = $client->createEndpoint('local2'); $endpoint3 = $client->createEndpoint('local3'); // get loadbalancer plugin instance and add endpoints $loadbalancer = $client->getPlugin('loadbalancer'); $loadbalancer->addEndpoint($endpoint1, 100); $loadbalancer->addEndpoint($endpoint2, 100); $loadbalancer->addEndpoint($endpoint3, 1); // create a basic query to execute $query = $client->createSelect(); // execute the query multiple times, displaying the server for each execution for ($i = 1; $i <= 8; $i++) { $resultset = $client->select($query); echo 'Query execution #' . $i . '<br/>'; echo 'NumFound: ' . $resultset->getNumFound() . '<br/>'; echo 'Server: ' . $loadbalancer->getLastEndpoint() . '<hr/>'; } // force a server for a query (normally solr 3 is extremely unlikely based on its weight) $loadbalancer->setForcedEndpointForNextQuery('local3'); $resultset = $client->select($query); echo 'Query execution with server forced to local3<br/>'; echo 'NumFound: ' . $resultset->getNumFound() . '<br/>'; echo 'Server: ' . $loadbalancer->getLastEndpoint() . '<hr/>'; // test a ping query
<?php require __DIR__ . '/init.php'; htmlHeader(); // create a client instance and get a select query instance $client = new Solarium\Client($config); // first an example manually defining dereferenced params $query = $client->createSelect(); $helper = $query->getHelper(); $join = $helper->qparser('join', array('from' => 'manu_id', 'to' => 'id'), true); $queryString = $join . 'id:1'; $query->setQuery($queryString); $request = $client->createRequest($query); // output resulting url with dereferenced params echo urldecode($request->getUri()) . '<hr/>'; // this second example gives the exact same result, using the special join helper $query = $client->createSelect(); $helper = $query->getHelper(); $join = $helper->join('manu_id', 'id', true); $queryString = $join . 'id:1'; $query->setQuery($queryString); $request = $client->createRequest($query); echo urldecode($request->getUri()); htmlFooter();
<?php require __DIR__ . '/init.php'; use Solarium\Plugin\BufferedAdd\Event\Events; use Solarium\Plugin\BufferedAdd\Event\PreFlush as PreFlushEvent; htmlHeader(); // create a client instance and autoload the buffered add plugin $client = new Solarium\Client($config); $buffer = $client->getPlugin('bufferedadd'); $buffer->setBufferSize(10); // this is quite low, in most cases you can use a much higher value // also register an event hook to display what is happening $client->getEventDispatcher()->addListener(Events::PRE_FLUSH, function (PreFlushEvent $event) { echo 'Flushing buffer (' . count($event->getBuffer()) . 'docs)<br/>'; }); // let's insert 25 docs for ($i = 1; $i <= 25; $i++) { // create a new document with dummy data and add it to the buffer $data = array('id' => 'test_' . $i, 'name' => 'test for buffered add', 'price' => $i); $buffer->createDocument($data); // alternatively you could create document instances yourself and use the addDocument(s) method } // At this point two flushes will already have been done by the buffer automatically (at the 10th and 20th doc), now // manually flush the remainder. Alternatively you can use the commit method if you want to include a commit command. $buffer->flush(); // In total 3 flushes (requests) have been sent to Solr. This should be visible in the output of the event hook. htmlFooter();
<?php require __DIR__ . '/init.php'; htmlHeader(); // create a client instance $client = new Solarium\Client($config); // get a terms query instance $query = $client->createTerms(); $query->setFields('features,name'); $query->setLowerbound('i'); // this executes the query and returns the result $resultset = $client->terms($query); // display terms foreach ($resultset as $field => $terms) { echo '<h3>' . $field . '</h3>'; foreach ($terms as $term => $count) { echo $term . ' (' . $count . ')<br/>'; } echo '<hr/>'; } htmlFooter();
<?php require __DIR__ . '/init.php'; htmlHeader(); // create a client instance $client = new Solarium\Client($config); // get an update query instance $update = $client->createUpdate(); // create a new document for the data $doc1 = $update->createDocument(); $doc1->id = 123; $doc1->name = 'testdoc-1'; $doc1->price = 364; // and a second one $doc2 = $update->createDocument(); $doc2->id = 124; $doc2->name = 'testdoc-2'; $doc2->price = 340; // add the documents and a commit command to the update query $update->addDocuments(array($doc1, $doc2)); $update->addCommit(); // this executes the query and returns the result $result = $client->update($update); echo '<b>Update query executed</b><br/>'; echo 'Query status: ' . $result->getStatus() . '<br/>'; echo 'Query time: ' . $result->getQueryTime(); htmlFooter();
<?php require __DIR__ . '/init.php'; htmlHeader(); // create a client instance and autoload the customize request plugin $client = new Solarium\Client($config); $parallel = $client->getPlugin('parallelexecution'); // Add a delay param to better show the effect, as an example Solr install with // only a dozen documents is too fast for good testing // This param only works with the correct Solr plugin, // see http://www.raspberry.nl/2012/01/04/solr-delay-component/ // If you don't have to plugin the example still works, just without the delay. $customizer = $client->getPlugin('customizerequest'); $customizer->createCustomization(array('key' => 'delay', 'type' => 'param', 'name' => 'delay', 'value' => '500', 'persistent' => true)); // create two queries to execute in an array. Keys are important for fetching the results later! $queryInstock = $client->createSelect()->setQuery('inStock:true'); $queryLowprice = $client->createSelect()->setQuery('price:[1 TO 300]'); // first execute the queries the normal way and time it $start = microtime(true); $client->execute($queryInstock); $client->execute($queryLowprice); echo 'Execution time for normal "serial" execution of two queries: ' . round(microtime(true) - $start, 3); echo '<hr/>'; // now execute the two queries parallel and time it $start = microtime(true); $parallel->addQuery('instock', $queryInstock); $parallel->addQuery('lowprice', $queryLowprice); $results = $parallel->execute(); echo 'Execution time for parallel execution of two queries: ' . round(microtime(true) - $start, 3); htmlFooter(); // Note: for this example on a default Solr index (with a tiny index) running on localhost the performance gain is
<?php require __DIR__ . '/init.php'; htmlHeader(); // create a client instance $client = new Solarium\Client($config); // get a select query instance $query = $client->createSelect(); // add distributed search settings // see http://wiki.apache.org/solr/DistributedSearch#Distributed_Search_Example for setting up two solr instances $distributedSearch = $query->getDistributedSearch(); $distributedSearch->addShard('shard1', 'localhost:8983/solr'); $distributedSearch->addShard('shard2', 'localhost:7574/solr'); // this executes the query and returns the result $resultset = $client->select($query); // display the total number of documents found by solr echo 'NumFound: ' . $resultset->getNumFound(); // show documents using the resultset iterator foreach ($resultset as $document) { echo '<hr/><table>'; // the documents are also iterable, to get all fields foreach ($document as $field => $value) { // this converts multivalue fields to a comma-separated string if (is_array($value)) { $value = implode(', ', $value); } echo '<tr><th>' . $field . '</th><td>' . $value . '</td></tr>'; } echo '</table>'; } htmlFooter();
/** * Creates a new content draft assigned to the authenticated user. * * If a different userId is given in $contentCreateStruct it is assigned to the given user * but this required special rights for the authenticated user * (this is useful for content staging where the transfer process does not * have to authenticate with the user which created the content object in the source server). * The user has to publish the draft if it should be visible. * In 4.x at least one location has to be provided in the location creation array. * * @throws \eZ\Publish\API\Repository\Exceptions\UnauthorizedException if the user is not allowed to create the content in the given location * @throws \eZ\Publish\API\Repository\Exceptions\InvalidArgumentException if there is a provided remoteId which exists in the system * or there is no location provided (4.x) or multiple locations * are under the same parent or if the a field value is not accepted by the field type * @throws \eZ\Publish\API\Repository\Exceptions\ContentFieldValidationException if a field in the $contentCreateStruct is not valid * @throws \eZ\Publish\API\Repository\Exceptions\ContentValidationException if a required field is missing or is set to an empty value * * @param \eZ\Publish\API\Repository\Values\Content\ContentCreateStruct $contentCreateStruct * @param \eZ\Publish\API\Repository\Values\Content\LocationCreateStruct[] $locationCreateStructs For each location parent under which a location should be created for the content * * @return \eZ\Publish\API\Repository\Values\Content\Content - the newly created content draft */ public function createContent(APIContentCreateStruct $contentCreateStruct, array $locationCreateStructs = array()) { #$startzeit=microtime(true); if ($contentCreateStruct->mainLanguageCode === null) { throw new InvalidArgumentException("\$contentCreateStruct", "'mainLanguageCode' property must be set"); } if ($contentCreateStruct->contentType === null) { throw new InvalidArgumentException("\$contentCreateStruct", "'contentType' property must be set"); } $contentCreateStruct = clone $contentCreateStruct; if ($contentCreateStruct->ownerId === null) { $contentCreateStruct->ownerId = $this->repository->getCurrentUser()->id; } if ($contentCreateStruct->alwaysAvailable === null) { $contentCreateStruct->alwaysAvailable = false; } $contentCreateStruct->contentType = $this->repository->getContentTypeService()->loadContentType($contentCreateStruct->contentType->id); $contentCreateStruct->sectionId = 1; if (empty($contentCreateStruct->sectionId)) { if (isset($locationCreateStructs[0])) { $location = $this->repository->getLocationService()->loadLocation($locationCreateStructs[0]->parentLocationId); $contentCreateStruct->sectionId = $location->contentInfo->sectionId; } else { $contentCreateStruct->sectionId = 1; } } /* if ( !$this->repository->canUser( 'content', 'create', $contentCreateStruct, $locationCreateStructs ) ) { throw new UnauthorizedException( 'content', 'create' ); } */ /* if ( !empty( $contentCreateStruct->remoteId ) ) { try { $this->loadContentByRemoteId( $contentCreateStruct->remoteId ); throw new InvalidArgumentException( "\$contentCreateStruct", "Another content with remoteId '{$contentCreateStruct->remoteId}' exists" ); } catch ( APINotFoundException $e ) { // Do nothing } } else { $contentCreateStruct->remoteId = $this->domainMapper->getUniqueHash( $contentCreateStruct ); } */ #Expect RemoteID is unique $contentCreateStruct->remoteId = $this->domainMapper->getUniqueHash($contentCreateStruct); $spiLocationCreateStructs = $this->buildSPILocationCreateStructs($locationCreateStructs); $languageCodes = $this->getLanguageCodesForCreate($contentCreateStruct); $fields = $this->mapFieldsForCreate($contentCreateStruct); $fieldValues = array(); $SolrDocFields = array(); $spiFields = array(); $allFieldErrors = array(); $inputRelations = array(); $locationIdToContentIdMapping = array(); foreach ($contentCreateStruct->contentType->getFieldDefinitions() as $fieldDefinition) { /** @var $fieldType \eZ\Publish\Core\FieldType\FieldType */ $fieldType = $this->repository->getFieldTypeService()->buildFieldType($fieldDefinition->fieldTypeIdentifier); foreach ($languageCodes as $languageCode) { $isEmptyValue = false; $valueLanguageCode = $fieldDefinition->isTranslatable ? $languageCode : $contentCreateStruct->mainLanguageCode; $isLanguageMain = $languageCode === $contentCreateStruct->mainLanguageCode; if (isset($fields[$fieldDefinition->identifier][$valueLanguageCode])) { $fieldValue = $fields[$fieldDefinition->identifier][$valueLanguageCode]->value; } else { $fieldValue = $fieldDefinition->defaultValue; } $fieldValue = $fieldType->acceptValue($fieldValue); if ($fieldType->isEmptyValue($fieldValue)) { $isEmptyValue = true; if ($fieldDefinition->isRequired) { throw new ContentValidationException("Value for required field definition '{$fieldDefinition->identifier}' with language '{$languageCode}' is empty"); } } else { $fieldErrors = $fieldType->validate($fieldDefinition, $fieldValue); if (!empty($fieldErrors)) { $allFieldErrors[$fieldDefinition->id][$languageCode] = $fieldErrors; } } if (!empty($allFieldErrors)) { continue; } $this->relationProcessor->appendFieldRelations($inputRelations, $locationIdToContentIdMapping, $fieldType, $fieldValue, $fieldDefinition->id); $fieldValues[$fieldDefinition->identifier][$languageCode] = $fieldValue; // Only non-empty value for: translatable field or in main language if (!$isEmptyValue && $fieldDefinition->isTranslatable || !$isEmptyValue && $isLanguageMain) { $spiFields[] = new SPIField(array("id" => null, "fieldDefinitionId" => $fieldDefinition->id, "type" => $fieldDefinition->fieldTypeIdentifier, "value" => $fieldType->toPersistenceValue($fieldValue), "languageCode" => $languageCode, "versionNo" => null)); $SolrDocFields[] = array("identifier" => $fieldDefinition->identifier, "type" => $fieldDefinition->fieldTypeIdentifier, "value" => $fields[$fieldDefinition->identifier][$valueLanguageCode]->value, "data" => $fieldType->toPersistenceValue($fieldValue)->data, "sortkey" => $fieldType->toPersistenceValue($fieldValue)->sortKey, "languageCode" => $languageCode, "searchable" => $fieldDefinition->isSearchable); } } } if (!empty($allFieldErrors)) { throw new ContentFieldValidationException($allFieldErrors); } $spiContentCreateStruct = new SPIContentCreateStruct(array("name" => $this->nameSchemaService->resolve($contentCreateStruct->contentType->nameSchema, $contentCreateStruct->contentType, $fieldValues, $languageCodes), "typeId" => $contentCreateStruct->contentType->id, "sectionId" => $contentCreateStruct->sectionId, "ownerId" => $contentCreateStruct->ownerId, "locations" => $spiLocationCreateStructs, "fields" => $spiFields, "alwaysAvailable" => $contentCreateStruct->alwaysAvailable, "remoteId" => $contentCreateStruct->remoteId, "modified" => isset($contentCreateStruct->modificationDate) ? $contentCreateStruct->modificationDate->getTimestamp() : time(), "initialLanguageId" => $this->persistenceHandler->contentLanguageHandler()->loadByLanguageCode($contentCreateStruct->mainLanguageCode)->id)); if (!is_numeric($spiContentCreateStruct->locations[0]->parentId) && $spiContentCreateStruct->locations[0]->parentId != "") { $url = trim($spiContentCreateStruct->locations[0]->parentId, '/'); $url_array = explode("/", $url); $url_array[] = $spiContentCreateStruct->remoteId; $url_alias_cats = array(); foreach ($url_array as $depth => $part) { $fullpart = ""; for ($i = 0; $i <= $depth; $i++) { $fullpart .= $url_array[$i] . "/"; } $url_alias_cats[] = $depth . "/" . $fullpart; } $url_alias = $url_alias_cats; $lasturlelement = array_pop($url_alias_cats); $parent_url_alias = $url_alias_cats; } else { $url_alias_cats = array("0/" . $spiContentCreateStruct->locations[0]->parentId, "1/" . $spiContentCreateStruct->locations[0]->parentId . "/" . $spiContentCreateStruct->remoteId); $url_alias = $url_alias_cats; $lasturlelement = array_pop($url_alias_cats); $parent_url_alias = $url_alias_cats; } # we ommit defaultObjectStates!!!! #$defaultObjectStates = $this->getDefaultObjectStates(); #This is the point where a new version is created #We create a version 1 of solrDoc #$spiContent = $this->persistenceHandler->contentHandler()->create( $spiContentCreateStruct ); #$startzeit=microtime(true); $solrserverconfig = Globals::getSolrServerConfig(); $solrglobalconfig = Globals::getSolrGlobalConfig(); $client = new \Solarium\Client($solrserverconfig); $update = $client->createUpdate(); $doc1 = $update->createDocument(); $doc1->meta_installation_id_ms = $solrglobalconfig["meta_installation_id_ms"]; $doc1->meta_guid_ms = $spiContentCreateStruct->remoteId; $doc1->meta_name_t = $spiContentCreateStruct->name["ger-DE"]; $doc1->meta_sort_name_ms = $spiContentCreateStruct->name["ger-DE"]; $doc1->meta_remote_id_ms = $spiContentCreateStruct->remoteId; $doc1->meta_current_version_si = 1; $doc1->meta_class_identifier_ms = $contentCreateStruct->contentType->identifier; $doc1->meta_class_name_ms = $contentCreateStruct->contentType->names["ger-DE"]; $doc1->meta_contentclass_id_si = $spiContentCreateStruct->typeId; $doc1->meta_url_alias_ms = $url_alias; $doc1->meta_parent_url_alias_ms = array_pop($parent_url_alias); $doc1->meta_main_url_alias_ms = array_pop($url_alias); $doc1->meta_language_code_ms = $solrglobalconfig["meta_language_code_ms"]; $date = new DateTime(); $date->setTimestamp($spiContentCreateStruct->modified); $doc1->meta_published_dt = $date->format("Y-m-d\\TH:i:s\\Z"); $doc1->timestamp = $date->format("Y-m-d\\TH:i:s\\Z"); $doc1->meta_id_si = 0; /* // is that really nessecary? #$doc1->meta_main_parent_node_id_si= 61; #$doc1->meta_node_id_si=array( 68 ); $doc1->is_solrdoc_b = true; $doc1->meta_installation_url_ms = $solrglobalconfig["meta_installation_id_ms"]; $doc1->meta_id_si = 0; $doc1->meta_section_id_si = $spiContentCreateStruct->sectionId; $doc1->meta_owner_id_si = $spiContentCreateStruct->ownerId; $doc1->meta_modified_dt=$date->format( "Y-m-d\\TH:i:s\\Z" ); $doc1->meta_is_hidden_b=array( false ); $doc1->meta_is_invisible_b=array( false ); $doc1->meta_always_available_b = $contentCreateStruct->alwaysAvailable; $doc1->meta_sort_field_ms=array( "1" ); $doc1->meta_sort_order_ms=array( "1"); $doc1->meta_priority_si=array( 0 ); $doc1->meta_view_count_si=array(0); $doc1->meta_owner_name_t = $solrglobalconfig["meta_owner_name_t"]; $doc1->meta_owner_group_id_si = array( $solrglobalconfig["meta_owner_group_id_si"] ); $doc1->meta_object_states_si=array( $solrglobalconfig["meta_object_states_si"] ); */ // LoopThroughFields #var_dump(count($SolrDocFields)); #var_dump($SolrDocFields); #die("sdkfj"); foreach ($SolrDocFields as $solrField) { if ($solrField["type"] == "eztext") { $ident = "attr_" . $solrField["identifier"] . "_t"; $solrvalue = $solrField["value"]; } if ($solrField["type"] == "ezstring") { $ident = "attr_" . $solrField["identifier"] . "_s"; $solrvalue = $solrField["value"]; } if ($solrField["type"] == "ezboolean") { $ident = "attr_" . $solrField["identifier"] . "_b"; $solrvalue = $solrField["value"]; } if ($solrField["type"] == "ezinteger") { $ident = "attr_" . $solrField["identifier"] . "_si"; $solrvalue = $solrField["value"]; } if ($solrField["type"] == "ezfloat") { $ident = "attr_" . $solrField["identifier"] . "_f"; $solrvalue = (double) $solrField["value"]; } if ($solrField["type"] == "ezkeyword") { $ident = "attr_" . $solrField["identifier"] . "____k"; $solrvalue = $solrField["value"]; } if ($solrField["type"] == "ezurl") { $ident = "attr_" . $solrField["identifier"] . "_ms"; $solrvalue = $solrField["value"]; } if ($solrField["type"] == "ezdatetime" or $solrField["type"] == "ezdate") { $ident = "attr_" . $solrField["identifier"] . "_dt"; $date = new DateTime(); $date->setTimestamp((int) $solrField["value"]); $solrvalue = $date->format("Y-m-d\\TH:i:s\\Z"); } if ($solrField["type"] == "ezxmltext") { $ident = "attr_" . $solrField["identifier"] . "_ms"; $textcontent = $solrField["data"]->textContent; $solrvalue = $solrField["value"]; $tident = "attr_" . $solrField["identifier"] . "_s"; $doc1->{$tident} = $textcontent; } if ($solrField["type"] == "ezgmaplocation") { $ident = "attr_" . $solrField["identifier"] . "_gpt"; $solrvalue = $solrField["value"]["longitude"] . "," . $solrField["value"]["latitude"]; } $doc1->{$ident} = $solrvalue; } $update->addDocuments(array($doc1)); $result = $client->update($update); /* $durationInMilliseconds = (microtime(true) - $startzeit) * 1000; $timing = number_format($durationInMilliseconds, 3, '.', '') . "ms"; if($durationInMilliseconds > 1000) { $timing = number_format($durationInMilliseconds / 1000, 1, '.', '') . "sec"; } echo "\nI:" . $timing . "\n"; */ /* Orig creation $this->repository->beginTransaction(); try { $spiContent = $this->persistenceHandler->contentHandler()->create( $spiContentCreateStruct ); $this->relationProcessor->processFieldRelations( $inputRelations, $spiContent->versionInfo->contentInfo->id, $spiContent->versionInfo->versionNo, $contentCreateStruct->contentType ); foreach ( $defaultObjectStates as $objectStateGroupId => $objectState ) { $this->persistenceHandler->objectStateHandler()->setContentState( $spiContent->versionInfo->contentInfo->id, $objectStateGroupId, $objectState->id ); } $this->repository->commit(); } catch ( Exception $e ) { $this->repository->rollback(); throw $e; } return $this->domainMapper->buildContentDomainObject( $spiContent ); */ }