Let us see how we can use PHP code along with Solarium library to update documents in Solr.
smith
in our index.http://localhost:8080/solr/collection1/select/?q=smith
numFound=0
, which means that there are no such documents. Let us add a book to our index with the last name of the author as smith
.$updateQuery = $client->createUpdate(); $testdoc = $updateQuery->createDocument(); $testdoc->id = 123456789; $testdoc->cat = 'book'; $testdoc->name = 'Test book'; $testdoc->price = 5.99; $testdoc->author = 'Hello Smith'; $updateQuery->addDocument($testdoc); $updateQuery->addCommit(); $client->update($updateQuery);
Smith
. Let us now update the author's name to Jack Smith
and the price tag to 7.59
:$testdoc = $updateQuery->createDocument(); $testdoc->id = 123456789; $testdoc->cat = 'book'; $testdoc->name = 'Test book'; $testdoc->price = 7.59; $testdoc->author = 'Jack Smith'; $updateQuery->addDocument($testdoc, true); $updateQuery->addCommit(); $client->update($updateQuery);
The process to update a document in Solr is similar to that of adding a document in Solr except for the fact that we have to set the overwrite
flag to true
. If no parameter is set, Solarium will not pass any flag to Solr. But on the Solr end, the overwrite
flag is by default set to true
. So any document to Solr will replace a previous document with the same unique key.
Solr internally does not have an update command. In order to update a document, when we provide the unique key and the overwrite flag, Solr internally deletes and inserts the document again.
We will need to add all fields of the document again, even fields that are not required to be updated. Since Solr will be deleting the complete document and inserting the new document.
Another interesting parameter in the method signature is the commit within time.
$updateQuery->addDocument($doc1, $overwrite=true, $commitwithin=10000)
The preceding code asks Solr to overwrite the document and commit within 10 seconds. This is explained later in this chapter.
We can also use the addDocuments(array($doc1, $doc2))
command to update multiple documents in a single call.
18.191.105.15