ElasticSearch: Java API
ElasticSearch provides Java API, thus it executes all operations asynchronously by using client object. Client object can execute the operations in bulk, cumulatively. Java API can be used internally in order to execute all APIs in ElasticSearch.
In this tutorial, we will consider how to carry out some operations with Java API in a standalone Java application that is similar to the ones we made in the previous article with the console.
Dependency
ElasticSearch is hosted on Maven central. In your Maven Project, you can define which ElasticSearch version you want to use in your pom.xml file as shown below:
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>0.90.3</version>
</dependency>
Client
Using client, you can perform administrative tasks in a running cluster, and some operations, such as standard index, get, delete and search operations, in an existing cluster. Also, you can launch all of the nodes.
The most common way of obtaining an ElasticSearch client is creating an embedded node which acts like a node in a cluster and then requesting a client from that embedded node.
Another way of obtaining a client is creating a TransportClient (it connects from remote by using transport module) which connects to a cluster.
One should consider using the same version of client and cluster while using Java API. The difference between client and cluster versions may cause some incompatibilities.
Node Client
The simplest way of getting a client instance is the node based client.
Node node = nodeBuilder().node();
Client client = node.client();
When a node is started, it joins to the "elasticsearch" cluster. You can create different clusters using the cluster.name setting or clusterName method in the /src/main/resources directory and in elasticsearch.yml file in your project:
cluster.name: yourclustername
Or in Java code:
Node node = nodeBuilder().clusterName("yourclustername").node();
Client client = node.client();
Creating Index
The Index API allows you to type a JSON document into a specific index, and makes it searchable. There are different ways of generating JSON documents. Here we used map, which represents JSON structure very well.
public static Map<String, Object> putJsonDocument(String title, String content, Date postDate,
String[] tags, String author){
Map<String, Object> jsonDocument = new HashMap<String, Object>();
jsonDocument.put("title", title);
jsonDocument.put("conten", content);
jsonDocument.put("postDate", postDate);
jsonDocument.put("tags", tags);
jsonDocument.put("author", author);
return jsonDocument;
}
Node node = nodeBuilder().node();
Client client = node.client();
client.prepareIndex("kodcucom", "article", "1")
.setSource(putJsonDocument("ElasticSearch: Java API",
"ElasticSearch provides the Java API, all operations "
+ "can be executed asynchronously using a client object.",
new Date(),
new String[]{"elasticsearch"},
"Hüseyin Akdoğan")).execute().actionGet();
node.close();
With the above code, we generate an index by the name of kodcucom and a type by the name of article with standard settings and a record (we don’t have to give an ID here) whose ID value of 1 is stored to ElasticSearch.
Getting Document
The Get API allows you to get a typed JSON document, based on the ID, from the index.
GetResponse getResponse = client.prepareGet("kodcucom", "article", "1").execute().actionGet();
Map<String, Object> source = getResponse.getSource();
System.out.println("------------------------------");
System.out.println("Index: " + getResponse.getIndex());
System.out.println("Type: " + getResponse.getType());
System.out.println("Id: " + getResponse.getId());
System.out.println("Version: " + getResponse.getVersion());
System.out.println(source);
System.out.println("------------------------------");
Search
The Search API allows you to execute a search query and get the matched results. The query can be executed across more than one indices and types. The query can be provided by using query Java API or filter Java API. Below you can see an example whose body of search request is built by using SearchSourceBuilder.
public static void searchDocument(Client client, String index, String type,
String field, String value){
SearchResponse response = client.prepareSearch(index)
.setTypes(type)
.setSearchType(SearchType.QUERY_AND_FETCH)
.setQuery(fieldQuery(field, value))
.setFrom(0).setSize(60).setExplain(true)
.execute()
.actionGet();
SearchHit[] results = response.getHits().getHits();
System.out.println("Current results: " + results.length);
for (SearchHit hit : results) {
System.out.println("------------------------------");
Map<String,Object> result = hit.getSource();
System.out.println(result);
}
}
searchDocument(client, "kodcucom", "article", "title", "ElasticSearch");
Updating
Below you can see an example of a field update.
public static void updateDocument(Client client, String index, String type,
String id, String field, String newValue){
Map<String, Object> updateObject = new HashMap<String, Object>();
updateObject.put(field, newValue);
client.prepareUpdate(index, type, id)
.setScript("ctx._source." + field + "=" + field)
.setScriptParams(updateObject).execute().actionGet();
}
updateDocument(client, "kodcucom", "article", "1", "tags", "big-data");
Deleting
The delete API allows you to delete a document whose ID value is specified. You can see below an example of deleting a document whose index, type and value is specified.
public static void deleteDocument(Client client, String index, String type, String id){
DeleteResponse response = client.prepareDelete(index, type, id).execute().actionGet();
System.out.println("Information on the deleted document:");
System.out.println("Index: " + response.getIndex());
System.out.println("Type: " + response.getType());
System.out.println("Id: " + response.getId());
System.out.println("Version: " + response.getVersion());
}
deleteDocument(client, "kodcucom", "article", "1");
See the sample application here.