Zend Lucene And PDF Documents Part 3: Indexing The Documents

5th November 2009

Last time we had reached the stage where we had PDF meta data and the extracted contents of PDF documents ready to be fed into our search indexing classes so that we can search them.

The first thing that is needed is a couple of configuration options to be set up. This will control where our Lucene index and the PDF files to be indexed will be kept. Add the following options to your configuration files (called application.ini if you used Zend Tool to create your applcation).

  1. luceneIndex = \path\to\lucene\index
  2. filesDirectory = \path\to\pdf\files\

You can load these options into the the Zend_Registry by using the following method in your Bootstrap.php file.

  1. protected function _initConfigLoad()
  2. {
  3. $config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', APPLICATION_ENV);
  4. Zend_Registry::set('config', $config);
  5. }

The APPLICATION_ENV constant should be defined in the index file.

Next we need some way of getting our application to index all of our PDF files, to do this I created an action in the Index conrtoller called indexpdfAction(). What this function will do is run through every file in our PDF folder and add it to our Lucene index. When finished indexing the action will send the number of documents in the index and the index size to the view so that we can see how many files were indexed. The following code block contains the full source code for that action. Note that this code won't run because most of the code behind it doesn't exist yet.

  1. public function indexpdfsAction() {
  2. $config = Zend_Registry::get('config');
  3. $appLucene = App_Search_Lucene::open($config->luceneIndex);
  4. $globOut = glob($config->filesDirectory . '*.pdf');
  5. if (count($globOut) > 0) { // make sure the glob array has something in it
  6. foreach ($globOut as $filename) {
  7. $index = App_Search_Lucene_Index_Pdfs::index($filename, $appLucene);
  8. }
  9. }
  10. $appLucene->commit();
  11. if ($appLucene != null) {
  12. $this->view->indexSize = $appLucene->count();
  13. $this->view->documents = $appLucene->numDocs();
  14. }
  15. }

The first line of this code deals with getting our config object from the registry so that we can use it to find out where our Lucene index and PDF documents are on the file system.

The next line calls the static open() method of a class called App_Search_Lucene and passes the location of our Lucene index. This class extends the Zend_Search_Lucene object so that we can have an extra level of control when adding and deleting documents from our index, as well as creating the index in the first place. We are using an extension to control how documents are added to our index because it is not possible to update a document through Zend_Search_Lucene, we must first delete the document before re-adding it to our index.

The open() method tries to open the Lucene index via the use of a class called Zend_Search_Lucene_Proxy, if the index doesn't exist yet then it is created using the create() method. The Zend_Search_Lucene_Proxy object is used to provide a gateway between our application and the methods available in the Zend_Search_Lucene object, but still allow us to control how files are added to the index.

  1. class App_Search_Lucene extends Zend_Search_Lucene
  2. {
  3. /**
  4.   * Create a new index.
  5.   *
  6.   * @param string $directory The location of the Lucene index.
  7.   * @return Zend_Search_Lucene_Proxy The Lucene index.
  8.   */
  9. public static function create($directory)
  10. {
  11. return new Zend_Search_Lucene_Proxy(new App_Search_Lucene($directory, true));
  12. }
  13.  
  14. /**
  15.   * Open the index. If the index does not exist then one will be created and
  16.   * returned.
  17.   *
  18.   * @param string $directory The location of the Lucene index.
  19.   * @return Zend_Search_Lucene_Proxy The Lucene index.
  20.   */
  21. public static function open($directory)
  22. {
  23. try {
  24. // Attempt to open the index.
  25. return new Zend_Search_Lucene_Proxy(new App_Search_Lucene($directory, false));
  26. } catch (Exception $e) {
  27. // Return a newly created index using the create method of this class.
  28. return self::create($directory);
  29. }
  30. }
  31.  
  32. /**
  33.   * Add a document to the index.
  34.   *
  35.   * @param Zend_Search_Lucene_Document $document The document to be added.
  36.   * @return Zend_Search_Lucene
  37.   */
  38. public function addDocument(Zend_Search_Lucene_Document $document)
  39. {
  40. // Search for documents with the same Key value.
  41. $term = new Zend_Search_Lucene_Index_Term($document->Key, 'Key');
  42. $docIds = $this->termDocs($term);
  43.  
  44. // Delete any documents found.
  45. foreach ($docIds as $id) {
  46. $this->delete($id);
  47. }
  48.  
  49. return parent::addDocument($document);
  50. }
  51. }

