### Start ILM Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Starts the Index Lifecycle Management (ILM) feature. ```APIDOC ## POST ilm/start ### Description Starts the Index Lifecycle Management (ILM) feature. ### Method POST ### Endpoint ilm/start ``` -------------------------------- ### watcher.start Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Starts the Watcher service in the Elasticsearch cluster. ```APIDOC ## POST watcher/_start ### Description Starts the watcher. ### Method POST ### Endpoint watcher/_start ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json {}``` ### Response #### Success Response (200) - **status** (integer) - The HTTP status code of the response. #### Response Example ```json { "status": 200 } ``` ``` -------------------------------- ### Basic Bulk Ingester Setup Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/usage/indexing-bulk.md Configure and use the BulkIngester to add operations for indexing documents. The ingester automatically handles grouping and sending bulk requests. Ensure to close the ingester to flush any remaining operations. ```java BulkIngester ingester = BulkIngester.of(b -> b .client(esClient) // <1> .maxOperations(100) // <2> .flushInterval(1, TimeUnit.SECONDS) // <3> ); for (File file: logFiles) { FileInputStream input = new FileInputStream(file); BinaryData data = BinaryData.of(IOUtils.toByteArray(input), ContentType.APPLICATION_JSON); ingester.add(op -> op // <4> .index(idx -> idx .index("logs") .document(data) ) ); } ingester.close(); // <5> ``` -------------------------------- ### Get Repository Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Retrieves information about snapshot repositories. ```APIDOC ## GET snapshot/repository/{repository} ### Description Retrieves information about snapshot repositories. ### Method GET ### Endpoint /snapshot/repository/{repository} ### Parameters #### Path Parameters - **repository** (string) - Optional - The name of the repository to retrieve information about. If not specified, information about all repositories is returned. #### Query Parameters - **master_timeout** (time) - Optional - Explicit operation timeout for the master node. - **timeout** (time) - Optional - Explicit operation timeout. ### Request Example (No request body for this operation) ### Response #### Success Response (200) - **repositories** (object) - An object containing repository information, keyed by repository name. - Each repository object contains: - **type** (string) - The type of the repository. - **settings** (object) - The settings of the repository. ### Response Example ```json { "my_repository": { "type": "fs", "settings": { "location": "/mnt/snapshots" } } } ``` ``` -------------------------------- ### Open ML Job Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Opens an ML job, allowing it to start processing data. ```APIDOC ## POST ml/open_job ### Description Opens an ML job, allowing it to start processing data. ### Method POST ### Endpoint /ml/open_job ### Parameters #### Request Body - **job_id** (string) - Required - Identifier for the ML job. ### Response #### Success Response (200) - **acknowledged** (boolean) - Indicates if the request was acknowledged. ``` -------------------------------- ### Indexing Application Objects in Bulk Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/usage/indexing-bulk.md This snippet demonstrates how to index a list of application objects in bulk. It iterates through a list of `Product` objects, creating an `index` operation for each and adding it to a `BulkRequest`. The example also includes basic error handling by checking the `errors` field in the `BulkResponse`. ```APIDOC ## Indexing Application Objects ### Description This operation allows you to index multiple application objects in a single bulk request. It's efficient for ingesting collections of data. ### Method `esClient.bulk(BulkRequest.Builder.build()) ### Endpoint N/A (Client-side operation) ### Parameters N/A (Operations are defined within the `BulkRequest.Builder`) ### Request Body Operations are built programmatically using `BulkRequest.Builder` and `Operation.Builder`. ### Request Example ```java List products = fetchProducts(); BulkRequest.Builder br = new BulkRequest.Builder(); for (Product product : products) { br.operations(op -> op .index(idx -> idx .index("products") .id(product.getSku()) .document(product) ) ); } BulkResponse result = esClient.bulk(br.build()); // Log errors, if any if (result.errors()) { logger.error("Bulk had errors"); for (BulkResponseItem item: result.items()) { if (item.error() != null) { logger.error(item.error().reason()); } } } ``` ### Response #### Success Response (200) Returns a `BulkResponse` object containing the results of each operation. #### Response Example ```json { "took": 50, "errors": false, "items": [ { "index": { "_index": "products", "_id": "sku123", "version": 1, "result": "created", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 0, "_primary_term": 1, "status": 201 } } ] } ``` ``` -------------------------------- ### Build RestClient with Multiple Hosts Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/transport/rest-client/usage/initialization.md Instantiate a RestClient by providing one or more HttpHost objects representing the Elasticsearch nodes. This is the basic setup for connecting to your cluster. ```java RestClient restClient = RestClient.builder( new HttpHost("localhost", 9200, "http"), new HttpHost("localhost", 9201, "http")).build(); ``` -------------------------------- ### Configure BulkIngester with constant backoff policy Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/release-notes/9-0-0.md Enable retry logic for BulkIngester operations that fail with a 429 error. This example configures a constant backoff policy for retries. ```java BulkIngester ingester = BulkIngester.of(b -> b .client(client) ... .listener(listener) .flushInterval(1000, TimeUnit.MILLISECONDS) .backoffPolicy(BackoffPolicy.constantBackoff(50L, 8)) ``` -------------------------------- ### Define a custom ES|QL mapper Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/usage/esql.md Create a custom ES|QL mapper for specific result representations. This example defines a column-oriented JSON mapper that reads results as lines of text. ```java public class CustomStringAdapter extends EsqlAdapterBase { public static final CustomStringAdapter INSTANCE = new CustomStringAdapter(); @Override public String format() { return "json"; } @Override public boolean columnar() { return true; } @Override public String deserialize(ApiClient client, QueryRequest request, BinaryResponse response) throws IOException { return new BufferedReader(new InputStreamReader(response.content())) .lines().collect(Collectors.joining("\n")); } } ``` -------------------------------- ### Customize Response Timeout with Rest5ClientBuilder Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/release-notes/9-0-4.md Use `setRequestConfigCallback` to customize request configurations. This example demonstrates setting the connection and response timeouts. ```java Rest5ClientBuilder builder = Rest5Client .builder(new HttpHost("localhost", 9200)) .setRequestConfigCallback(r -> r .setConnectTimeout(Timeout.of(5000, TimeUnit.MILLISECONDS)) .setResponseTimeout(Timeout.of(30000, TimeUnit.MILLISECONDS)) .build() ); ``` -------------------------------- ### Customizing RequestOptions Per Request Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/transport/rest5-client/usage/requests.md Explains how to customize `RequestOptions` on a per-request basis, for example, by adding an additional header. ```APIDOC ## Customizing RequestOptions Per Request ### Description Allows for per-request customization of `RequestOptions` by creating a new builder from existing options and adding specific configurations. ### Method `COMMON_OPTIONS.toBuilder()` and `builder.addHeader()` ### Endpoint N/A (Applies to any request) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java RequestOptions.Builder options = COMMON_OPTIONS.toBuilder(); options.addHeader("cats", "knock things off of other things"); request.setOptions(options); ``` ### Response N/A ``` -------------------------------- ### Setup TermQuery Deserializer Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/design/0003-json-framework.md Configures the deserializer for TermQuery, including its fields and shortcut properties. This method is protected to allow subclasses to call it. ```java protected static void setupTermQueryDeserializer(ObjectDeserializer op) { QueryBase.setupQueryBaseDeserializer(op); op.add(Builder::value, FieldValue._DESERIALIZER, "value"); op.add(Builder::caseInsensitive, JsonpDeserializer.booleanDeserializer(), "case_insensitive"); op.setKey(Builder::field, JsonpDeserializer.stringDeserializer()); op.shortcutProperty("value", true); } ``` -------------------------------- ### Get a document by ID Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/getting-started.md Retrieve a 'Product' document from the 'products' index using its ID. Logs the product name if found, otherwise logs 'Product not found'. ```java GetResponse response = esClient.get(g -> g .index("products") // <1> .id("bk-1"), Product.class // <2> ); if (response.found()) { Product product = response.source(); logger.info("Product name " + product.getName()); } else { logger.info ("Product not found"); } ``` -------------------------------- ### Nested Search Query with Boolean Logic Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/usage/searching.md Combines multiple search criteria using boolean logic for more complex queries. This example searches for 'bike' products with a maximum price of 200.0. It demonstrates creating individual queries and combining them with a boolean 'must' clause. ```java String searchText = "bike"; double maxPrice = 200.0; // Search by product name Query byName = MatchQuery.of(m -> m // <1> .field("name") .query(searchText) )._toQuery(); // <2> // Search by max price Query byMaxPrice = RangeQuery.of(r -> r .number(n -> n .field("price") .gte(maxPrice)) // <3> )._toQuery(); // Combine name and price queries to search the product index SearchResponse response = esClient.search(s -> s .index("products") .query(q -> q .bool(b -> b // <4> .must(byName) // <5> .must(byMaxPrice) ) ), Product.class ); List> hits = response.hits().hits(); for (Hit hit: hits) { Product product = hit.source(); logger.info("Found product " + product.getSku() + ", score " + hit.score()); } ``` -------------------------------- ### Applying RequestOptions Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/transport/rest5-client/usage/requests.md Demonstrates how to apply a pre-configured `RequestOptions` object to a request. ```APIDOC ## Applying RequestOptions ### Description Applies a `RequestOptions` object to a specific request, overriding or adding to the default options. ### Method `request.setOptions(RequestOptions options)` ### Endpoint N/A (Applies to any request) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java request.setOptions(COMMON_OPTIONS); ``` ### Response N/A ``` -------------------------------- ### Get API Key Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Retrieves information about an API key. This endpoint can be used to get details of a specific API key or all API keys. ```APIDOC ## GET security/api_key ### Description Retrieves information about an API key. ### Method GET ### Endpoint /security/api_key ### Parameters #### Query Parameters - **id** (string) - Optional - The ID of the API key to retrieve. - **name** (string) - Optional - The name of the API key to retrieve. ### Response #### Success Response (200) - **id** (string) - The ID of the API key. - **name** (string) - The name of the API key. - **api_key** (string) - The actual API key. - **creation** (long) - The creation time of the API key in milliseconds since the epoch. - **exprire_in_days** (integer) - The number of days until the API key expires. - **role_descriptors** (object) - A map of role descriptors associated with the API key. ``` -------------------------------- ### Index Single Document using Fluent DSL with `IndexRequest.of()` Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/usage/indexing.md Shows how to create an `IndexRequest` object using the static `of()` method and the fluent DSL syntax, then execute it. ```APIDOC ## Index Single Document using Fluent DSL with `IndexRequest.of()` ### Description Creates an `IndexRequest` object using the `IndexRequest.of()` static method with fluent DSL syntax and then executes the request. ### Method ```java IndexRequest request = IndexRequest.of(i -> i .index("products") .id(product.getSku()) .document(product) ); IndexResponse response = esClient.index(request); ``` ### Parameters - `index`: The name of the index. - `id`: The unique identifier for the document. - `document`: The application object to be indexed. ``` -------------------------------- ### RequestOptions Singleton Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/transport/rest5-client/usage/requests.md Shows how to create a singleton `RequestOptions` instance to share common request configurations like headers and response consumer factories across multiple requests. ```APIDOC ## RequestOptions Singleton ### Description Creates a reusable `RequestOptions` object that can be shared across multiple requests to maintain consistent configurations, such as authorization headers. ### Method `RequestOptions.DEFAULT.toBuilder()` and `builder.build()` ### Endpoint N/A (Configuration object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java private static final RequestOptions COMMON_OPTIONS; static { RequestOptions.Builder builder = RequestOptions.DEFAULT .toBuilder() .addHeader("Authorization", "Bearer " + TOKEN) // Add authorization headers .setHttpAsyncResponseConsumerFactory( HttpAsyncResponseConsumerFactory.DEFAULT ); COMMON_OPTIONS = builder.build(); } ``` ### Response N/A ``` -------------------------------- ### Get Index Settings Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Retrieves the settings for an index. ```APIDOC ## GET /{index}/_settings ### Description Retrieves the settings for an index. ### Method GET ### Endpoint /{index}/_settings ### Parameters #### Path Parameters - **index** (string) - Required - The name of the index. ``` -------------------------------- ### Initialize Rest5Client with URLs Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/transport/rest5-client/usage/initialization.md Create a Rest5Client instance by providing one or more URLs that the client will communicate with. The Rest5Client is thread-safe and should have the same lifecycle as the application. ```java Rest5Client restClient = Rest5Client.builder( URI.create("http://localhost:9200"), URI.create("http://localhost:9201") ).build(); ``` -------------------------------- ### Get Index Template Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Retrieves an index template. ```APIDOC ## GET indices/_index_template/{name} ### Description Retrieves an index template. ### Method GET ### Endpoint indices/_index_template/{name} ### Parameters #### Path Parameters - **name** (string) - Required - The name of the index template to retrieve. ``` -------------------------------- ### Basic Initialization Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/transport/rest5-client/usage/initialization.md Initialize the Rest5Client with one or more URLs or HttpHost objects. The client is thread-safe and should have the same lifecycle as the application. ```APIDOC ## Basic Initialization ### Description Initialize the Rest5Client with one or more URLs or HttpHost objects. The client is thread-safe and should have the same lifecycle as the application. ### Method ```java Rest5Client restClient = Rest5Client.builder( URI.create("http://localhost:9200"), URI.create("http://localhost:9201") ).build(); ``` ### Closing the Client It is important to close the client when no longer needed to release all resources. ### Method ```java restClient.close(); ``` ``` -------------------------------- ### Get Snapshot Status Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Retrieves the status of snapshot operations. ```APIDOC ## GET snapshot/status ### Description Retrieves the status of snapshot operations. ### Method GET ### Endpoint /snapshot/status ### Parameters #### Query Parameters - **repository** (string) - Optional - The name of the repository to filter snapshots by. - **snapshot** (string) - Optional - The name of the snapshot to get the status for. Can be a comma-separated list or a wildcard. - **master_timeout** (time) - Optional - Explicit operation timeout for the master node. - **timeout** (time) - Optional - Explicit operation timeout. ### Request Example (No request body for this operation) ### Response #### Success Response (200) - **snapshots** (array) - A list of snapshot status objects. - Each snapshot status object contains: - **snapshot** (string) - The name of the snapshot. - **state** (string) - The current state of the snapshot operation (e.g., IN_PROGRESS, SUCCESS, FAILED). - **start_time_in_millis** (long) - The start time of the snapshot operation in milliseconds. - **end_time_in_millis** (long) - The end time of the snapshot operation in milliseconds. - **duration_in_millis** (long) - The duration of the snapshot operation in milliseconds. - **repository** (string) - The name of the repository. - **indices** (object) - Information about the indices being snapshotted. - **shards** (object) - Information about the shards involved in the snapshot operation. - **partial** (boolean) - Whether the snapshot contains partial indices. ### Response Example ```json { "snapshots": [ { "snapshot": "my_snapshot_in_progress", "state": "IN_PROGRESS", "start_time_in_millis": 1678886400000, "end_time_in_millis": 0, "duration_in_millis": 60000, "repository": "my_repository", "indices": { "index1": { "shards": 1, "successful_shards": 0, "failed_shards": 0 } }, "shards": { "total": 1, "successful": 0, "failed": 0 }, "partial": false } ] } ``` ``` -------------------------------- ### Get Snapshot Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Retrieves information about one or more snapshots from a repository. ```APIDOC ## GET snapshot/{snapshot} ### Description Retrieves information about one or more snapshots from a repository. ### Method GET ### Endpoint /snapshot/{snapshot} ### Parameters #### Path Parameters - **snapshot** (string) - Required - The name or comma-separated list of snapshot names to retrieve. Use _all to get all snapshots. #### Query Parameters - **repository** (string) - Required - The name of the repository from which to retrieve snapshots. - **master_timeout** (time) - Optional - Explicit operation timeout for the master node. - **timeout** (time) - Optional - Explicit operation timeout. - **ignore_unavailable** (boolean) - Optional - Whether to ignore unavailable snapshots. Defaults to false. ### Request Example (No request body for this operation) ### Response #### Success Response (200) - **snapshots** (array) - A list of snapshot objects. - Each snapshot object contains: - **snapshot** (string) - The name of the snapshot. - **state** (string) - The state of the snapshot. - **start_time_in_millis** (long) - The start time of the snapshot operation. - **end_time_in_millis** (long) - The end time of the snapshot operation. - **duration_in_millis** (long) - The duration of the snapshot operation. - **indices** (object) - Information about the indices included in the snapshot. - **shards** (object) - Information about the shards included in the snapshot. - **repository** (string) - The name of the repository. - **version** (string) - The version of Elasticsearch when the snapshot was created. - **index_count** (integer) - The number of indices in the snapshot. - **shard_count** (integer) - The number of shards in the snapshot. - **size_in_bytes** (long) - The total size of the snapshot in bytes. - **global_state** (boolean) - Whether the global state was included. - **partial** (boolean) - Whether the snapshot contains partial indices. ### Response Example ```json { "snapshots": [ { "snapshot": "my_snapshot_1", "state": "SUCCESS", "start_time_in_millis": 1678886400000, "end_time_in_millis": 1678886460000, "duration_in_millis": 60000, "indices": { "index1": { "shards": 1, "successful_shards": 1, "failed_shards": 0 } }, "shards": { "total": 1, "successful": 1, "failed": 0 }, "repository": "my_repository", "version": "8.7.0", "index_count": 1, "shard_count": 1, "size_in_bytes": 1024000, "global_state": true, "partial": false } ] } ``` ``` -------------------------------- ### Create Repository Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Creates a new snapshot repository. ```APIDOC ## PUT snapshot/repository/{repository} ### Description Creates a new snapshot repository. ### Method PUT ### Endpoint /snapshot/repository/{repository} ### Parameters #### Path Parameters - **repository** (string) - Required - The name of the repository to create. #### Query Parameters - **master_timeout** (time) - Optional - Explicit operation timeout for the master node. - **timeout** (time) - Optional - Explicit operation timeout. #### Request Body - **type** (string) - Required - The type of the repository (e.g., "fs", "s3", "azure", "gcs"). - **settings** (object) - Required - Settings specific to the repository type. - For "fs" type: - **location** (string) - Required - Path to the repository location on the filesystem. - For "s3" type: - **bucket** (string) - Required - The S3 bucket name. - **base_path** (string) - Optional - The base path within the S3 bucket. - **region** (string) - Optional - The AWS region of the S3 bucket. - For "azure" type: - **container** (string) - Required - The Azure container name. - **base_path** (string) - Optional - The base path within the Azure container. - For "gcs" type: - **bucket** (string) - Required - The GCS bucket name. - **base_path** (string) - Optional - The base path within the GCS bucket. ### Request Example ```json { "type": "fs", "settings": { "location": "/mnt/snapshots" } } ``` ### Response #### Success Response (200) - **acknowledged** (boolean) - True if the repository creation was acknowledged. ### Response Example ```json { "acknowledged": true } ``` ``` -------------------------------- ### Get ML Jobs Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Retrieves a list of ML jobs. ```APIDOC ## GET ml/get_jobs ### Description Retrieves a list of ML jobs. ### Method GET ### Endpoint /ml/get_jobs ### Parameters #### Query Parameters - **job_id** (string) - Optional - Identifier for the ML job. - **datafeed_id** (string) - Optional - Identifier for the datafeed. ### Response #### Success Response (200) - **jobs** (array) - A list of ML jobs. ``` -------------------------------- ### Perform a Search Request with Product Class Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/setup/connecting.md Illustrates a search query for items in a 'products' index matching 'bicycle' by name. Results are returned as instances of the Product class. This uses a fluent functional builder pattern for concise query definition. ```java SearchResponse search = esClient.search(s -> s .index("products") .query(q -> q .term(t -> t .field("name") .value(v -> v.stringValue("bicycle")) )), Product.class); for (Hit hit: search.hits().hits()) { processProduct(hit.source()); } ``` -------------------------------- ### Get Lifecycle Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Retrieves the details of an index lifecycle policy. ```APIDOC ## GET ilm/get_lifecycle/{policy} ### Description Retrieves the details of a specific index lifecycle policy. ### Method GET ### Endpoint ilm/get_lifecycle/{policy} ### Parameters #### Path Parameters - **policy** (string) - Required - The name of the lifecycle policy to retrieve. ``` -------------------------------- ### Create Index Request with Builder Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/api-conventions/building-objects.md Demonstrates creating an index request using the traditional builder pattern. Builders should not be reused after `build()` is called. ```java ElasticsearchClient esClient = createClient(); CreateIndexResponse createResponse = esClient.indices().create( new CreateIndexRequest.Builder() .index("my-index") .aliases("foo", new Alias.Builder().isWriteIndex(true).build() ) .build() ); ``` -------------------------------- ### Use Blocking and Async Clients Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/api-conventions/blocking-async.md Demonstrates how to instantiate and use both blocking and asynchronous Elasticsearch clients. Ensure proper error handling for asynchronous operations. ```java ElasticsearchClient esClient = new ElasticsearchClient(transport); if (esClient.exists(b -> b.index("products").id("foo")).value()) { logger.info("product exists"); } // Asynchronous non-blocking client ElasticsearchAsyncClient asyncClient = new ElasticsearchAsyncClient(transport); asyncClient .exists(b -> b.index("products").id("foo")) .whenComplete((response, exception) -> { if (exception != null) { logger.error("Failed to index", exception); } else { logger.info("Product exists"); } }); ``` -------------------------------- ### Get Trained ML Models Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Retrieves trained ML models. ```APIDOC ## GET ml/get_trained_models ### Description Retrieves trained ML models. ### Method GET ### Endpoint /ml/get_trained_models ### Parameters #### Query Parameters - **model_id** (string) - Optional - Identifier for the trained model. ### Response #### Success Response (200) - **models** (array) - A list of trained ML models. ``` -------------------------------- ### Get ML Model Snapshots Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Retrieves ML model snapshots. ```APIDOC ## GET ml/get_model_snapshots ### Description Retrieves ML model snapshots. ### Method GET ### Endpoint /ml/get_model_snapshots ### Parameters #### Query Parameters - **model_id** (string) - Optional - Identifier for the model. - **snapshot_id** (string) - Optional - Identifier for the snapshot. ### Response #### Success Response (200) - **snapshots** (array) - A list of ML model snapshots. ``` -------------------------------- ### Run Elasticsearch and Kibana Locally Source: https://github.com/elastic/elasticsearch-java/blob/main/README.md Use this command to quickly set up and run Elasticsearch and Kibana on your local machine for testing and development purposes. ```bash curl -fsSL https://elastic.co/start-local | sh ``` -------------------------------- ### Create Index Request with Builder Lambdas Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/api-conventions/building-objects.md Shows how to create an index request using builder lambda expressions for more concise code. Types are inferred, avoiding explicit imports. ```java ElasticsearchClient esClient = createClient(); CreateIndexResponse createResponse = esClient.indices() .create(createIndexBuilder -> createIndexBuilder .index("my-index") .aliases("foo", aliasBuilder -> aliasBuilder .isWriteIndex(true) ) ); ``` -------------------------------- ### Get ML Job Stats Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Retrieves statistics for ML jobs. ```APIDOC ## GET ml/get_job_stats ### Description Retrieves statistics for ML jobs. ### Method GET ### Endpoint /ml/get_job_stats ### Parameters #### Query Parameters - **job_id** (string) - Optional - Identifier for the ML job. ### Response #### Success Response (200) - **job_stats** (object) - Statistics for the ML job. ``` -------------------------------- ### Create ElasticsearchClient with simplified builder Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/release-notes/9-0-0.md Instantiate ElasticsearchClient using a concise builder pattern. Requires server URL and API key. ```java ElasticsearchClient esClient = ElasticsearchClient.of(b -> b .host(serverUrl) .apiKey(apiKey) ); ``` -------------------------------- ### Get ML Anomaly Records Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Retrieves anomaly records from ML jobs. ```APIDOC ## GET ml/get_records ### Description Retrieves anomaly records from ML jobs. ### Method GET ### Endpoint /ml/get_records ### Parameters #### Query Parameters - **job_id** (string) - Required - Identifier for the ML job. - **start** (string) - Optional - Start time for the records. - **end** (string) - Optional - End time for the records. ### Response #### Success Response (200) - **records** (array) - A list of anomaly records. ``` -------------------------------- ### Basic Initialization Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/transport/rest-client/usage/initialization.md Initialize the RestClient with one or more HttpHost instances. The RestClient is thread-safe and should have the same lifecycle as the application. ```APIDOC ## Basic Initialization ### Description Initialize the RestClient with one or more HttpHost instances. The RestClient is thread-safe and should have the same lifecycle as the application. ### Method ```java RestClient restClient = RestClient.builder( new HttpHost("localhost", 9200, "http"), new HttpHost("localhost", 9201, "http")).build(); ``` ### Closing the Client It is important to close the client when no longer needed to release resources. ### Method ```java restClient.close(); ``` ``` -------------------------------- ### Get ML Memory Stats Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Retrieves memory statistics for ML processes. ```APIDOC ## GET ml/get_memory_stats ### Description Retrieves memory statistics for ML processes. ### Method GET ### Endpoint /ml/get_memory_stats ### Response #### Success Response (200) - **memory_stats** (object) - Memory statistics for ML. ``` -------------------------------- ### Index Single Document using Classic Builders Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/usage/indexing.md Illustrates how to use the classic builder pattern to construct an `IndexRequest` before executing it. ```APIDOC ## Index Single Document using Classic Builders ### Description Constructs an `IndexRequest` using the classic builder pattern and then executes the request. ### Method ```java IndexRequest.Builder indexReqBuilder = new IndexRequest.Builder<>(); indexReqBuilder.index("product"); indexReqBuilder.id(product.getSku()); indexReqBuilder.document(product); IndexResponse response = esClient.index(indexReqBuilder.build()); ``` ### Parameters - `index`: The name of the index. - `id`: The unique identifier for the document. - `document`: The application object to be indexed. ``` -------------------------------- ### Get Trained ML Models Stats Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Retrieves statistics for trained ML models. ```APIDOC ## GET ml/get_trained_models_stats ### Description Retrieves statistics for trained ML models. ### Method GET ### Endpoint /ml/get_trained_models_stats ### Parameters #### Query Parameters - **model_id** (string) - Optional - Identifier for the trained model. ### Response #### Success Response (200) - **model_stats** (array) - Statistics for trained ML models. ``` -------------------------------- ### Initialize RestClient and Sniffer Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/transport/rest-client/sniffer/usage.md Create a RestClient instance and associate a Sniffer with it. The Sniffer will periodically update the node list. ```java RestClient restClient = RestClient.builder( new HttpHost("localhost", 9200, "http")) .build(); Sniffer sniffer = Sniffer.builder(restClient).build(); ``` -------------------------------- ### Get ML Overall Buckets Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Retrieves overall buckets for ML anomaly detection. ```APIDOC ## GET ml/get_overall_buckets ### Description Retrieves overall buckets for ML anomaly detection. ### Method GET ### Endpoint /ml/get_overall_buckets ### Parameters #### Query Parameters - **job_id** (string) - Required - Identifier for the ML job. - **start** (string) - Optional - Start time for the buckets. - **end** (string) - Optional - End time for the buckets. ### Response #### Success Response (200) - **buckets** (array) - A list of overall buckets. ``` -------------------------------- ### Create common RequestOptions singleton in Java Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/transport/rest5-client/usage/requests.md Create a singleton `RequestOptions` instance to share common settings like headers and response consumer factories across multiple requests. ```java private static final RequestOptions COMMON_OPTIONS; static { RequestOptions.Builder builder = RequestOptions.DEFAULT .toBuilder() .addHeader("Authorization", "Bearer " + TOKEN) // <1> .setHttpAsyncResponseConsumerFactory( HttpAsyncResponseConsumerFactory.DEFAULT ); // <2> COMMON_OPTIONS = builder.build(); } ``` -------------------------------- ### Enroll Node Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Enrolls a node into an Elasticsearch cluster. This is part of the security setup for nodes. ```APIDOC ## POST security/enroll/node ### Description Enrolls a node into an Elasticsearch cluster. ### Method POST ### Endpoint /security/enroll/node ### Parameters #### Request Body - **name** (string) - Required - The name of the node. - **policy_name** (string) - Optional - The name of the enrollment policy to use. ### Response #### Success Response (200) - **token** (string) - The enrollment token for the node. ``` -------------------------------- ### Configuring Request Options Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/transport/rest-client/usage/requests.md Explains how to use `RequestOptions` to configure common settings like headers and response consumer factories, which can be shared across multiple requests. ```APIDOC ## Configuring Request Options ### Description Allows configuration of common request settings like headers and response consumer factories that can be shared across multiple requests. ### Method ```java request.setOptions(requestOptions) ``` ### Parameters #### Request Options - **requestOptions** (RequestOptions) - Required - An instance of `RequestOptions` containing the desired configurations. ### Request Example (Common Options) ```java private static final RequestOptions COMMON_OPTIONS; static { RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder(); builder.addHeader("Authorization", "Bearer " + TOKEN); builder.setHttpAsyncResponseConsumerFactory( new HttpAsyncResponseConsumerFactory .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024)); COMMON_OPTIONS = builder.build(); } // Usage: request.setOptions(COMMON_OPTIONS); ``` ### Request Example (Per-Request Customization) ```java RequestOptions.Builder options = COMMON_OPTIONS.toBuilder(); options.addHeader("cats", "knock things off of other things"); request.setOptions(options); ``` ``` -------------------------------- ### Get Privileges Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Retrieves a list of custom privileges defined in Elasticsearch. These are privileges created by users. ```APIDOC ## GET security/privilege/{name} ### Description Retrieves a list of custom privileges defined in Elasticsearch. ### Method GET ### Endpoint /security/privilege/{name} ### Parameters #### Path Parameters - **name** (string) - Required - The name of the privilege to retrieve. ### Response #### Success Response (200) - **privilege** (object) - **name** (string) - The name of the privilege. - **application** (string) - The application the privilege belongs to. - **privileges** (array) - A list of actions associated with the privilege. ``` -------------------------------- ### Get ILM Status Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Retrieves the current status of the Index Lifecycle Management (ILM) feature. ```APIDOC ## GET ilm/get_status ### Description Retrieves the current status of the Index Lifecycle Management (ILM) feature. ### Method GET ### Endpoint ilm/get_status ``` -------------------------------- ### Configure Basic Authentication with RestClient Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/transport/rest-client/config/basic_authentication.md Provide an `HttpClientConfigCallback` to the `RestClient` builder to set up default credentials for basic authentication. ```java final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user", "test-user-password")); RestClientBuilder builder = RestClient.builder( new HttpHost("localhost", 9200)) .setHttpClientConfigCallback(new HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient( HttpAsyncClientBuilder httpClientBuilder) { return httpClientBuilder .setDefaultCredentialsProvider(credentialsProvider); } }); ``` -------------------------------- ### Enroll Kibana Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Enrolls a Kibana instance into an Elasticsearch cluster. This is part of the security setup for Kibana. ```APIDOC ## POST security/enroll/kibana ### Description Enrolls a Kibana instance into an Elasticsearch cluster. ### Method POST ### Endpoint /security/enroll/kibana ### Parameters #### Request Body - **name** (string) - Required - The name of the Kibana instance. - **policy_name** (string) - Optional - The name of the enrollment policy to use. ### Response #### Success Response (200) - **token** (string) - The enrollment token for the Kibana instance. ``` -------------------------------- ### Initialize Sniffer Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/transport/rest5-client/sniffer/index.md Create a Rest5Client and associate a Sniffer with it. The Sniffer will periodically fetch node information. ```java Rest5Client restClient = Rest5Client .builder(HttpHost.create("http://localhost:9200")) .build(); Sniffer sniffer = Sniffer.builder(restClient).build(); ``` -------------------------------- ### Convert PEM files to PKCS#12 keystore Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/transport/rest-client/config/encrypted_communication.md Use this command-line utility when your client certificate and private key are in PEM encoded files and you need to create a PKCS#12 keystore for use with the Java REST client. ```bash openssl pkcs12 -export -in client.crt -inkey private_key.pem \ -name "client" -out client.p12 ``` -------------------------------- ### Get Role Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Retrieves information about a specific role or all roles in Elasticsearch. Roles define sets of privileges. ```APIDOC ## GET security/role/{name} ### Description Retrieves information about a specific role in Elasticsearch. ### Method GET ### Endpoint /security/role/{name} ### Parameters #### Path Parameters - **name** (string) - Required - The name of the role to retrieve. ### Response #### Success Response (200) - **role** (object) - **name** (string) - The name of the role. - **privileges** (array) - A list of privileges assigned to the role. - **role_descriptors** (object) - A map of role descriptors associated with the role. ``` -------------------------------- ### Configure common request options Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/transport/rest-client/usage/requests.md Create a singleton `RequestOptions` instance to share common settings like headers and response consumer factories across multiple requests. ```java private static final RequestOptions COMMON_OPTIONS; static { RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder(); builder.addHeader("Authorization", "Bearer " + TOKEN); <1> builder.setHttpAsyncResponseConsumerFactory( new HttpAsyncResponseConsumerFactory .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024)); COMMON_OPTIONS = builder.build(); } ``` -------------------------------- ### Get Builtin Privileges Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Retrieves a list of all built-in privileges available in Elasticsearch. These are predefined privileges that cannot be modified. ```APIDOC ## GET security/privilege ### Description Retrieves a list of all built-in privileges available in Elasticsearch. ### Method GET ### Endpoint /security/privilege ### Response #### Success Response (200) - **privileges** (object) - A map where keys are application names and values are lists of privileges for that application. ``` -------------------------------- ### Get ML Model Snapshot Upgrade Stats Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Retrieves statistics for upgrading ML model snapshots. ```APIDOC ## GET ml/get_model_snapshot_upgrade_stats ### Description Retrieves statistics for upgrading ML model snapshots. ### Method GET ### Endpoint /ml/get_model_snapshot_upgrade_stats ### Parameters #### Query Parameters - **model_id** (string) - Optional - Identifier for the model. ### Response #### Success Response (200) - **upgrade_stats** (object) - Statistics for model snapshot upgrades. ``` -------------------------------- ### Create an index Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/getting-started.md Create a new index named 'products' using the Elasticsearch Java client. ```java esClient.indices().create(c -> c .index("products") ); ``` -------------------------------- ### Get Role Mapping Source: https://github.com/elastic/elasticsearch-java/blob/main/java-client/src/main/java/co/elastic/clients/elasticsearch/doc-files/api-spec.html Retrieves information about a role mapping in Elasticsearch. Role mappings link users and groups to roles. ```APIDOC ## GET security/role_mapping/{name} ### Description Retrieves information about a role mapping in Elasticsearch. ### Method GET ### Endpoint /security/role_mapping/{name} ### Parameters #### Path Parameters - **name** (string) - Required - The name of the role mapping to retrieve. ### Response #### Success Response (200) - **role_mapping** (object) - **name** (string) - The name of the role mapping. - **roles** (array) - A list of roles associated with the mapping. - **users** (array) - A list of users included in the mapping. - **groups** (array) - A list of groups included in the mapping. ``` -------------------------------- ### Create TermQuery Deserializer Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/design/0003-json-framework.md Defines the static deserializer for TermQuery using ObjectBuilderDeserializer. It lazily initializes the builder and setup method. ```java public static final JsonpDeserializer _DESERIALIZER = ObjectBuilderDeserializer.lazy( Builder::new, TermQuery::setupTermQueryDeserializer ); ``` -------------------------------- ### Connect to Elasticsearch using API Key Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/getting-started.md Instantiate the Elasticsearch client using your server URL and API key. Ensure to close the client when done to release resources. ```java // URL and API key String serverUrl = "https://localhost:9200"; String apiKey = "VnVhQ2ZHY0JDZGJrU..."; ElasticsearchClient esClient = ElasticsearchClient.of(b -> b .host(serverUrl) .apiKey(apiKey) ); // Use the client... // Close the client, also closing the underlying transport object and network connections. esClient.close(); ``` -------------------------------- ### Index Single Document using Fluent DSL Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/usage/indexing.md Demonstrates how to index a domain object by providing it directly to the index method. The object is automatically mapped to JSON. ```APIDOC ## Index Single Document using Fluent DSL ### Description Indexes a domain object into Elasticsearch using the fluent DSL. The object is automatically mapped to JSON. ### Method ```java IndexResponse response = esClient.index(i -> i .index("products") .id(product.getSku()) .document(product) ); ``` ### Parameters - `index`: The name of the index to which the document will be added. - `id`: The unique identifier for the document. - `document`: The application object to be indexed, which will be mapped to JSON. ``` -------------------------------- ### Consume ES|QL results as Objects Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/usage/esql.md Map ES|QL query results directly to application domain objects. This requires defining a Book class and using the ObjectsEsqlAdapter. ```java List queryRes = (List) client.esql().query(ObjectsEsqlAdapter.of(Book.class), queryAuthor); ``` -------------------------------- ### Setting a Node Selector Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/transport/rest5-client/usage/initialization.md Specify a node selector to filter which nodes the client sends requests to, for example, to skip dedicated master nodes. ```APIDOC ## Setting a Node Selector ### Description Specify a node selector to filter which nodes the client sends requests to, for example, to skip dedicated master nodes. ### Method ```java Rest5ClientBuilder builder = Rest5Client .builder(new HttpHost("http", "localhost", 9200)); builder.setNodeSelector(NodeSelector.SKIP_DEDICATED_MASTERS); // <1> ``` 1. Set the node selector to be used to filter the nodes the client will send requests to among the ones that are set to the client itself. This is useful for instance to prevent sending requests to dedicated master nodes when sniffing is enabled. By default the client sends requests to every configured node. ``` -------------------------------- ### Customizing HTTP Client Configuration Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/transport/rest-client/usage/initialization.md Use a callback to modify the HTTP client configuration, such as setting up a proxy. ```APIDOC ## Customizing HTTP Client Configuration ### Description Set a callback that allows modification of the HTTP client configuration, such as enabling encrypted communication over SSL or configuring a proxy using `org.apache.http.impl.nio.client.HttpAsyncClientBuilder`. ### Method ```java RestClientBuilder builder = RestClient.builder( new HttpHost("localhost", 9200, "http")); builder.setHttpClientConfigCallback(new HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient( HttpAsyncClientBuilder httpClientBuilder) { return httpClientBuilder.setProxy( new HttpHost("proxy", 9000, "http")); } }); ``` ``` -------------------------------- ### Create Index Request with Short Builder Lambdas Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/api-conventions/building-objects.md Illustrates using shortened variable names in builder lambda expressions for improved readability, especially in chained calls. ```java ElasticsearchClient esClient = createClient(); CreateIndexResponse createResponse = esClient.indices() .create(c -> c .index("my-index") .aliases("foo", a -> a .isWriteIndex(true) ) ); ``` -------------------------------- ### Build search request with MatchAllQuery directly Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/release-notes/9-0-0.md Construct search requests by directly providing specific query variants like MatchAllQuery, instead of using the parent class and then selecting the variant. ```java esClient.search(s -> s .index("my-index") .query(q -> q .matchAll(m -> m) ) ); ``` ```java esClient.search(s -> s .index("my-index") .query(MatchAllQuery.of(m -> m)) ); ``` -------------------------------- ### Create Index using Indices Namespace Client Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/reference/api-conventions/package-structure.md Use the indices namespace client to create an index. The lambda syntax is used for building API objects. ```java // Create the "products" index ElasticsearchClient client = ... client.indices().create(c -> c.index("products")); ``` -------------------------------- ### Filtered Endpoint implementation Source: https://github.com/elastic/elasticsearch-java/blob/main/docs/design/0002-namespace-clients-and-endpoints.md An example of creating a custom endpoint for filtered responses. This new endpoint delegates to the original but specifies a different response parser and adds a 'filter_path' query parameter. ```java public static final Endpoint FILTERED = new Endpoint.Simple<>( FooRequest.ENDPOINT::method, FooRequest.ENDPOINT::requestUrl, FooRequest.ENDPOINT::headers, r -> Map.of("filter_path", "-*.big_field"), // should be a static value for realz ReducedFooResponse.PARSER ); ```