Using the HTTP protocol
This recipe shows us the usage of the HTTP protocol with an example.
Getting ready
You need a working instance of the ElasticSearch cluster. Using default configuration, ElasticSearch enables port number 9200 on your server to communicate in HTTP.
How to do it...
The standard RESTful protocol is easy to integrate.
We will see how easy it is to fetch the ElasticSearch greeting API on a running server on port 9200 using different programming languages:
- In BASH, the request will be:
curl –XGET http://127.0.0.1:9200
- In Python, the request will be:
import urllib result = urllib.open("http://127.0.0.1:9200")
- In Java, the request will be:
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; … truncated… try{ // get URL content URL url = new URL("http://127.0.0.1:9200"); URLConnection conn = url.openConnection();// open the stream and put it into BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; while ((inputLine = br.readLine()) != null){ System.out.println(inputLine); } br.close(); System.out.println("Done"); } Catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); }
- In Scala, the request will be:
scala.io.Source.fromURL("http://127.0.0.1:9200","utf-8").getLines.mkString("\n")
For every language sample, the response will be the same:
{ "ok" : true, "status" : 200, "name" : "Payge, Reeva", "version" : { "number" : "1.4.0", "snapshot_build" : false }, "tagline" : "You Know, for Search" }
How it works...
Every client creates a connection to the server index /
and fetches the answer. The answer is a valid JSON object. You can invoke the ElasticSearch server from any language that you like.
The main advantages of this protocol are:
- Portability: This uses Web standards so that it can be integrated in different languages (Erlang, JavaScript, Python, Ruby, and so on) or called via a command-line application such as cURL.
- Durability: The REST APIs don't change often. They don't break for minor release changes as native protocol does.
- Simple to use: This has JSON-to-JSON interconnectivity.
- Good support: This has much more support than other protocols. Every plugin typically supports a REST endpoint on HTTP.
- Easy cluster scaling: You can simply put your cluster nodes behind an HTTP load balancer to balance the calls such as HAProxy or NGinx.
In this book, a lot of the examples are done by calling the HTTP API via the command-line cURL program. This approach is very fast and allows you to test functionalities very quickly.
There's more...
Every language provides drivers for best integration with ElasticSearch or RESTful web services.
The ElasticSearch community provides official drivers that support the most used programming languages.