The second object we use in this application is called App_Search_Lucene_Index_Pdfs. This has a single method called index() which takes two parameters. The first is the path to the PDF document and the second is the Lucene index. What this method does is to find out as much information about the PDF document as possible and then add the document to the Lucene index. It does this last part by creating an instance of an object called App_Search_Lucene_Document (explained later on in the post) and sends this to the addDocument() method of the App_Search_Lucene object. This class is where all of the code from the previous two posts comes into play. After opening the PDF document the object then reads the meta data into an array before extracting the textual content of the PDF and adding this to the array. This class is fairly self explainitory and uses code that you have already seen in this series so I won't go into it in great detail. I have put comments within the code at key points to explain what is going on.

  1. class App_Search_Lucene_Index_Pdfs
  2. {
  3. /**
  4.   * Extract data from a PDF document and add this to the Lucene index.
  5.   *
  6.   * @param string $pdfPath The path to the PDF document.
  7.   * @param Zend_Search_Lucene_Proxy $luceneIndex The Lucene index object.
  8.   * @return Zend_Search_Lucene_Proxy
  9.   */
  10. public static function index($pdfPath, $luceneIndex)
  11. {
  12. // Load the PDF document.
  13. $pdf = Zend_Pdf::load($pdfPath);
  14. $key = md5($pdfPath);
  15.  
  16. /**
  17.   * Set up array to contain the document index data.
  18.   * The Filename will be used to retrive the document if it is found in
  19.   * the search resutls.
  20.   * The Key will be used to uniquely identify the document so we can
  21.   * delete it from the search index when adding it.
  22.   */
  23. $indexValues = array(
  24. 'Filename' => $pdfPath,
  25. 'Key' => $key,
  26. 'Title' => '',
  27. 'Author' => '',
  28. 'Subject' => '',
  29. 'Keywords' => '',
  30. 'Creator' => '',
  31. 'Producer' => '',
  32. 'CreationDate' => '',
  33. 'ModDate' => '',
  34. 'Contents' => '',
  35. );
  36.  
  37. // Go through each meta data item and add to index array.
  38. foreach ($pdf->properties as $meta => $metaValue) {
  39. switch ($meta) {
  40. case 'Title':
  41. $indexValues['Title'] = $pdf->properties['Title'];
  42. break;
  43. case 'Subject':
  44. $indexValues['Subject'] = $pdf->properties['Subject'];
  45. break;
  46. case 'Author':
  47. $indexValues['Author'] = $pdf->properties['Author'];
  48. break;
  49. case 'Keywords':
  50. $indexValues['Keywords'] = $pdf->properties['Keywords'];
  51. break;
  52. case 'CreationDate':
  53. $dateCreated = $pdf->properties['CreationDate'];
  54.  
  55. $distance = substr($dateCreated, 16, 2);
  56. if (!is_long($distance)) {
  57. $distance = null;
  58. }
  59. // Convert date from the PDF format of D:20090731160351+01'00'
  60. $dateCreated = mktime(substr($dateCreated, 10, 2), //hour
  61. substr($dateCreated, 12, 2), //minute
  62. substr($dateCreated, 14, 2), //second
  63. substr($dateCreated, 6, 2), //month
  64. substr($dateCreated, 8, 2), //day
  65. substr($dateCreated, 2, 4), //year
  66. $distance); //distance
  67. $indexValues['CreationDate'] = $dateCreated;
  68. break;
  69. case 'Date':
  70. $indexValues['Date'] = $pdf->properties['Date'];
  71. break;
  72. }
  73. }
  74.  
  75. /**
  76.   * Parse the contents of the PDF document and pass the text to the
  77.   * contents item in the $indexValues array.
  78.   */
  79. $pdfParse = new App_Search_Helper_PdfParser();
  80. $indexValues['Contents'] = $pdfParse->pdf2txt($pdf->render());
  81.  
  82. // Create the document using the values
  83. $doc = new App_Search_Lucene_Document($indexValues);
  84. if ($doc !== false) {
  85. // If the document creation was sucessful then add it to our index.
  86. $luceneIndex->addDocument($doc);
  87. }
  88.  
  89. // Return the Lucene index object.
  90. return $luceneIndex;
  91. }
  92. }

The Key attribute is used to uniquely identify the file in the index quickly and easily. For this class I have made it an md5 of the filename, but this can be changed to something different.

