How to change path in SolrClient

156 views Asked by At

Regarding documentation one has to set the path (i.e. core) on initialization of SolrClient:

$client = new SolrClient([
    'hostname' => 'localhost',
    'port' => 8983,
    'path' => '/solr/coreXYZ',
]);

As I need access to multiple cores (ex. /solr/core_1, /solr/core_2), is there any way to dynamically change the path? I was not able to find any option for query or request method.

Edit

I found a way which worked also:

$client->setServlet(SolrClient::SEARCH_SERVLET_TYPE, '../' . $core . '/select');
$client->setServlet(SolrClient::UPDATE_SERVLET_TYPE, '../' . $core . '/update');

But this is a dirty hack only for me

1

There are 1 answers

1
MatsLindh On BEST ANSWER

Create a factory method and return different objects depending on which core you're accessing. Keeping object state that changes between which core you're requesting without being set explicitly through the query method is a recipe for weird bugs.

Something like the following pseudo-ish code (I don't have the Solr extension available, so I wasn't able to test this):

class SolrClientFactory {
    protected $cache = [];
    protected $commonOptions = [];

    public function __construct($common) {
        $this->commonOptions = $common;
    }

    public function getClient($core) {
        if (isset($this->cache[$core])) {
            return $this->cache[$core];
        }

        $opts = $this->commonOptions;

        // assumes $path is given as '/solr/'
        $opts['path'] .= $core;

        $this->cache[$core] = new SolrClient($opts);
        return $this->cache[$core];
    }
}

$factory = new SolrClientFactory([
    'hostname' => 'localhost',
    'port' => 8983,
    'path' => '/solr/',
]);

$client = $factory->getClient('coreXYZ');