WebSenor

Using Elasticsearch with PHP a simple guide

Elasticsearch is an open-source full-text search engine which allows you to store and search data in real time. You can search for phrases as well and it will give you the results within seconds depending on how large the Elasticsearch database is. This engine outputs results faster than SQL and is one of the most used search around the web. There are two ways you can use Elasticsearch with PHP; one with using curl and the other by using official client of Elasticsearch for PHP. In this tutorial I will show you how to use Elasticsearch using its PHP Client. Before we start, make sure that Elasticsearch is installed on your local machine. Here’s how you can do it:

Installing Elasticsearch for PHP

We will install it using composer. In your localhost root folder, create a new directory and name it elastic_php. In the same directory, create a new file composer.json and paste the following text in it:

Run composer install. Now that we have have installed it, let’s connect it with PHP.

Connecting Elasticsearch with PHP

Now create a new PHP script file and name it index.php inside the elastic_php directory and paste the following code in it:

Save it and run the script. Make sure Elasticsearch is running or you will get a connection error.

Indexing data in Elasticsearch

Now that we are connected to Elasticsearch, let’s index some data in it. Open your index.php file and change the following code in it.

When you run the above code you will get 1 as output.

Getting data from Elasticsearch

Now we have an index, let’s get data from it. Now replace the code with the following in your index.php and run it:

You will get the field that we have added.

Adding My First Field In Elasticsearch

Searching in Elasticsearch

Let’s search for some data in Elasticsearch. Now open your index.php file again replace it with the following code.

Now let’s understand the code a bit. When we search for our query in Elasticsearch it returns with a lot of results including our specific query result. We need to fetch our result from it and for that, first we need to check how many results we have:

Then we fetch our results from it which will be less than its hits because it’s an array.

After that we print the result in a browser. Now run the code provided above and you will get the following result (again):

Adding My First Field In Elasticsearch

Conclusion

In this tutorial you learned how to connect Elasticsearch with PHP and how to save and retrieve data from it. You also learned how to perform a search with PHP and Elasticsearch. If there is anything that confuses you, please leave a comment below and we’ll come up with the solution for you!

Download App

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor

d

Contact