The App_Search_Lucene_Document class is the one class that needs the most explanation, mainly due to the decisions made when creating it. The class extends the Zend_Search_Lucene_Document class and so acts just like a normal Lucene document. The constructor is passed a single parameter containing an associative array of values that are to be written to the document. The rest of this class then deals with adding the items of the array to the document as field objects. The following code block contains the source code for this class.

  1. class App_Search_Lucene_Document extends Zend_Search_Lucene_Document
  2. {
  3.  
  4. /**
  5.   * Constructor.
  6.   *
  7.   * @param array $values An associative array of values to be used
  8.   * in the document.
  9.   */
  10. public function __construct($values)
  11. {
  12. // If the Filename or the Key values are not set then reject the document.
  13. if (!isset($values['Filename']) && !isset($values['key'])) {
  14. return false;
  15. }
  16.  
  17. // Add the Filename field to the document as a Keyword field.
  18. $this->addField(Zend_Search_Lucene_Field::Keyword('Filename', $values['Filename']));
  19. // Add the Key field to the document as a Keyword.
  20. $this->addField(Zend_Search_Lucene_Field::Keyword('Key', $values['Key']));
  21.  
  22. if (isset($values['Title']) && $values['Title'] != '') {
  23. // Add the Title field to the document as a Text field.
  24. $this->addField(Zend_Search_Lucene_Field::Text('Title', $values['Title']));
  25. }
  26.  
  27. if (isset($values['Subject']) && $values['Subject'] != '') {
  28. // Add the Subject field to the document as a Text field.
  29. $this->addField(Zend_Search_Lucene_Field::Text('Subject', $values['Subject']));
  30. }
  31.  
  32. if (isset($values['Author']) && $values['Author'] != '') {
  33. // Add the Author field to the document as a Text field.
  34. $this->addField(Zend_Search_Lucene_Field::Text('Author', $values['Author']));
  35. }
  36.  
  37. if (isset($values['Keywords']) && $values['Keywords'] != '') {
  38. // Add the Keywords field to the document as a Keyword field.
  39. $this->addField(Zend_Search_Lucene_Field::Keyword('Keywords', $values['Keywords']));
  40. }
  41.  
  42. if (isset($values['CreationDate']) && $values['CreationDate'] != '') {
  43. // Add the CreationDate field to the document as a Text field.
  44. $this->addField(Zend_Search_Lucene_Field::Text('CreationDate', $values['CreationDate']));
  45. }
  46.  
  47. if (isset($values['ModDate']) && $values['ModDate'] != '') {
  48. // Add the ModDate field to the document as a Text field.
  49. $this->addField(Zend_Search_Lucene_Field::Text('ModDate', $values['ModDate']));
  50. }
  51.  
  52. if (isset($values['Contents']) && $values['Contents'] != '') {
  53. // Add the Contents field to the document as an UnStored field.
  54. $this->addField(Zend_Search_Lucene_Field::UnStored('Contents', $values['Contents']));
  55. }
  56. }
  57. }

There are five different types of field objects available, and each acts in a different way. The three field types I have used in this class are Keyword, Text and UnStored. Here is a brief explanation of each and why they were chosen.

  • Keyword - These fields are stored and indexed and so are available when searching. However, no processing or tokenizing is done on the string so the entire string is stored as is. I selected this for the Filename and Key fields because it is best for strings that are searched for in full
  • Text - Text fields are stored, indexed and tokenized. The majority of fields in this class are stored as text fields as they shouldn't be too long and can be displayed in the search results if we need them to.
  • UnStored - UnStored fields are treated like Text fields except that they are not stored within the index. This type of field is ideal when dealing with potentially large amounts of text and as a result the Contents are dealt with in this way. Rather than take up disk space and store the entire document in the index it is best to allow Lucene to tokenize the text so that it can be searched. Using the UnStored field means that we can't print out the field in our search results, but there isn't any need to here as we will have all the information needed to describe and provide a link to our PDF documents.

See the Zend Search Lucene field types documentation for more information about the different types of fields available in Zend_Search_Lucene.

The App_Search_Lucene_Document class will return false in the constructor if the Filename or Key values are not present. It would be possible to create the Key within this class but it made sense to keep the processing of the data in the App_Search_Lucene_Index_Pdfs class and the document creation in the App_Search_Lucene_Document completely separate.

Remember that all class names are dependent on their location within the library folder of our application. So the class App_Search_Lucene_Index_Pdfs is called Pdfs.php and would be located in \App\Search\Lucene\Index. For clarity I have written out where each file should be located.

  1. --application
  2. --library
  3. ----App
  4. ------Search
  5. --------Helper
  6. ----------PdfParser.php
  7. --------Lucene
  8. ----------Index
  9. ------------Pdfs.php
  10. --------Document.php
  11. ------Lucene.php
  12. ----Zend

This directory structure allows for future change if we want to add different file types to our indexing service, or even change to a different search engine like Xapian.

In the next instalment of Zend Lucene and PDF documents I will be showing you how to add a search form to the application, so that we can search for the documents we have indexed. I will be making all of the source code available in the final episode so keep posted if you want to get hold of it.

Comments

Permalink
Hello, Thank you very much for this tutorials, i have a question: In your class App_Search_Lucene_Index_Pdfs you wrote $pdfParse = new App_Search_Helper_PdfParser(); normally the class App_Search_Helper_PdfParser must be defined! where can i find it? thnks in advance.

Omar (Tue, 01/08/2013 - 09:49)

Add new comment

The content of this field is kept private and will not be shown publicly.