Solr is a web application. Any sort of client application can use solr. The client requests to solr to do some functionalities and responds. Client applications can reach Solr by creating HTTP requests and parsing HTTP responses.
Query, index, delete, commit, and optimize are the most fundamental operations to work with Solr. Clients use these operations.
Many programming environments are ready to send HTTP requests and retrieve responses.
In PHP, SolrClient is used to connect solr and send requests to solr to perform different operations and retrieve responses.
PHP code to retrieve response:-
<?php
/**
* configurations
*/
$configuration_server = [
'hostname' => '127.0.0.1',
'port' => '8983',
'path' => 'solr/test_solr'
];
$solr_connection = new SolrClient ( $configuration_server );
/**
******** Add Documents ***********
*/
$docs = [
{
"id" : "978-0641723445",
"cat" : ["book","hardcover"],
"name" : "The Lightning Thief",
"author" : "Rick Riordan",
"series_t" : "Percy Jackson and the Olympians",
"sequence_i" : 1,
"genre_s" : "fantasy",
"inStock" : true,
"price" : 12.50,
"pages_i" : 384
},
{
"id" : "978-1423103349",
"cat" : ["book","paperback"],
"name" : "The Sea of Monsters",
"author" : "Jostein Gaarder",
"series_t" : "Percy Jackson and the Olympians",
"sequence_i" : 2,
"genre_s" : "fantasy",
"inStock" : true,
"price" : 6.49,
"pages_i" : 304
}
];
/**
******** code for Add Documents ***********
*/
$documents = [ ];
foreach ( $docs as $doc ) {
$solr_doc = new SolrInputDocument ();
foreach ( $doc as $field => $values ) {
if (is_array ( $values )) {
foreach ( $values as $value ) {
$solr_doc->addField ( $field, $value );
}
} else {
$solr_doc->addField ( $field, $values );
}
}
array_push ( $documents, $solr_doc );
}
try {
$solr_connection->addDocuments ( $documents, true, 1000 );
$solr_connection->commit ();
} catch ( Exception $e ) {
}
/**
******** Run Search Query with filter, facet, sorting ***********
*/
$query_text='*';
$filters = [
'author' => [
'Rick Riordan'
]
];
$facets = [
'cat',
'author',
'genre_s'
];
// KEY send
$query = new SolrQuery ( $query_text );
// Sort functionality
$query->addSortField ( 'id', 'asc' );
// filter query(fq)
foreach ( $filters as $field => $values ) {
if (is_array ( $values )) {
$query->addFilterQuery ( $field . ":(" . implode ( " OR ", $values ) . ")" );
} else {
$query->addFilterQuery ( $field . ":" . $values );
}
}
// Facet
foreach ( $facets as $facet ) {
$obj = [
str_replace ( '_facet', '', $facet ) => [
'type' => 'terms',
'field' => $facet,
'numBuckets' => true
]
];
$query->addParam ( 'json.facet', json_encode ( $obj ) );
}
//Response
$response = $solr_connection->query($query)->getResponse();
print_r($response);
?>
0 Comments