Jest - ElasticSearch Java Client

 

https://www.cnblogs.com/liululee/p/11075432.html

 

 

1 Introduction

Anyone who has used Elasticsearch all know, the rest based API to build search query may be tedious and error-prone.

In this tutorial, we will study Jest, one for HTTP Java client Elasticsearch of. Elasticsearch provides its own native Java client, however Jest API provides a smoother and easier to use interfaces.

2. Maven relies

The first thing we need to do is to import Jest library to our POM file:

<dependency>
    <groupId>io.searchbox</groupId> <artifactId>jest</artifactId> <version>6.3.1</version> </dependency> 

Jest version is to follow Elasticsearch major version number.
This will ensure compatibility between the client and server.

By including Jest dependency, the appropriate [elasticsearch libraries] ( https://search.maven.org/search?q=g:org.elasticsearch  A: elasticsearch) will be included to pass dependency.

3. Jest Client

In this section, we will examine how to perform common tasks Jest client Elasticsearch in.

To use Jest client, we just use  JestClientFactory  create a  JestClient  object. The cost of creating these objects are very high, and is thread-safe, so we will create a singleton instance that can be shared throughout the application:

public JestClient jestClient() { JestClientFactory factory = new JestClientFactory(); factory.setHttpClientConfig( new HttpClientConfig.Builder("http://localhost:9200") .multiThreaded(true) .defaultMaxTotalConnectionPerRoute(2) .maxTotalConnection(10) .build()); return factory.getObject(); } 

This will create a Jest client, the client connects to Elasticsearch running locally. Although this connection example is simple, but Jest also fully supports proxy, SSL, authentication, even node discovery.

JestClient  class is a generic class, only a few public methods. A primary method we will use is execute, it takes an instance of the Action interface. Jest client provides several different operating builder class to help create Elasticsearch interact with.

An example of the results of all calls are JestResult of Jest. We can call  issucceeded to check if successful method. For a failed operation, we can call the GetErrorMessagemethod to get more detailed information:

JestResult jestResult = jestClient.execute(new Delete.Builder("1").index("employees").build()); if (jestResult.isSucceeded()) { System.out.println("Success!"); } else { System.out.println("Error: " + jestResult.getErrorMessage()); } 

3.1 Management Index

Checks whether the index exists, we use the IndicatesExistsfollowing:

JestResult result = jestClient.execute(new IndicesExists.Builder("employees").build()) 

Create an index, we use the CreateIndexfollowing:

jestClient.execute(new CreateIndex.Builder("employees").build()); 

This will create an index of the default settings have. We can override specific settings when creating an index:

Map<String, Object> settings = new HashMap<>(); settings.put("number_of_shards", 11); settings.put("number_of_replicas", 2); jestClient.execute(new CreateIndex.Builder("employees").settings(settings).build()); 

Use ModifyAliasesthe operation to create or change the alias is also very simple:

jestClient.execute(new ModifyAliases.Builder( new AddAliasMapping.Builder("employees", "e").build()).build()); jestClient.execute(new ModifyAliases.Builder( new RemoveAliasMapping.Builder("employees", "e").build()).build()); 

3.2. Creating documents

Jest client using the index or index operations like creating a new document easier. Elasticsearch documents in just JSON data, there are several ways to transfer data to JSON Jest client index.

For this example, let's use a fictitious employees document:

{
    "name": "Michael Pratt", "title": "Java Developer", "skills": ["java", "spring", "elasticsearch"], "yearsOfService": 2 } 

The first method is to use JSON document represents the Java string. Although we can create a JSON string manually, but we must pay attention to the correct format, braces and escape quote characters. Thus, an easier way is to use a library JSON (e.g., Jackson) to build our structure of JSON, then convert it to a string:

ObjectMapper mapper = new ObjectMapper(); JsonNode employeeJsonNode = mapper.createObjectNode() .put("name", "Michael Pratt") .put("title", "Java Developer") .put("yearsOfService", 2) .set("skills", mapper.createArrayNode() .add("java") .add("spring") .add("elasticsearch")); jestClient.execute(new Index.Builder(employeeJsonNode.toString()).index("employees").build()); 

We can also use the Java  the Map  to represent JSON data and passes it to the index action:

Map<String, Object> employeeHashMap = new LinkedHashMap<>(); employeeHashMap.put("name", "Michael Pratt"); employeeHashMap.put("title", "Java Developer"); employeeHashMap.put("yearsOfService", 2); employeeHashMap.put("skills", Arrays.asList("java", "spring", "elasticsearch")); jestClient.execute(new Index.Builder(employeeHashMap).index("employees").build()); 

The last, Jest client can accept any POJO representation of the document to be indexed. Suppose we have an Employee class:

public class Employee { String name; String title; List<String> skills; int yearsOfService; } 

We can put an instance of this class is passed directly to the Index builder:

Employee employee = new Employee(); employee.setName("Michael Pratt"); employee.setTitle("Java Developer"); employee.setYearsOfService(2); employee.setSkills(Arrays.asList("java", "spring", "elasticsearch")); jestClient.execute(new Index.Builder(employee).index("employees").build()); 

3.3 Read the document

Access documents from Elasticsearch There are two main methods of using Jest client. First of all, if we know the document ID, we can set to get direct access to it:

jestClient.execute(new Get.Builder("employees", "17").build()); 

To access the documents returned, we must call one of the getSourcemethods. We can get JSON results for the original, or to deserialize DTO:

Employee getResult = jestClient.execute(new Get.Builder("employees", "1").build()) .getSourceAsObject(Employee.class); 

Other ways to access the document is to use the search query, in this way is achieved through a search operation in the Jest.

Jest client supports all Elasticsearch query DSL. As with indexing operations, the query is represented as JSON document, and there are several ways to perform the search.

First, we can pass a JSON string representation of the search query. As a reminder, we must ensure that strings are properly escaped and is valid JSON:

String search = "{" +
  " \"query\": {" + " \"bool\": {" + " \"must\": [" + " { \"match\": { \"name\": \"Michael Pratt\" }}" + " ]" + " }" + " }" + "}"; jestClient.execute(new Search.Builder(search).build()); 

As with the above indexing operations, we can use like Jackson JSON library to build the query string. In addition, we can also use Elasticsearch native query API. A disadvantage of this is that our application must rely on the integrity of Elasticsearch library.

GetSource we can use the method to access the document search operation in the match. However, Jest also offers Hit class, which wraps the matching documents and provide information about the results of metadata. Use Hit class, we can access the results of each additional metadata: score, routing and interpreting the results, a few examples:

List<SearchResult.Hit<Employee, Void>> searchResults = jestClient.execute(new Search.Builder(search).build()) .getHits(Employee.class); searchResults.forEach(hit -> { System.out.println(String.format("Document %s has score %s", hit.id, hit.score)); }); 

3.4 Update Document

Jest Update provides a simple operation to update the document:

employee.setYearOfService(3); jestClient.execute(new Update.Builder(employee).index("employees").id("1").build()); 

It accepts the same indexing operations we saw earlier JSON representation, which makes the operation code sharing between the two becomes easy.

3.5. Delete Document

Delete documents from the index using the Delete operation is completed. It requires the index name and Document ID:

jestClient.execute(new Delete.Builder("17") .index("employees") .build()); 

4. Batch Operation

Jest client also supports batch operations. This means we can send multiple operations by simultaneously to save time and bandwidth.

Use bulk operations, we can combine any number of requests into a single call. We can even be combined with different types of requests:

jestClient.execute(new Bulk.Builder() .defaultIndex("employees") .addAction(new Index.Builder(employeeObject1).build()) .addAction(new Index.Builder(employeeObject2).build()) .addAction(new Delete.Builder("17").build()) .build()); 

5. asynchronous operation

Jest client also supports asynchronous operation. This means we can use non-blocking I / O to perform any of these operations.

To an asynchronous call, simply use the client's executeAsyncmethod:

jestClient.executeAsync(
  new Index.Builder(employeeObject1).build(), new JestResultHandler<JestResult>() { @Override public void completed(JestResult result) { // handle result } @Override public void failed(Exception ex) { // handle exception } }); 

Note that in addition (in the present embodiment is the index) operation, an asynchronous stream needed JestResultHandler. When the operation is complete, Jest client will call the object. The interface has two methods - and complete failure - allows the success or failure of each processing operation.

6 Conclusion

In this tutorial, we briefly describe the Jest client, one for Elasticsearch of RESTful Java clients. Although we only introduce a small part of its function, but obviously Jest is a robust Elasticsearch client. It's smooth builder classes and RESTful interfaces make it easy to learn, and it fully supports Elasticsearch interface makes it a powerful alternative to native clients.

As usual, all of the code examples in this tutorial are in our Github page on.

Author: Michael Pratt

Translator: huowolf /

Guess you like

Origin www.cnblogs.com/xiaohanlin/p/12341960.html