ElasticSearch: Java API

ElasticSearch provides Java API, thus it executes all operations asynchronously by using client object. Client object can execute the operations in a bulk accumulatively. 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 previous article with 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:

1<dependency>
2    <groupId>org.elasticsearch</groupId>
3    <artifactId>elasticsearch</artifactId>
4    <version>0.90.3</version>
5</dependency>

 

Client

By 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 and 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.

It should be considered to use 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.

1Node node  = nodeBuilder().node();
2Client client = node.client();

When a node is started, it joins to “elasticsearch” cluster. You can create different clusters by cluster.name setting or clusterName method. In /src/main/resources directory and in elasticsearch.yml file in your project:

1cluster.name: yourclustername

Or in Java code:

1Node node = nodeBuilder().clusterName("yourclustername").node();
2Client 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 document. In here we used map which represents JSON structure very well.

01public static Map<String, Object> putJsonDocument(String title, String content, Date postDate,
02                                                      String[] tags, String author){
03         
04        Map<String, Object> jsonDocument = new HashMap<String, Object>();
05         
06        jsonDocument.put("title", title);
07        jsonDocument.put("conten", content);
08        jsonDocument.put("postDate", postDate);
09        jsonDocument.put("tags", tags);
10        jsonDocument.put("author", author);
11         
12        return jsonDocument;
13    }
01Node node    = nodeBuilder().node();
02Client client   = node.client();
03         
04client.prepareIndex("kodcucom", "article", "1")
05              .setSource(putJsonDocument("ElasticSearch: Java API",
06                                         "ElasticSearch provides the Java API, all operations "
07                                         + "can be executed asynchronously using a client object.",
08                                         new Date(),
09                                         new String[]{"elasticsearch"},
10                                         "Hüseyin Akdoğan")).execute().actionGet();
11                 
12        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 is 1 is stored to ElasticSearch.

 

Getting document

The Get API allows you to get a typed JSON document as ID based from the index.

01GetResponse getResponse = client.prepareGet("kodcucom", "article", "1").execute().actionGet();
02 
03Map<String, Object> source = getResponse.getSource();
04         
05System.out.println("------------------------------");
06System.out.println("Index: " + getResponse.getIndex());
07System.out.println("Type: " + getResponse.getType());
08System.out.println("Id: " + getResponse.getId());
09System.out.println("Version: " + getResponse.getVersion());
10System.out.println(source);
11System.out.println("------------------------------");

 

Search

The Search API allows you to execute a search query and to 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.

01public static void searchDocument(Client client, String index, String type,
02                                      String field, String value){
03         
04        SearchResponse response = client.prepareSearch(index)
05                                        .setTypes(type)
06                                        .setSearchType(SearchType.QUERY_AND_FETCH)
07                                        .setQuery(fieldQuery(field, value))
08                                        .setFrom(0).setSize(60).setExplain(true)
09                                        .execute()
10                                        .actionGet();
11         
12        SearchHit[] results = response.getHits().getHits();
13         
14        System.out.println("Current results: " + results.length);
15        for (SearchHit hit : results) {
16            System.out.println("------------------------------");
17            Map<String,Object> result = hit.getSource();  
18            System.out.println(result);
19        }
20         
21    }
1searchDocument(client, "kodcucom", "article", "title", "ElasticSearch");

 

Updating

Below you can see an example of a field update.

01public static void updateDocument(Client client, String index, String type,
02                                      String id, String field, String newValue){
03         
04        Map<String, Object> updateObject = new HashMap<String, Object>();
05        updateObject.put(field, newValue);
06         
07        client.prepareUpdate(index, type, id)
08              .setScript("ctx._source." + field + "=" + field)
09              .setScriptParams(updateObject).execute().actionGet();
10    }
1updateDocument(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.

1public static void deleteDocument(Client client, String index, String type, String id){
2         
3        DeleteResponse response = client.prepareDelete(index, type, id).execute().actionGet();
4        System.out.println("Information on the deleted document:");
5        System.out.println("Index: " + response.getIndex());
6        System.out.println("Type: " + response.getType());
7        System.out.println("Id: " + response.getId());
8        System.out.println("Version: " + response.getVersion());
9    }
1deleteDocument(client, "kodcucom", "article", "1");

The sample application: ElasticSearch

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值