Elasticsearch Cloud + Java REST Client Fuzzy Search


The new Elasticsearch JAVA REST client is here.

Let’s get right into it!

The Elastisearch JAVA REST client doesn’t seem to lend itself to dot notation a much as I’d prefer.

examples of dot notation:




I had to construct much of the search request using a handmade JSON string. I made use of the Apache HttpEntity to pass the constructed JSON to Elasticsearch. Since I took this approach, let’s look at how to first create the pure JSON query.

In the screenshot below, we have the Kibana search screen on the left, and on the right is the response. We perform a search by first and last name. Because we are using the fuzziness option we don’t have to properly spell the names. Below we left out a letter in the first name, and yet we are able to find a matching record, which you see on the right side of the image.


Now this next part is not difficult, it’s just a bit annoying. We need to construct this request string in Java. Our goal is a query to find a person named “Sean Wu”. Notice how we butcher the first name passed in and we are still able to locate the record, thanks to fuzzy matching!

String encodedBytes = Base64.getEncoder().encodeToString(“username:password”.getBytes());

Header[] headers = { new BasicHeader(HttpHeaders.CONTENT_TYPE, “application/json”), new BasicHeader(“Authorization”, “Basic ” + encodedBytes) };

RestClient r = RestClient .builder(new HttpHost(“url_to_elastic_cloud_endpoint”, 9243, “https”)) .setDefaultHeaders(headers).build();


String firstname =”San”;

String lastname=”Wu”;

HttpEntity entity = new NStringEntity(


“\”query\”: {“+

” \”bool\”: {“+

“\”must\”: [“+

“{“+          “\”match\”: {“+

“\”firstname\”: {“+

“\”query\”: \””+


“\”fuzziness\”: \”AUTO\””+


“}”+        “},”+


“\”match\”: {“+

“\”lastname\”: {“+

“\”query\”: \””+


“\”fuzziness\”: \”AUTO\””+









Map<String, String> paramMap = new HashMap<String, String>();

paramMap.put(“pretty”, “true”);

Response response = r.performRequest(“GET”, “/*/_search”, paramMap,entity);



System.out.println(“Host -” + response.getHost());

System.out.println(“RequestLine -” + response.getRequestLine()); System.out.println(response.toString());


try {


} catch (IOException e) {




There you have it!

Author: Michael Clayton


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: