Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

enadabuzaid's avatar

solr apache with Laravel ?

can explain more details about Solr and how can use it in Laravel?

0 likes
10 replies
LaryAI's avatar
Level 58

Apache Solr is an open-source search platform built on Apache Lucene. It provides full-text search, hit highlighting, faceted search, real-time indexing, dynamic clustering, database integration, and rich document handling. Integrating Solr with Laravel can significantly enhance the search capabilities of your application.

To use Solr with Laravel, you can follow these steps:

  1. Install Solr: You need to have Solr installed on your server. You can download it from the official website (http://lucene.apache.org/solr/) and follow the installation instructions for your specific operating system.

  2. Configure Solr: After installation, you'll need to configure a Solr core for your application. A Solr core is essentially a running instance of a Lucene index along with all the Solr configuration required to use it.

  3. Install a Laravel Package for Solr: While you can interact with Solr using raw HTTP requests, it's more convenient to use a package. One such package is solarium/solarium. You can install it via Composer:

composer require solarium/solarium
  1. Configure the Laravel Service Provider: After installing the package, you may need to set up a service provider to configure the Solarium client. You can do this by creating a new service provider or by adding the configuration to the AppServiceProvider.

Here's an example of how you might configure the Solarium client in a service provider:

use Solarium\Client;

// ...

public function register()
{
    $this->app->singleton(Client::class, function ($app) {
        $config = [
            'endpoint' => [
                'localhost' => [
                    'host' => '127.0.0.1',
                    'port' => 8983,
                    'path' => '/',
                    'core' => 'your_core_name',
                ]
            ]
        ];

        return new Client($config);
    });
}
  1. Indexing Data: To make your Laravel models searchable, you'll need to index their data in Solr. You can do this by creating a command or a job that reads your models and sends their data to Solr.

Here's a very basic example of how you might index a model:

use App\Models\Post;
use Solarium\Client;

// ...

public function indexPosts(Client $client)
{
    $update = $client->createUpdate();

    Post::all()->each(function ($post) use ($update) {
        $document = $update->createDocument();
        $document->id = $post->id;
        $document->title = $post->title;
        $document->content = $post->content;

        $update->addDocument($document);
    });

    $update->addCommit();
    $client->update($update);
}
  1. Searching: To perform a search, you can use the Solarium client to build a query and then execute it.

Here's an example of how you might perform a search:

use Solarium\Client;

// ...

public function searchPosts(Client $client, $query)
{
    $select = $client->createSelect();
    $select->setQuery($query);

    $resultset = $client->select($select);

    foreach ($resultset as $document) {
        echo 'Id: '.$document->id.' Title: '.$document->title.PHP_EOL;
    }
}

Remember to handle exceptions and errors appropriately, and to secure your Solr server, especially if it's accessible over the internet.

This is a basic overview of how you might integrate Solr with Laravel. Depending on your application's needs, you may need to delve deeper into Solr's features and the Solarium package's documentation.

tisuchi's avatar

@enadabuzaid Can you be most explicit about what exactly you want to know?

Solr and how can use it in Laravel?

2 likes
enadabuzaid's avatar

@tisuchi Firstly, I want to know whether to use Solr or Elasticsearch. and how Solar Can help me in big filtration for Properties with many filters for example

  • I have filter area, number of rooms, number of flowers, house size, and so on ....

Secondly, I just want to learn more and try to improve my skills ..

2 likes
tisuchi's avatar

@enadabuzaid Looking at your scenario (even without knowing the details of business logic), both of the services can handle it properly. Now the question is, which one do you want to use?

If you have a chance to choose (alternatively you are building your application from sketch), I would recommend using elasticsearch instead of Solr because Solr is cumbersome to maintain. In addition, the interface for elastic search is user-friendly and modern.

Luckily, I have experience with both, unfortunately, I struggled to handle SOLR.

Secondly, I just want to learn more and try to improve my skills ..

To improve your skills, you may check the documentation/tutorial. There should be some course. You may take advantage from there.

2 likes
enadabuzaid's avatar

@tisuchi, thank you. to be honest it is required to know that in Solr because it is a free and open-source.

or if suggest something like solar, elasticsearch the price it is low.

and what is your advice to start applying and learning this feature?

2 likes
tisuchi's avatar
tisuchi
Best Answer
Level 70

@enadabuzaid

and what is your advice to start applying and learning this feature?

Personally, I explored based on the existing project where I was working. Maybe if you have any chance, try to explore this way.

or if suggest something like solar, elasticsearch the price it is low.

I don't know honestly. Maybe you can search on google to get an open-source alternative to them. :)

3 likes
enadabuzaid's avatar

@tisuchi Hello, I connected with the Solr Successfully but I have an Issue when trying to index

this indexPropery in SolarServcose

class SolrService
{
    protected $client;

    public function __construct()
    {
        $adapter = new Curl();
        $eventDispatcher = new EventDispatcher();

        $config = config('solr.endpoint.localhost');

        $this->client = new Client($adapter, $eventDispatcher, $config);

    }

public function indexProperty(Property $property)
    {
        $update = $this->client->createUpdate();

        $doc = $update->createDocument();
        $doc->id = $property->id;
        $doc->title = $property->title;
        $doc->description = $property->description;
        $doc->category = $property->category;
        $doc->price = $property->price;

        $update->addDocument($doc);
        $update->addCommit();

        return $this->client->update($update);
    }

}

this is when testing the Connection

public function ping()
    {
        try {
            $ping = $this->client->createPing();
            return $this->client->ping($ping);
        } catch (\Exception $e) {
            return 'Error: ' . $e->getMessage();
        }
    }

here created Command to index the properties

class IndexProperties extends Command
{
    protected $signature = 'properties:index';
    protected $description = 'Index all properties in Solr';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $solrService = resolve(SolrService::class);
        Property::all()->each(function ($property) use ($solrService) {
            $solrService->indexProperty($property);
        });

        $this->info('All properties have been indexed.');

    }
}

