Connecting

edit

The Java API Client is structured around three main components:

  • API client classes. These provide strongly typed data structures and methods for Elasticsearch APIs. Since the Elasticsearch API is large, it is structured in feature groups (also called “namespaces”), each having its own client class. Elasticsearch core features are implemented in the ElasticsearchClient class.
  • A JSON object mapper. This maps your application classes to JSON and seamlessly integrates them with the API client.
  • A transport layer implementation. This is where all HTTP request handling takes place.

This code snippet creates and wires together these three components:

// Create the low-level client
RestClient restClient = RestClient.builder(
    new HttpHost("localhost", 9200)).build();

// Create the transport with a Jackson mapper
ElasticsearchTransport transport = new RestClientTransport(
    restClient, new JacksonJsonpMapper());

// And create the API client
ElasticsearchClient client = new ElasticsearchClient(transport);

Authentication is managed by the Java Low Level REST Client. For further details on configuring authentication, refer to its documentation.

Your first request

edit

The code snippet below searches all items from a “product” index whose name matches “bicycle” and return them as instances of a Product application class.

It illustrates the use of fluent functional builders to write search queries as concise DSL-like code. This pattern is explained in more detail in API conventions.

SearchResponse<Product> search = client.search(s -> s
    .index("products")
    .query(q -> q
        .term(t -> t
            .field("name")
            .value(v -> v.stringValue("bicycle"))
        )),
    Product.class);

for (Hit<Product> hit: search.hits().hits()) {
    processProduct(hit.source());
}

The source code for the examples above can be found in the Java API Client tests.