This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Try the fastest hosting platform with pay-as-you-go pricing & 24/7 expert support! MIGRATE NOW →

Using Elasticsearch in PHP sites on Cloudways

Updated on March 10, 2022

2 Min Read
elasticsearch php

Honestly speaking, before Elasticsearch having a decent search functionality on a PHP website was a distant dream. Yeah, there were some options but they hardly worked as you wanted them to.

The good thing about Elasticsearch is its ability to deep-search documents. We all know that Cloudways comes with Elasticsearch, regardless of the stack (plain PHP or otherwise) you launch. On Content Management System solutions, you get many plugins, addons, and extensions through which you can use to integrate Elasticsearch. But what about custom PHP sites?

Yeah, not exactly an easy task. Well, you are in luck as this post is for all those who want to use Elasticsearch in PHP sites. Let’s get started!

What is Elasticsearch

Elasticsearch is an open-source look server based on Apache Lucene. It performs super quick full-text and other complex searches. It also incorporates a REST API which allows us to effectively issue demands for making, erasing, upgrading, and recovering information.

Elasticsearch Client is a dispersed, free and open look and analytics motor for all sorts of information, including literary, numerical, geospatial, structured, and unstructured. Elasticsearch is built on Apache Lucene and was first released in 2010 by Elasticsearch N.V.

Supercharged Managed PHP Hosting – Improve Your PHP App Speed by 300%

Step 1: Choose Server

After you have created an account with Cloudways, choose your desired cloud provider from Vultr, DigitalOcean, Amazon, or Google. You need to select the PHP Stack.

DO installation

Now click on Launch Server. Wait till your server is fully launched. Once your server is launched, go to the Application Management tab and click on rename and name your application folder to elastic for now. This makes it easily accessible through the SSH terminal.

Step 2: Activating Elasticsearch

By default, the Elasticsearch PHP client is inactive on Cloudways. You need to enable it in order to use it. For this, go to your Server Management tab and scroll down to Server Settings & Packages section. Click on Plus sign (+)  to open this section. Now, click on the Packages tab. On that, you will see Elasticsearch is off. Now, click on the Edit Marker (Pencil icon) in the Elasticsearch field. A drop-down menu will open. Select Yes and click on Save.

Wait for the server to load your new package.

To confirm, go back to the same tab and you will see Elasticsearch is now turned on.

Step 3: Installing Elasticsearch-PHP API

The preferred way is by using the SSH terminal to create composer.json and then install it.

I will be using SSH to create the JSON file and install it. But first, take a backup. It is a good practice to make backups before you go on a new mission. 🙂

Let’s start.

  1. Go to the Server Management tab. Click on the Launch SSH terminal and log in with your details that can be found on that tab.
  2. Now we need to access your public_html folder to install Elasticsearch API. Type this command to reach there:
    cd applications/<app_name>/public_html
  3. Now, install composer.phar in this folder by using the following command.
    curl -s http://getcomposer.org/installer | php
  4. Now, let’s create our composer.json. Follow the following commands line by line to create it.
    php composer.phar init

    composer start
    Leave Package Name and Description empty by hitting Enter two times. Now set your Author Name according to this and hit Enter:

    Author: Your name <[email protected]>

    Now type “Yes” and hit Enter in order to search for required dependencies. Now search for Elasticsearch-PHP. When the search is complete, you will find a list of Elasticsearch dependencies for different frameworks.

    ssh terminal

    Now select the package number where you find elasticsearch/elasticsearch and hit Enter key. On define dev dependencies, type NN and hit Enter.

    ssh terminal
    On confirmation, type Yes and hit Enter. Your composer.json file is now created.

  5. Now, let us install Composer.json by typing the following command:php composer.phar install nodev

    composer install
    Elasticsearch API is now installed and ready-for-use.

Stop Wasting Time on Servers

Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.

Step 4: Using Elasticsearch-PHP API to Connect Custom PHP Site With Elasticsearch

Now, let’s edit our index.php file on our SSH terminal. Use this command:

vi index.php

You will see that your file has been viewed on your terminal. Now, start editing it. Now, press the Insert key on your keyboard. Move your cursor to:

echo '<h1>PHP Stack - Test Page</h1>';

Remove this whole line by backspace. Paste the following code in it by right-clicking and selecting “Paste from browser”.

require 'vendor/autoload.php';

$client = Elasticsearch\ClientBuilder::create()->build();

$params = [

    'index' => 'my_index',

    'type'  => 'my_type',

    'id'    => 'my_id',

    'body'  => ['testField' => 'abc'],

];

$response = $client->index($params);

print_r($response);

After pasting, your terminal will look like this:

code

Now press the ESC key and type :w this will save the index.php. Press the ESC key and type :q this will exit the viewer.

In the code above, we have created a new node named my_index, its type is my_type and its body has only one variable testField having value abc. This gets indexed by Elasticsearch running on the server.

Note: You can also edit the files by connecting to SFTP provided in Server Management tab under Master Credentials using the FTP client.

You might be interested in: How to Connect MySQL with Elasticsearch

Step 5: Running It:

Now go to the Application Management tab on your Cloudways Console and click on Application URL. You should see this result:

Array ( [_index] => my_index [_type] => my_type [_id] => my_id [_version] => 2 [created] => )

This means you have successfully connected your custom PHP code with Elasticsearch.

This is one of the easiest ways to integrate Elasticsearch in PHP site and use it. To learn more about Elasticsearch-PHP API, you can refer to its official page and use it on your PHP sites to make its search faster.

Alternate Method

You can create Composer.JSON using your favorite editor. Then, use SFTP to upload the file to public_html folder.

However, you have to go back to SSH for installation.

I am not a fan of this method. I think SSH-all-the-way is much easier.

Time to test

If you have a PHP cloud server on Cloudways, you should use Elasticsearch PHP client now. It’s awesome. If your current host is creating hurdles, you can test us out. Sign up for a free server on Cloudways PHP Hosting Platform and bring a testing website over to run your experiment with Elasticsearch-PHP API. I am convinced you will like it here.

Host PHP Websites with Ease [Starts at $10 Credit]

  • Free Staging
  • Free backup
  • PHP 8.0
  • Unlimited Websites

TRY NOW

Q: Elasticsearch-PHP vs Elastica: Which one should be used for developing web applications?

A: To integrate Elasticsearch in PHP applications, there are two libraries available i.e. Elastica & Elasticsearch-PHP.
Elastica is a non-official community project, while the Elasticsearch-PHP is an official PHP client for installing Elasticsearch. It is better to use Elasticsearch-PHP in web applications, as it supports various JSON requests which Elastica does not.

Q: What is Elasticsearch and how does it work?

A: Elasticsearch is a highly scalable web tool that provides fast full-text searches. It allows users to store, organize and search huge amounts of data, records etc. within seconds. It can be said as a standalone database server that takes data and stores it an organized manner for later fast & language-based searches.

Q: Can I use Elasticsearch as a database?

A: Yes, you can use Elasticsearch as a database, but keep in mind that it is a distributed NoSQL database. It uses documents rather than schema tables, hence doesn’t provide normal database functionalities like joins, transactions etc.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Shahzeb Ahmed

Shahzeb is a Digital Marketer with a Software Engineering background, works as a Community Manager — PHP Community at Cloudways. He is growth ambitious and aims to learn & share information about PHP & Laravel Development through practice and experimentation. He loves to travel and explore new ideas whenever he finds time. Get in touch with him at [email protected]

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now