Using Elastica to query elasticsearch

The last couple of months I have been playing around with elasticsearch, an open source, distributed, RESTful search engine built on top of Apache Lucene. To interact with elasticsearch in PHP I have been using a client called Elastica. This was all fun and games until I needed to do actual queries, which is what our users will be doing most of the time.

Elastica’s documentation does not (yet) say anything about how to search using the client, so I needed to dig through the code to see if I could find some solutions. Some different methods exist, and I’ll present some of them here using different types of queries.

Note: The remainder of this post requires some understanding on how elasticsearch work. I will post more on this subject on this blog in the coming weeks.

Imagine indexing this very blog in elasticsearch, using the following mapping (with cURL):

Simple URI-based queries

Let’s start with a really simple query using cURL:

Using Elastica to perform the same query is pretty straight forward:

Complex queries using filters, facets, sorting and more

More complex queries in elasticsearch can be accomplished by including the query in the request body. A filtered query using facets, sorting and from/size (offset/limit) using cURL can look like this:

Queries like the one above can be created in Elastica in many different ways. We can use the query builder and simply pass in the same query as used with cURL:

or, we can build the query using the fluent API of Elastica’s query builder (indentation used for increased readability):

or, we can build our query using a set of objects:

There are probably more ways to do queries with Elastica as well, and hopefully Elastica’s docs will improve in the future. Feel free to comment if you know about other ways to do the same queries used in this post, or if you need help running other types of queries. Happy searching!

Read more from the Software engineering category