Ejemplos de cómo usar la extensión Apache Solr de PHP
Ejemplo #1 Contenido del archivo BootStrap
<?php
/* Nombre de dominio del servidor Solr */
define('SOLR_SERVER_HOSTNAME', 'solr.example.com');
/* Si ejecutar en modo seguro */
define('SOLR_SECURE', true);
/* Puerto HTTP para la conexión */
define('SOLR_SERVER_PORT', ((SOLR_SECURE) ? 8443 : 8983));
/* Nomre de Usuario de Autenticación Básica de HTTP */
define('SOLR_SERVER_USERNAME', 'admin');
/* Contraseña de Autenticación Básica de HTTP */
define('SOLR_SERVER_PASSWORD', 'changeit');
/* Tiempo límite de conexión de HTTP */
/* Es el tiempo máximo en segundos permitido para la operación de transferencia de datos de http. El valor predeterminado es 30 seg. */
define('SOLR_SERVER_TIMEOUT', 10);
/* Nombre de archivo a una clave + certificado privados con formato PEM (concatenado en ese ornden */
define('SOLR_SSL_CERT', 'certs/combo.pem');
/* Nombre de archivo a un certificado privado con formato PEM */
define('SOLR_SSL_CERT_ONLY', 'certs/solr.crt');
/* Nombre de archivo a una clave privada con formato PEM */
define('SOLR_SSL_KEY', 'certs/solr.key');
/* Contraseña para el archivo de clave privada con formato PEM */
define('SOLR_SSL_KEYPASSWORD', 'StrongAndSecurePassword');
/* Nombre del archivo que mantiene uno o más certificados CA para ser verificados con su par */
define('SOLR_SSL_CAINFO', 'certs/cacert.crt');
/* Nombre del directorio que mantiene múltiples certificados CA para ser verificados con su par */
define('SOLR_SSL_CAPATH', 'certs/');
?>
Ejemplo #2 Añadir un documento al índice
<?php
include "bootstrap.php";
$opciones = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);
$cliente = new SolrClient($opciones);
$doc = new SolrInputDocument();
$doc->addField('id', 334455);
$doc->addField('cat', 'Software');
$doc->addField('cat', 'Lucene');
$respuestaActualización = $cliente->addDocument($doc);
print_r($respuestaActualización->getResponse());
?>
El resultado del ejemplo sería algo similar a:
SolrObject Object ( [responseHeader] => SolrObject Object ( [status] => 0 [QTime] => 446 ) )
Ejemplo #3 Fusionar un documento con otro documento
<?php
include "bootstrap.php";
$doc = new SolrDocument();
$segundo_doc = new SolrDocument();
$doc->addField('id', 1123);
$doc->features = "PHP Client Side";
$doc->features = "Fast development cycles";
$doc['cat'] = 'Software';
$doc['cat'] = 'Custom Search';
$doc->cat = 'Information Technology';
$segundo_doc->addField('cat', 'Lucene Search');
$segundo_doc->merge($doc, true);
print_r($segundo_doc->toArray());
?>
El resultado del ejemplo sería algo similar a:
Array ( [document_boost] => 0 [field_count] => 3 [fields] => Array ( [0] => SolrDocumentField Object ( [name] => cat [boost] => 0 [values] => Array ( [0] => Software [1] => Custom Search [2] => Information Technology ) ) [1] => SolrDocumentField Object ( [name] => id [boost] => 0 [values] => Array ( [0] => 1123 ) ) [2] => SolrDocumentField Object ( [name] => features [boost] => 0 [values] => Array ( [0] => PHP Client Side [1] => Fast development cycles ) ) ) )
Ejemplo #4 Buscar documentos - respuestas de SolrObject
<?php
include "bootstrap.php";
$opciones = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);
$cliente = new SolrClient($opciones);
$consulta = new SolrQuery();
$consulta->setQuery('lucene');
$consulta->setStart(0);
$consulta->setRows(50);
$consulta->addField('cat')->addField('features')->addField('id')->addField('timestamp');
$respuesta_consulta = $cliente->query($consulta);
$respuesta = $respuesta_consulta->getResponse();
print_r($respuesta);
?>
El resultado del ejemplo sería algo similar a:
SolrObject Object ( [responseHeader] => SolrObject Object ( [status] => 0 [QTime] => 1 [params] => SolrObject Object ( [wt] => xml [rows] => 50 [start] => 0 [indent] => on [q] => lucene [fl] => cat,features,id,timestamp [version] => 2.2 ) ) [response] => SolrObject Object ( [numFound] => 3 [start] => 0 [docs] => Array ( [0] => SolrObject Object ( [cat] => Array ( [0] => Software [1] => Lucene ) [id] => 334456 ) [1] => SolrObject Object ( [cat] => Array ( [0] => Software [1] => Lucene ) [id] => 334455 ) [2] => SolrObject Object ( [cat] => Array ( [0] => software [1] => search ) [features] => Array ( [0] => Advanced Full-Text Search Capabilities using Lucene [1] => Optimized for High Volume Web Traffic [2] => Standards Based Open Interfaces - XML and HTTP [3] => Comprehensive HTML Administration Interfaces [4] => Scalability - Efficient Replication to other Solr Search Servers [5] => Flexible and Adaptable with XML configuration and Schema [6] => Good unicode support: héllo (hello with an accent over the e) ) [id] => SOLR1000 [timestamp] => 2009-09-04T20:38:55.906 ) ) ) )
Ejemplo #5 Buscar documentos - respuestas de SolrDocument
<?php
include "bootstrap.php";
$opciones = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);
$cliente = new SolrClient($opciones);
$consulta = new SolrQuery();
$consulta->setQuery('lucene');
$consulta->setStart(0);
$consulta->setRows(50);
$consulta->addField('cat')->addField('features')->addField('id')->addField('timestamp');
$respuesta_consulta = $cliente->query($consulta);
$respuesta_consulta->setParseMode(SolrQueryResponse::PARSE_SOLR_DOC);
$respuesta = $respuesta_consulta->getResponse();
print_r($respuesta);
?>
El resultado del ejemplo sería algo similar a:
SolrObject Object ( [responseHeader] => SolrObject Object ( [status] => 0 [QTime] => 1 [params] => SolrObject Object ( [wt] => xml [rows] => 50 [start] => 0 [indent] => on [q] => lucene [fl] => cat,features,id,timestamp [version] => 2.2 ) ) [response] => SolrObject Object ( [numFound] => 3 [start] => 0 [docs] => Array ( [0] => SolrDocument Object ( [_hashtable_index:SolrDocument:private] => 19740 ) [1] => SolrDocument Object ( [_hashtable_index:SolrDocument:private] => 25485 ) [2] => SolrDocument Object ( [_hashtable_index:SolrDocument:private] => 25052 ) ) ) )
Ejemplo #6 Ejemplo sencillo de TermsComponent - básico
<?php
include "bootstrap.php";
$opciones = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);
$cliente = new SolrClient($opciones);
$consulta = new SolrQuery();
$consulta->setTerms(true);
$consulta->setTermsField('cat');
$respuestaActualización = $cliente->query($consulta);
print_r($respuestaActualización->getResponse());
?>
El resultado del ejemplo sería algo similar a:
SolrObject Object ( [responseHeader] => SolrObject Object ( [status] => 0 [QTime] => 2 ) [terms] => SolrObject Object ( [cat] => SolrObject Object ( [electronics] => 14 [Lucene] => 4 [Software] => 4 [memory] => 3 [card] => 2 [connector] => 2 [drive] => 2 [graphics] => 2 [hard] => 2 [monitor] => 2 ) ) )
Ejemplo #7 Ejemplo sencillo de TermsComponent - usar un prefijo
<?php
include "bootstrap.php";
$opciones = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);
$cliente = new SolrClient($opciones);
$consulta = new SolrQuery();
$consulta->setTerms(true);
/* Devolver sólo los términos que empiecen con $prefijo */
$prefijo = 'c';
$consulta->setTermsField('cat')->setTermsPrefix($prefijo);
$respuestaActualización = $cliente->query($consulta);
print_r($respuestaActualización->getResponse());
?>
El resultado del ejemplo sería algo similar a:
SolrObject Object ( [responseHeader] => SolrObject Object ( [status] => 0 [QTime] => 1 ) [terms] => SolrObject Object ( [cat] => SolrObject Object ( [card] => 2 [connector] => 2 [camera] => 1 [copier] => 1 ) ) )
Ejemplo #8 Ejemplo sencillo de TermsComponent - especificar una frecuencia mínima
<?php
include "bootstrap.php";
$opciones = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);
$cliente = new SolrClient($opciones);
$consulta = new SolrQuery();
$consulta->setTerms(true);
/* Devolver sólo los términos que empiecen con $prefijo */
$prefijo = 'c';
/* Devolver sólo los términos con una frecuencia de 2 o mayor */
$frecuencia_mín = 2;
$consulta->setTermsField('cat')->setTermsPrefix($prefijo)->setTermsMinCount($frecuencia_mín);
$respuestaActualización = $cliente->query($consulta);
print_r($respuestaActualización->getResponse());
?>
El resultado del ejemplo sería algo similar a:
SolrObject Object ( [responseHeader] => SolrObject Object ( [status] => 0 [QTime] => 0 ) [terms] => SolrObject Object ( [cat] => SolrObject Object ( [card] => 2 [connector] => 2 ) ) )
Ejemplo #9 Ejemplo sencillo de Facet
<?php
include "bootstrap.php";
$opciones = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);
$cliente = new SolrClient($opciones);
$consulta = new SolrQuery('*:*');
$consulta->setFacet(true);
$consulta->addFacetField('cat')->addFacetField('name')->setFacetMinCount(2);
$respuestaActualización = $cliente->query($consulta);
$array_respuesta = $respuestaActualización->getResponse();
$datos_faceta = $array_respuesta->facet_counts->facet_fields;
print_r($datos_faceta);
?>
El resultado del ejemplo sería algo similar a:
SolrObject Object ( [cat] => SolrObject Object ( [electronics] => 14 [memory] => 3 [Lucene] => 2 [Software] => 2 [card] => 2 [connector] => 2 [drive] => 2 [graphics] => 2 [hard] => 2 [monitor] => 2 [search] => 2 [software] => 2 ) [name] => SolrObject Object ( [gb] => 6 [1] => 3 [184] => 3 [2] => 3 [3200] => 3 [400] => 3 [500] => 3 [ddr] => 3 [i] => 3 [ipod] => 3 [memori] => 3 [pc] => 3 [pin] => 3 [pod] => 3 [sdram] => 3 [system] => 3 [unbuff] => 3 [canon] => 2 [corsair] => 2 [drive] => 2 [hard] => 2 [mb] => 2 [n] => 2 [power] => 2 [retail] => 2 [video] => 2 [x] => 2 ) )
Ejemplo #10 Ejemplo sencillo de Facet - con sobrescritura de campo opcional para mincount
<?php
include "bootstrap.php";
$opciones = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);
$cliente = new SolrClient($opciones);
$consulta = new SolrQuery('*:*');
$consulta->setFacet(true);
$consulta->addFacetField('cat')->addFacetField('name')->setFacetMinCount(2)->setFacetMinCount(4, 'name');
$respuestaActualización = $cliente->query($consulta);
$array_respuesta = $respuestaActualización->getResponse();
$datos_faceta = $array_respuesta->facet_counts->facet_fields;
print_r($datos_faceta);
?>
El resultado del ejemplo sería algo similar a:
SolrObject Object ( [cat] => SolrObject Object ( [electronics] => 14 [memory] => 3 [Lucene] => 2 [Software] => 2 [card] => 2 [connector] => 2 [drive] => 2 [graphics] => 2 [hard] => 2 [monitor] => 2 [search] => 2 [software] => 2 ) [name] => SolrObject Object ( [gb] => 6 ) )
Ejemplo #11 Ejemplo de fecha de faceta
<?php
include "bootstrap.php";
$opciones = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);
$client = new SolrClient($opciones);
$consulta = new SolrQuery('*:*');
$consulta->setFacet(true);
$consulta->addFacetDateField('manufacturedate_dt');
$consulta->setFacetDateStart('2006-02-13T00:00:00Z');
$consulta->setFacetDateEnd('2012-02-13T00:00:00Z');
$consulta->setFacetDateGap('+1YEAR');
$consulta->setFacetDateHardEnd(1);
$consulta->addFacetDateOther('before');
$respuestaActualización = $client->query($consulta);
$array_respuesta = $respuestaActualización->getResponse();
$datos_faceta = $array_respuesta->facet_counts->facet_dates;
print_r($datos_faceta);
?>
El resultado del ejemplo sería algo similar a:
SolrObject Object ( [manufacturedate_dt] => SolrObject Object ( [2006-02-13T00:00:00Z] => 9 [2007-02-13T00:00:00Z] => 0 [2008-02-13T00:00:00Z] => 0 [2009-02-13T00:00:00Z] => 0 [2010-02-13T00:00:00Z] => 0 [2011-02-13T00:00:00Z] => 0 [gap] => +1YEAR [start] => 2006-02-13T00:00:00Z [end] => 2012-02-13T00:00:00Z [before] => 2 ) )
Ejemplo #12 Conectar a un Servidor con SSL Habilitado
<?php
include "bootstrap.php";
$opciones = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
'timeout' => SOLR_SERVER_TIMEOUT,
'secure' => SOLR_SECURE,
'ssl_cert' => SOLR_SSL_CERT_ONLY,
'ssl_key' => SOLR_SSL_KEY,
'ssl_keypassword' => SOLR_SSL_KEYPASSWORD,
'ssl_cainfo' => SOLR_SSL_CAINFO,
);
$cliente = new SolrClient($opciones);
$consulta = new SolrQuery('*:*');
$consulta->setFacet(true);
$consulta->addFacetField('cat')->addFacetField('name')->setFacetMinCount(2)->setFacetMinCount(4, 'name');
$respuestaActualización = $cliente->query($consulta);
$array_respuesta = $respuestaActualización->getResponse();
$datos_faceta = $array_respuesta->facet_counts->facet_fields;
print_r($datos_faceta);
?>
El resultado del ejemplo sería algo similar a:
SolrObject Object ( [cat] => SolrObject Object ( [electronics] => 14 [memory] => 3 [Lucene] => 2 [Software] => 2 [card] => 2 [connector] => 2 [drive] => 2 [graphics] => 2 [hard] => 2 [monitor] => 2 [search] => 2 [software] => 2 ) [name] => SolrObject Object ( [gb] => 6 ) )
Ejemplo #13 Colapsar un SolrQuery
<?php
include "bootstrap.php";
$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
'path' => SOLR_SERVER_PATH
);
$client = new SolrClient($options);
$query = new SolrQuery('*:*');
$collapseFunction = new SolrCollapseFunction('manu_id_s');
$collapseFunction
->setSize(2)
->setNullPolicy(SolrCollapseFunction::NULLPOLICY_IGNORE);
$query
->collapse($collapseFunction)
->setRows(4);
$queryResponse = $client->query($query);
$response = $queryResponse->getResponse();
print_r($response);
?>
El resultado del ejemplo sería algo similar a:
SolrObject Object ( [responseHeader] => SolrObject Object ( [status] => 0 [QTime] => 1 [params] => SolrObject Object ( [q] => *:* [indent] => on [fq] => {!collapse field=manu_id_s size=2 nullPolicy=ignore} [rows] => 4 [version] => 2.2 [wt] => xml ) ) [response] => SolrObject Object ( [numFound] => 14 [start] => 0 [docs] => Array ( [0] => SolrObject Object ( [id] => SP2514N [name] => Array ( [0] => Samsung SpinPoint P120 SP2514N - hard drive - 250 GB - ATA-133 ) [manu] => Array ( [0] => Samsung Electronics Co. Ltd. ) [manu_id_s] => samsung [cat] => Array ( [0] => electronics [1] => hard drive ) [features] => Array ( [0] => 7200RPM, 8MB cache, IDE Ultra ATA-133 [1] => NoiseGuard, SilentSeek technology, Fluid Dynamic Bearing (FDB) motor ) [price] => Array ( [0] => 92 ) [popularity] => Array ( [0] => 6 ) [inStock] => Array ( [0] => 1 ) [manufacturedate_dt] => 2006-02-13T15:26:37Z [store] => Array ( [0] => 35.0752,-97.032 ) [_version_] => 1510294336412057600 ) [1] => SolrObject Object ( [id] => 6H500F0 [name] => Array ( [0] => Maxtor DiamondMax 11 - hard drive - 500 GB - SATA-300 ) [manu] => Array ( [0] => Maxtor Corp. ) [manu_id_s] => maxtor [cat] => Array ( [0] => electronics [1] => hard drive ) [features] => Array ( [0] => SATA 3.0Gb/s, NCQ [1] => 8.5ms seek [2] => 16MB cache ) [price] => Array ( [0] => 350 ) [popularity] => Array ( [0] => 6 ) [inStock] => Array ( [0] => 1 ) [store] => Array ( [0] => 45.17614,-93.87341 ) [manufacturedate_dt] => 2006-02-13T15:26:37Z [_version_] => 1510294336449806336 ) [2] => SolrObject Object ( [id] => F8V7067-APL-KIT [name] => Array ( [0] => Belkin Mobile Power Cord for iPod w/ Dock ) [manu] => Array ( [0] => Belkin ) [manu_id_s] => belkin [cat] => Array ( [0] => electronics [1] => connector ) [features] => Array ( [0] => car power adapter, white ) [weight] => Array ( [0] => 4 ) [price] => Array ( [0] => 19.95 ) [popularity] => Array ( [0] => 1 ) [inStock] => Array ( [0] => ) [store] => Array ( [0] => 45.18014,-93.87741 ) [manufacturedate_dt] => 2005-08-01T16:30:25Z [_version_] => 1510294336458194944 ) [3] => SolrObject Object ( [id] => MA147LL/A [name] => Array ( [0] => Apple 60 GB iPod with Video Playback Black ) [manu] => Array ( [0] => Apple Computer Inc. ) [manu_id_s] => apple [cat] => Array ( [0] => electronics [1] => music ) [features] => Array ( [0] => iTunes, Podcasts, Audiobooks [1] => Stores up to 15,000 songs, 25,000 photos, or 150 hours of video [2] => 2.5-inch, 320x240 color TFT LCD display with LED backlight [3] => Up to 20 hours of battery life [4] => Plays AAC, MP3, WAV, AIFF, Audible, Apple Lossless, H.264 video [5] => 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] => Array ( [0] => earbud headphones, USB cable ) [weight] => Array ( [0] => 5.5 ) [price] => Array ( [0] => 399 ) [popularity] => Array ( [0] => 10 ) [inStock] => Array ( [0] => 1 ) [store] => Array ( [0] => 37.7752,-100.0232 ) [manufacturedate_dt] => 2005-10-12T08:00:00Z [_version_] => 1510294336562003968 ) ) ) )
Ejemplo #14 Ejemplo de conseguir el tiempo real Solr(RTG) SolrClient::getById()
<?php
include "bootstrap.php";
$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
'path' => SOLR_SERVER_PATH
);
$client = new SolrClient($options);
$response = $client->getById('GB18030TEST');
print_r($response->getResponse());
?>
El resultado del ejemplo sería algo similar a:
SolrObject Object ( [doc] => SolrObject Object ( [id] => GB18030TEST [name] => Array ( [0] => Test with some GB18030 encoded characters ) [features] => Array ( [0] => No accents here [1] => 这是一个功能 [2] => This is a feature (translated) [3] => 这份文件是很有光泽 [4] => This document is very shiny (translated) ) [price] => Array ( [0] => 0 ) [inStock] => Array ( [0] => 1 ) [_version_] => 1510294336239042560 ) )