tjSolrDoctrineBehaviorPlugin - 1.0.0

Doctrine behavior for indexing content with Solr

You are currently browsing
the website for symfony 1

Visit the Symfony2 website

« Back to the Plugins Home


Forgot your password?
Create an account



advanced search
Information Readme Releases Changelog Contribute
Show source


The tjSolrDoctrineBehaviorPlugin provides a Doctrine behavior to easily index and search model objects in the Solr search engine.


Plugin installation

You can install this plugin the usual way (RTFM), or if you want to work with the trunk:

$ cd plugins
$ git clone git://

Then activate the plugin in the config/ProjectConfiguration.class.php file.

Setting up Solr

The recommended Solr version is the latest (1.4). It is not tested with any other Solr version.

A Solr installation is already embedded in the plugin, in the lib/vendor/solr directory. It's a default installation, and the only modified file is the schema.xml.

If you want to use your own Solr installation, add those lines to the schema, in the "fields" section:

<!-- unique document id -->
<field name="sf_unique_id" type="string" indexed="true" stored="true" required="true" />
<!-- indexed object class -->
<field name="sf_meta_class" type="string" indexed="true" stored="true" required="true" />
<!-- indexed object id -->
<field name="sf_meta_id" type="sint" indexed="true" stored="true" required="true" />
<!-- default search field -->
<field name="sf_text" type="text" indexed="true" stored="true" multiValued="true" />

And after the fields definition:

<!-- Field to use to determine and enforce document uniqueness.
Unless this field is marked with required="false", it will be a required field
<!-- field for the QueryParser to use when an explicit fieldname is absent -->
<!-- copyField commands copy one field to another at the time a document
is added to the index.  It's used either to index the same field differently,
or to add multiple fields to the same field for easier/faster searching.
<copyField source="*_t" dest="sf_text" />
<copyField source="*_s" dest="sf_text" /

Once your configuration is correct, you can start Solr. Of course, you need a java installation.

$ cd plugins/tjSolrDoctrineBehaviorPlugin/lib/vendor/solr
$ java -jar start.jar

Solr in a production environment

In a production environment, you should run Solr as a daemon. The right way to do depends on your server's system, however, some startup scripts are included in the lib/vendor/scripts directory.

On a debian server :

$ cp plugins/tjSolrDoctrineBehaviorPlugin/lib/vendor/scripts/debian/solr /etc/init.d/solr
$ chmod 755 /etc/init.d/solr
$ update-rc.d solr defaults

Before running Solr, just set the PROJECT_NAME value to your symfony project directory.


The Solr index will be created in you data dir, and the logs will go in log dir. You have to create one last directory before we're ready.

$ mkdir logs/solr

More logging configuration can be found in the plugins/tjSolrDoctrineBehaviorPlugin/lib/vendor/solr/ file. You can check out some more documentation about logging here.

Then you can start the daemon:

$ /etc/init.d/solr start

Check this URL to be sure everything went fine.


How to use ?

Enabling the behavior

To index some model objects into Solr, you have to modify your schema.yml file. Add the Solr behavior to the object type you want to index, and define which fields needs to be indexed.

Here's an example schema file:

      type: string(255)
      notnull: true
      fields: [ title, body ]
      type: integer
      notnull: true
      type: string(255)
      notnull: true
      type: clob
      notnull: true
      onDelete: CASCADE
      foreignAlias: Posts

Rebuild your model, load your data, et voilà! Each time a Post object is created/updated/deleted, the Solr index will be automaticaly updated.

Field mapping

In the previous example, the plugin will try to index the title and body fields into Solr. You have to manualy define those names in the Solr schema, or indexing will fail :

<field name="title" type="text" indexed="true" stored="true" multiValued="false" />
<field name="body" type="text" indexed="true" stored="true" multiValued="false" />

You also have to make sure that those fiels are copied in the "sf_text" fields :

<copyField source="title" dest="sf_text" />
<copyField source="body" dest="sf_text" />

Configuring each field in the Solr schema can be a pain. That's why this plugin allows you to use Solr's dynamic fields.

If your model field's name matches some specific pattern, the Solr field will be automaticaly created. For example, each field suffixed with "_t" will be created with a "text" type, and copied into the "sf_text" default search field.

You can configure this mapping in the Doctrine schema :

      fields: [ title, body ]
      fieldmap: { title: title_t, body: body_t }

Look into the "dynamicField" entries in the Solr's schema to see available patterns.

Indexing virtual fields

Thanks to the Doctrine magic, it is very easy to index virtual fields. All you have to do is to add a custom getter in the model class. This way, you can even index some relations fields.

      fields: [ title, body, threadTitle ]
      fieldmap: { title: title_t, body: body_t, threadTitle: thread_t }

Add this getter in the Post class :

public function getThreadTitle()
  return $this->getThread()->getTitle();

Connecting to Solr

This plugins uses the default Solr connexion parameters. You can override them in the doctrine schema :

      fields: [ title, body ]
      fieldmap: { title: title_t, body: body_t }
      host: localhost
      post: 8389
      path: '/solr'

