Tuesday, September 30, 2014

How to insert data in solr using php


Inserting data into the Solr using PHP is very easy. When it comes to Solr there are two very important files namely config.xml & schema.xml. These files are the soul of solr. Schema.xml takes the control for data insertion. It comes with pre-defined field types. Schema.xml file defines type of fields, which field should be unique/primary key, which fields are required.
Lets have a simple example of students information like student roll number, name, medal, standard & date of birth. Below will be the schema defination for above fields. Find the <types> in schema.xml file & put the following code into <types> </types>.




RollNumber should be unique & always be an integer value. Name must be string contains alphanumeric charaters. You can see medal field type defination where we have multivalued true. This means we can store multiple values for each record like Gold, Silver, Bronze. We have used datetime field type to store the date of birth. We have done with the solr schema. Save this file & restart the Solr server. Make sure you restart the server whenever you edit both files schema & solrconfig.xml file.
Now lets add php snippet that adds students record into the database. You should have solr hostname, login, password etc details to create the object of solrClient.
$options = array
(
    'hostname' => SOLR_SERVER_HOSTNAME,
    'login'    => SOLR_SERVER_USERNAME,
    'password' => SOLR_SERVER_PASSWORD,
    'port'     => SOLR_SERVER_PORT,
    'path'     => SOLR_PATH_TO_SOLR,
);

$client = new SolrClient($options); 
// You can start loop for multiple records insertions here.

$doc = new SolrInputDocument(); // Create an object of Solr Document.

$doc->addField('RollNo', 12); 
$doc->addField('name', 'John Anderson');
$doc->addField('marks', 'Bronze');
$doc->addField('date', '$date');

Just add list of field names(id, name etc) as added in schema.xml.  

if(!empty($documents)) 
{
$client->addDocuments($documents); 
$client->commit();
$client->optimize(); 
}
You can refer Php-Solr manual also here

1 comment:

  1. Netguru Solution India Pvt. Ltd. is one of the leading and developing Website Design and Mobile Application Development Company in Pune with a specialist management and expert group.
    Website Design Company In Pune
    Mobile Application Development Company In Pune

    ReplyDelete