when execute the command

sail php artisan properties:index


I get this error :

 Solarium\Exception\HttpException 

  Solr HTTP error: Neither collection nor core set. (404)
#0 /var/www/html/vendor/solarium/solarium/src/Core/Client/Adapter/AdapterHelper.php(38): Solarium\Core\Client\Endpoint->getBaseUri()
#1 /var/www/html/vendor/solarium/solarium/src/Core/Client/Adapter/Curl.php(84): Solarium\Core\Client\Adapter\AdapterHelper::buildUri()
#2 /var/www/html/vendor/solarium/solarium/src/Core/Client/Adapter/Curl.php(179): Solarium\Core\Client\Adapter\Curl->createHandle()
#3 /var/www/html/vendor/solarium/solarium/src/Core/Client/Adapter/Curl.php(41): Solarium\Core\Client\Adapter\Curl->getData()
#4 /var/www/html/vendor/solarium/solarium/src/Core/Client/Client.php(848): Solarium\Core\Client\Adapter\Curl->execute()
#5 /var/www/html/vendor/solarium/solarium/src/Core/Client/Client.php(819): Solarium\Core\Client\Client->executeRequest()
#6 /var/www/html/vendor/solarium/solarium/src/Core/Client/Client.php(901): Solarium\Core\Client\Client->execute()

2 likes
tisuchi's avatar

@enadabuzaid have you created the core?

  • You have to create core
  • Then you need to mention in the configuration, which core you are going to use.

2 likes
enadabuzaid's avatar
return [
    'endpoint' => [
        'localhost' => [
            'host' => env('SOLR_HOST', 'localhost'),
            'port' => env('SOLR_PORT', 8983),
            'path' => env('SOLR_PATH', '/solr'),
            'core' => env('SOLR_CORE', 'mycore'),
        ],
    ],
];

yes I create mycore it is worl and I can see it in this url http://localhost:8983/solr/#/mycore/query

and this ```http://localhost:8983/solr/admin/cores?action=STATUS````

{
  "responseHeader":{
    "status":0,
    "QTime":1
  },
  "initFailures":{ },
  "status":{
    "mycore":{
      "name":"mycore",
      "instanceDir":"/var/solr/data/mycore",
      "dataDir":"/var/solr/data/mycore/data/",
      "config":"solrconfig.xml",
      "schema":"managed-schema.xml",
      "startTime":"2024-01-11T10:23:08.276Z",
      "uptime":82645360,
      "index":{
        "numDocs":0,
        "maxDoc":0,
        "deletedDocs":0,
        "version":2,
        "segmentCount":0,
        "current":true,
        "hasDeletions":false,
        "directory":"org.apache.lucene.store.NRTCachingDirectory:NRTCachingDirectory(MMapDirectory@/var/solr/data/mycore/data/index lockFactory=org.apache.lucene.store.NativeFSLockFactory@2d4e099; maxCacheMB=48.0 maxMergeSizeMB=4.0)",
        "segmentsFile":"segments_1",
        "segmentsFileSizeInBytes":69,
        "userData":{ },
        "sizeInBytes":69,
        "size":"69 bytes"
      }
    }
  }
}
2 likes

Please or to participate in this conversation.