If you have a Solr installation with a multicore index, and want to index differents object types, just change the "path" parameter for each type.


Indexing is good, but searching is better.

Once you have attached the behavior to your model, it will provide a "search" method.

// returns true or false wether solr is available or not
$solrAvailable = Doctrine_Core::getTable('Post')->isSearchAvailable();
  throw new sfException('Search is unavailable right now. Please come back later');
$post = new Post();
$post->title = 'test title';
$post->body = 'this is my body';
$post->Thread = new Thread();
$post->Thread->title = 'test thread';
// returns every indexed elements
$results = Doctrine::getTable('Post')->search('*:*');
// search in every text fields
$results = Doctrine::getTable('Post')->search('test');
// search only in "title" field
$results = Doctrine::getTable('Post')->search('title_t:test');
// You can set the offset and limit params
$results = Doctrine::getTable('Post')->search('*:*', 0, 10);
// search can take extra params
$results = Doctrine::getTable('Post')->search('*:*', 0, 10, array('sort' => 'score desc', 'fl' => '*,score'));

The search methods retuns a php array corresponding to the Solr xml response.

$results = Doctrine::getTable('Post')->search('*:*');
array(2) {
  array(3) {
    array(7) {
      string(1) "0"
      string(3) "*:*"
      string(3) "map"
      string(4) "json"
      string(18) "sf_meta_class:Post"
      string(3) "1.2"
      string(2) "30"
  array(3) {
    array(1) {
      array(7) {
        string(6) "Post_9"
        string(4) "Post"
        string(24) "2010-02-06T15:16:30.523Z"
        array(1) {
          string(5) "title"
        array(2) {
          string(5) "title"
          string(4) "body"
        array(1) {
          string(4) "body"

Instead of a dummy php array, the plugin can also generate a Doctrine_Query object, which you can manipulate as usual. For instance, you can modify sorting options, paginate the list, add other criterias, etc.

$q = Doctrine::getTable('Post')->createSearchQuery('my query');
$maxResults = 50; // 256 is the function default, for a performance matter
$q2 = Doctrine::getTable('Post')->createSearchQuery('my other query', $maxResults);

There is a last available method to performs a search. You can use the solr:search task from the command line.

$ php symfony solr:search Post "my query"
$ php symfony help solr:search

reset index

Sometimes, you may want to reset the index and clear all indexed objects. There is a function to do this.

// remove all posts from solr index

You can also do this from the command line.

$ php symfony solr:reset-index Post
$ php symfony help solr:reset-index

This method will only remove objects from the current class (here: Post).


Solr supports transactions. By default, the plugins sends a commit message after every index operation. However, you may want to perform many operations in one time, then it is more efficient to send only one commit when the job's done.

$thread = new Thread();
$thread->title = 'test tread';
for($i = 0 ; $i < 20 ; $i++)
  $post = new Post();
  $post->title = "post $i";
  $post->body = 'post body';
  $post->Thread = $thread
// You can use the inTransaction function to know if a transaction exists
Doctrine_Core::getTable('Post')->inTransaction(); // returns true
// After the commit, data will be available for searching

Testing the plugin

This plugins comes with an auto-generated (with the sfTaskExtraPlugin) fixtures project, to run the tests without touching your own app. Tests are not included in the package version, so you'll have to checkout the trunk version.

Before you run the tests, make sure Solr is running is accessible. Note that those tests are written to be run with lime 2 (alpha1).

WARNING : By default, the tests will be run over the default Solr index. Make sure you won't lose any data.

Here's how you can easily run the plugin test suite :

  • export the SYMFONY shell var to the symfony lib path. Example :

    $ export SYMFONY='/var/www/myproject/lib/vendor/symfony-1.4.1/lib/'
  • Setup the database for testing

    The plugin's tests are made to run against an independant db. You have to create it before anything else.

    mysql> CREATE DATABASE solr_doctrine_behavior_test;
    mysql> GRANT ALL ON solr_doctrine_behavior_test.* TO test;

    If you want to use an existing database, you have to configure the database connexion by yourself

    $ php plugins/tjSolrDoctrineBehaviorPlugin/test/fixtures/project/symfony configure:database --env=test
  • build the bootstrap project. You don't have to load the fixtures, this will be done on time.

    $ php plugins/tjSolrDoctrineBehaviorPlugin/test/fixtures/project/symfony doctrine:build --env=test --all
  • run the tests

    $ php symfony test:plugin tjSolrDoctrineBehaviorPlugin

    or, if the sfTaskExtraPlugin is not installed :

    $ php plugins/tjSolrDoctrineBehaviorPlugin/test/bin/prove.php


I'd wish to thank the following persons for contributing to this plugin : * Guillaume Roques


Here's some ideas for further developpements:

  • Add an option to allow or not objects modifications when solr is unavailable
  • Add a task to batch index objects
  • Compatibility with the i18n behavior
  • Add geolocation search
  • add a moreLikeThis() function
  • add an option to set the default search field