Day2 ElasticSearch: Java Query API

Arthur Lee
2 min readJan 19, 2019

--

Today I am going to try the query library for Elastic Search.

I think it is a easy part than environment setting.

Create a Client

client = new PreBuiltTransportClient(
Settings
.builder().put("client.transport.sniff", false)
.put("cluster.name","docker-cluster").build())
.addTransportAddress(new TransportAddress(InetAddress.getByName("localhost"), 9300));

Generate a dummy data

private void setupNaiveData() throws Exception {
XContentBuilder builderObject1 = getExampleObject("Mark", "15");
XContentBuilder builderObject2 = getExampleObject("Mark", "35");

client.prepareIndex("member", "Doe")
.setSource(builderObject1).get();
client.prepareIndex("member", "Doe")
.setSource(builderObject2).get();
}

So in the before setUp() will be the following:

Check the data is ready

Also, we can use postman to do that.

We created two new Mark and the yesterday Test . Now we have 3 data.

Query the result

We will use QueryBuilders to create a query.

Then, Using preareSearch() to do the query.

You also can build a boolQuery()

ClearUp

In the end, please not forget to close the connection.

@After
public void clearUp() {
client.close();
}

--

--

Arthur Lee
Arthur Lee

Written by Arthur Lee

An machine learning engineer in Bay Area in the United States

No responses yet