CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-opensearch--opensearch

OpenSearch is a distributed, RESTful search and analytics engine built as a community-driven fork of Elasticsearch.

Pending
Overview
Eval results
Files

action-framework.mddocs/

Action Framework

Core action system for document operations, bulk processing, and the underlying request/response infrastructure. The action framework provides the foundation for all OpenSearch operations with typed requests, responses, and async execution patterns.

Capabilities

Base Action Framework

Core interfaces and classes that form the foundation of the OpenSearch action system.

/**
 * Base class defining action types with typed request and response handling
 */
abstract class ActionType<Response extends ActionResponse> implements Streamable {
    /**
     * Get action name identifier
     */
    String name();
    
    /**
     * Create new response instance for deserialization
     */
    Response newResponse();
    
    /**
     * Get response class
     */
    Class<Response> getResponseClass();
}

/**
 * Base class for all action requests with validation and streaming support
 */
abstract class ActionRequest implements Streamable, Validatable {
    /**
     * Validate request parameters and return validation errors
     * @return Validation exception with error details, or null if valid
     */
    ActionRequestValidationException validate();
    
    /**
     * Create request builder for this request type
     */
    ActionRequestBuilder<?, ?, ?> createBuilder();
    
    /**
     * Get description of the request for logging and monitoring
     */
    String getDescription();
}

/**
 * Base class for all action responses with streaming support
 */
abstract class ActionResponse implements Streamable {
    /**
     * Read response from input stream
     * @param in Input stream to read from
     */
    void readFrom(StreamInput in) throws IOException;
    
    /**
     * Write response to output stream
     * @param out Output stream to write to
     */
    void writeTo(StreamOutput out) throws IOException;
}

/**
 * Builder pattern base class for constructing action requests
 */
abstract class ActionRequestBuilder<Request extends ActionRequest, Response extends ActionResponse, 
    RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> {
    
    /**
     * Get the action type
     */
    ActionType<Response> action();
    
    /**
     * Get the request being built
     */
    Request request();
    
    /**
     * Execute request asynchronously
     * @param listener Callback for response handling
     */
    void execute(ActionListener<Response> listener);
    
    /**
     * Execute request synchronously and return response
     */
    Response get();
    
    /**
     * Execute request with timeout
     * @param timeout Maximum time to wait for response
     */
    Response get(TimeValue timeout);
}

Document Write Operations

Core document manipulation operations including indexing, updating, and deletion.

/**
 * Base class for all document write operations (index, update, delete)
 */
abstract class DocWriteRequest<T extends DocWriteRequest<T>> extends ActionRequest {
    /**
     * Get target index name
     */
    String index();
    
    /**
     * Get document ID
     */
    String id();
    
    /**
     * Get routing value for shard selection
     */
    String routing();
    
    /**
     * Set routing value
     * @param routing Routing value for shard selection
     */
    T routing(String routing);
    
    /**
     * Get operation type (INDEX, CREATE, UPDATE, DELETE)
     */
    OpType opType();
    
    /**
     * Set operation type
     * @param opType Type of write operation
     */
    T opType(OpType opType);
    
    /**
     * Get version for optimistic concurrency control
     */
    long version();
    
    /**
     * Set document version
     * @param version Document version for conflict detection
     */
    T version(long version);
    
    /**
     * Get version type
     */
    VersionType versionType();
    
    /**
     * Set version type for conflict resolution
     * @param versionType Version type (INTERNAL, EXTERNAL, EXTERNAL_GTE)
     */
    T versionType(VersionType versionType);
    
    /**
     * Document write operation types
     */
    enum OpType {
        INDEX, CREATE, UPDATE, DELETE
    }
}

/**
 * Base response class for document write operations
 */
abstract class DocWriteResponse extends ActionResponse {
    /**
     * Get target index name
     */
    String getIndex();
    
    /**
     * Get document ID
     */
    String getId();
    
    /**
     * Get document version after operation
     */
    long getVersion();
    
    /**
     * Get operation result (CREATED, UPDATED, DELETED, NOT_FOUND, NOOP)
     */
    Result getResult();
    
    /**
     * Get shard information where operation was performed
     */
    ReplicationResponse.ShardInfo getShardInfo();
    
    /**
     * Get primary term for the document
     */
    long getPrimaryTerm();
    
    /**
     * Get sequence number for the document
     */
    long getSeqNo();
    
    /**
     * Document write operation results
     */
    enum Result {
        CREATED, UPDATED, DELETED, NOT_FOUND, NOOP
    }
}

/**
 * Request to index a document (create or update)
 */
class IndexRequest extends DocWriteRequest<IndexRequest> {
    /**
     * Create index request for specified index
     * @param index Target index name
     */
    IndexRequest(String index);
    
    /**
     * Set document ID
     * @param id Document identifier
     */
    IndexRequest id(String id);
    
    /**
     * Set document source from JSON string
     * @param source Document content as JSON
     * @param xContentType Content type of the source
     */
    IndexRequest source(String source, XContentType xContentType);
    
    /**
     * Set document source from map
     * @param source Document content as key-value pairs
     */
    IndexRequest source(Map<String, Object> source);
    
    /**
     * Set document source from byte array
     * @param source Document content as bytes
     * @param xContentType Content type of the source
     */
    IndexRequest source(byte[] source, XContentType xContentType);
    
    /**
     * Set create-only flag (fail if document exists)
     * @param create Whether to only create (not update) documents
     */
    IndexRequest create(boolean create);
    
    /**
     * Set request timeout
     * @param timeout Operation timeout
     */
    IndexRequest timeout(String timeout);
    
    /**
     * Set refresh policy for when changes become visible
     * @param refreshPolicy When to refresh (NONE, IMMEDIATE, WAIT_UNTIL)
     */
    IndexRequest setRefreshPolicy(WriteRequest.RefreshPolicy refreshPolicy);
    
    /**
     * Get document source
     */
    BytesReference source();
    
    /**
     * Get content type of the source
     */
    XContentType getContentType();
}

/**
 * Response for index operations containing operation result and metadata
 */
class IndexResponse extends DocWriteResponse {
    /**
     * Get index response status
     */
    RestStatus status();
    
    /**
     * Check if document was created (vs updated)
     */
    boolean isCreated();
}

/**
 * Request to retrieve a document by ID
 */
class GetRequest extends ActionRequest {
    /**
     * Create get request for document
     * @param index Index name
     * @param id Document ID
     */
    GetRequest(String index, String id);
    
    /**
     * Set routing value for shard selection
     * @param routing Routing value
     */
    GetRequest routing(String routing);
    
    /**
     * Set fields to include in response
     * @param fields Field names to retrieve
     */
    GetRequest storedFields(String... fields);
    
    /**
     * Set source filtering
     * @param fetchSource Whether to fetch document source
     */
    GetRequest fetchSourceContext(FetchSourceContext fetchSource);
    
    /**
     * Set document version for conflict detection
     * @param version Expected document version
     */
    GetRequest version(long version);
    
    /**
     * Set version type
     * @param versionType Version type for conflict resolution
     */
    GetRequest versionType(VersionType versionType);
    
    /**
     * Set real-time flag
     * @param realtime Whether to return real-time data or from index
     */
    GetRequest realtime(boolean realtime);
    
    /**
     * Set refresh flag
     * @param refresh Whether to refresh before get
     */
    GetRequest refresh(boolean refresh);
    
    /**
     * Get target index
     */
    String index();
    
    /**
     * Get document ID
     */
    String id();
}

/**
 * Response for get operations containing document data and metadata
 */
class GetResponse extends ActionResponse {
    /**
     * Get index name
     */
    String getIndex();
    
    /**
     * Get document ID
     */
    String getId();
    
    /**
     * Get document version
     */
    long getVersion();
    
    /**
     * Check if document exists
     */
    boolean isExists();
    
    /**
     * Get document source as string
     */
    String getSourceAsString();
    
    /**
     * Get document source as map
     */
    Map<String, Object> getSourceAsMap();
    
    /**
     * Get document source as bytes
     */
    BytesReference getSourceAsBytesRef();
    
    /**
     * Get stored fields
     */
    Map<String, DocumentField> getFields();
    
    /**
     * Check if source was found
     */
    boolean isSourceEmpty();
}

Update Operations

Document update operations with scripting and upsert support.

/**
 * Request to update a document with partial updates, scripts, or upserts
 */
class UpdateRequest extends DocWriteRequest<UpdateRequest> {
    /**
     * Create update request for document
     * @param index Index name
     * @param id Document ID
     */
    UpdateRequest(String index, String id);
    
    /**
     * Set partial document for merging
     * @param doc Partial document content
     * @param xContentType Content type of the document
     */
    UpdateRequest doc(String doc, XContentType xContentType);
    
    /**
     * Set partial document from map
     * @param source Partial document as key-value pairs
     */
    UpdateRequest doc(Map<String, Object> source);
    
    /**
     * Set upsert document (created if document doesn't exist)
     * @param upsert Document to insert if not found
     * @param xContentType Content type of the upsert document
     */
    UpdateRequest upsert(String upsert, XContentType xContentType);
    
    /**
     * Set upsert document from map
     * @param source Upsert document as key-value pairs
     */
    UpdateRequest upsert(Map<String, Object> source);
    
    /**
     * Set script for update operation
     * @param script Script to execute for update
     */
    UpdateRequest script(Script script);
    
    /**
     * Set whether to return updated document source
     * @param fetchSource Whether to fetch source in response
     */
    UpdateRequest fetchSource(boolean fetchSource);
    
    /**
     * Set source filtering for response
     * @param fetchSourceContext Source filtering configuration
     */
    UpdateRequest fetchSource(FetchSourceContext fetchSourceContext);
    
    /**
     * Set scripted upsert flag
     * @param scriptedUpsert Whether to use script for upsert
     */
    UpdateRequest scriptedUpsert(boolean scriptedUpsert);
    
    /**
     * Set doc as upsert flag
     * @param docAsUpsert Whether to use doc as upsert
     */
    UpdateRequest docAsUpsert(boolean docAsUpsert);
    
    /**
     * Set detect noop flag
     * @param detectNoop Whether to detect no-op updates
     */
    UpdateRequest detectNoop(boolean detectNoop);
    
    /**
     * Set retry on conflict count
     * @param retryOnConflict Number of times to retry on version conflicts
     */
    UpdateRequest retryOnConflict(int retryOnConflict);
    
    /**
     * Get partial document
     */
    IndexRequest doc();
    
    /**
     * Get upsert document
     */
    IndexRequest upsertRequest();
    
    /**
     * Get update script
     */
    Script script();
}

/**
 * Response for update operations containing update result and optional document data
 */
class UpdateResponse extends DocWriteResponse {
    /**
     * Get get result containing document data
     */
    GetResult getGetResult();
    
    /**
     * Check if get result is available
     */
    boolean hasGetResult();
}

/**
 * Request to delete a document by ID
 */
class DeleteRequest extends DocWriteRequest<DeleteRequest> {
    /**
     * Create delete request for document
     * @param index Index name
     * @param id Document ID
     */
    DeleteRequest(String index, String id);
    
    /**
     * Set request timeout
     * @param timeout Operation timeout
     */
    DeleteRequest timeout(String timeout);
    
    /**
     * Set refresh policy
     * @param refreshPolicy When to refresh after delete
     */
    DeleteRequest setRefreshPolicy(WriteRequest.RefreshPolicy refreshPolicy);
}

/**
 * Response for delete operations containing deletion result
 */
class DeleteResponse extends DocWriteResponse {
    /**
     * Check if document was found and deleted
     */
    boolean isFound();
}

Bulk Operations

Batch processing for multiple document operations with efficient execution.

/**
 * Request to execute multiple document operations in a single batch
 */
class BulkRequest extends ActionRequest {
    /**
     * Create empty bulk request
     */
    BulkRequest();
    
    /**
     * Create bulk request with initial capacity
     * @param globalIndex Default index for requests without explicit index
     */
    BulkRequest(String globalIndex);
    
    /**
     * Add document write request to bulk operation
     * @param request Document operation (index, update, delete)
     */
    BulkRequest add(DocWriteRequest<?> request);
    
    /**
     * Add index request to bulk operation
     * @param indexRequest Index request to add
     */
    BulkRequest add(IndexRequest indexRequest);
    
    /**
     * Add update request to bulk operation
     * @param updateRequest Update request to add
     */
    BulkRequest add(UpdateRequest updateRequest);
    
    /**
     * Add delete request to bulk operation
     * @param deleteRequest Delete request to add
     */
    BulkRequest add(DeleteRequest deleteRequest);
    
    /**
     * Add requests from byte array (newline-delimited JSON)
     * @param data Bulk request data in NDJSON format
     * @param xContentType Content type of the data
     */
    BulkRequest add(byte[] data, XContentType xContentType);
    
    /**
     * Set global refresh policy for all operations
     * @param refreshPolicy When to refresh after operations
     */
    BulkRequest setRefreshPolicy(WriteRequest.RefreshPolicy refreshPolicy);
    
    /**
     * Set request timeout
     * @param timeout Operation timeout
     */
    BulkRequest timeout(String timeout);
    
    /**
     * Get number of operations in bulk request
     */
    int numberOfActions();
    
    /**
     * Get list of requests
     */
    List<DocWriteRequest<?>> requests();
    
    /**
     * Get estimated size of the bulk request
     */
    long estimatedSizeInBytes();
}

/**
 * Response for bulk operations containing results for each individual operation
 */
class BulkResponse extends ActionResponse {
    /**
     * Get execution time for entire bulk operation
     */
    TimeValue getTook();
    
    /**
     * Check if any operations had errors
     */
    boolean hasFailures();
    
    /**
     * Get failure message summary
     */
    String buildFailureMessage();
    
    /**
     * Get results for all operations
     */
    BulkItemResponse[] getItems();
    
    /**
     * Get results as iterable
     */
    Iterable<BulkItemResponse> items();
    
    /**
     * Get ingest pipeline execution time
     */
    TimeValue getIngestTook();
}

/**
 * Individual operation result within a bulk response
 */
class BulkItemResponse implements Streamable {
    /**
     * Get operation index in bulk request
     */
    int getItemId();
    
    /**
     * Get operation type (index, create, update, delete)
     */
    String getOpType();
    
    /**
     * Check if operation failed
     */
    boolean isFailed();
    
    /**
     * Get operation response (if successful)
     */
    <T extends DocWriteResponse> T getResponse();
    
    /**
     * Get failure details (if failed)
     */
    BulkItemResponse.Failure getFailure();
    
    /**
     * Get operation version
     */
    long getVersion();
    
    /**
     * Get target index name
     */
    String getIndex();
    
    /**
     * Get document ID
     */
    String getId();
    
    /**
     * Failure information for failed bulk operations
     */
    static class Failure implements Streamable {
        /**
         * Get target index
         */
        String getIndex();
        
        /**
         * Get document ID
         */
        String getId();
        
        /**
         * Get failure cause
         */
        Exception getCause();
        
        /**
         * Get error message
         */
        String getMessage();
        
        /**
         * Get HTTP status code
         */
        RestStatus getStatus();
    }
}

/**
 * Container for bulk request items with metadata
 */
class BulkItemRequest implements Streamable {
    /**
     * Create bulk item request
     * @param id Item index in bulk request
     * @param request Document write request
     */
    BulkItemRequest(int id, DocWriteRequest<?> request);
    
    /**
     * Get item ID
     */
    int id();
    
    /**
     * Get document write request
     */
    DocWriteRequest<?> request();
    
    /**
     * Get abort flag
     */
    boolean isAborted();
    
    /**
     * Set abort flag
     * @param abort Whether to abort this operation
     */
    BulkItemRequest abort(boolean abort);
}

Multi-Get Operations

Batch retrieval of multiple documents by ID with efficient execution.

/**
 * Request to retrieve multiple documents by ID in a single batch operation
 */
class MultiGetRequest extends ActionRequest {
    /**
     * Create empty multi-get request
     */
    MultiGetRequest();
    
    /**
     * Add get request to batch
     * @param item Multi-get item specifying document to retrieve
     */
    MultiGetRequest add(MultiGetRequest.Item item);
    
    /**
     * Add get request with index and ID
     * @param index Index name
     * @param id Document ID
     */
    MultiGetRequest add(String index, String id);
    
    /**
     * Set global source filtering
     * @param fetchSource Whether to fetch document sources
     */
    MultiGetRequest fetchSourceContext(FetchSourceContext fetchSource);
    
    /**
     * Set real-time flag for all requests
     * @param realtime Whether to get real-time data
     */
    MultiGetRequest realtime(boolean realtime);
    
    /**
     * Set refresh flag for all requests
     * @param refresh Whether to refresh before get
     */
    MultiGetRequest refresh(boolean refresh);
    
    /**
     * Get list of items to retrieve
     */
    List<MultiGetRequest.Item> getItems();
    
    /**
     * Individual item in multi-get request
     */
    static class Item implements Streamable {
        /**
         * Create multi-get item
         * @param index Index name
         * @param id Document ID
         */
        Item(String index, String id);
        
        /**
         * Set routing value
         * @param routing Routing for shard selection
         */
        Item routing(String routing);
        
        /**
         * Set stored fields to retrieve
         * @param fields Field names to include
         */
        Item storedFields(String... fields);
        
        /**
         * Set source filtering
         * @param fetchSourceContext Source filtering configuration
         */
        Item fetchSourceContext(FetchSourceContext fetchSourceContext);
        
        /**
         * Set document version
         * @param version Expected document version
         */
        Item version(long version);
        
        /**
         * Set version type
         * @param versionType Version type for conflict resolution
         */
        Item versionType(VersionType versionType);
        
        /**
         * Get index name
         */
        String index();
        
        /**
         * Get document ID
         */
        String id();
    }
}

/**
 * Response for multi-get operations containing results for each requested document
 */
class MultiGetResponse extends ActionResponse {
    /**
     * Get results for all requested documents
     */
    MultiGetItemResponse[] getResponses();
    
    /**
     * Get responses as iterable
     */
    Iterable<MultiGetItemResponse> responses();
}

/**
 * Individual document result within a multi-get response
 */
class MultiGetItemResponse implements Streamable {
    /**
     * Create multi-get item response with get response
     * @param response Get response for the item
     * @param failure Failure information (null if successful)
     */
    MultiGetItemResponse(GetResponse response, MultiGetResponse.Failure failure);
    
    /**
     * Get document response (if successful)
     */
    GetResponse getResponse();
    
    /**
     * Get failure details (if failed)
     */
    MultiGetResponse.Failure getFailure();
    
    /**
     * Check if retrieval failed
     */
    boolean isFailed();
    
    /**
     * Get index name
     */
    String getIndex();
    
    /**
     * Get document ID
     */
    String getId();
}

Usage Examples

Basic Document Operations

import org.opensearch.action.index.IndexRequest;
import org.opensearch.action.index.IndexResponse;
import org.opensearch.action.get.GetRequest;
import org.opensearch.action.get.GetResponse;
import org.opensearch.action.update.UpdateRequest;
import org.opensearch.action.delete.DeleteRequest;
import org.opensearch.common.xcontent.XContentType;

// Index a document
IndexRequest indexRequest = new IndexRequest("products");
indexRequest.id("1");
indexRequest.source("""
    {
        "name": "Gaming Laptop",
        "price": 1299.99,
        "category": "electronics",
        "brand": "TechCorp",
        "in_stock": true,
        "tags": ["gaming", "laptop", "high-performance"]
    }
    """, XContentType.JSON);

indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);

IndexResponse indexResponse = client.index(indexRequest);
System.out.println("Document indexed: " + indexResponse.getResult());
System.out.println("Version: " + indexResponse.getVersion());
System.out.println("Created: " + indexResponse.status() == RestStatus.CREATED);

// Retrieve the document
GetRequest getRequest = new GetRequest("products", "1");
GetResponse getResponse = client.get(getRequest);

if (getResponse.isExists()) {
    System.out.println("Document found:");
    System.out.println("Source: " + getResponse.getSourceAsString());
    System.out.println("Version: " + getResponse.getVersion());
    
    Map<String, Object> source = getResponse.getSourceAsMap();
    System.out.println("Product name: " + source.get("name"));
    System.out.println("Price: " + source.get("price"));
} else {
    System.out.println("Document not found");
}

// Update the document
UpdateRequest updateRequest = new UpdateRequest("products", "1");
updateRequest.doc(Map.of(
    "price", 1199.99,
    "sale", true,
    "updated_at", "2024-01-15T10:30:00Z"
));
updateRequest.fetchSource(true); // Return updated document

UpdateResponse updateResponse = client.update(updateRequest);
System.out.println("Document updated: " + updateResponse.getResult());
if (updateResponse.hasGetResult()) {
    System.out.println("Updated source: " + updateResponse.getGetResult().sourceAsString());
}

// Delete the document
DeleteRequest deleteRequest = new DeleteRequest("products", "1");
DeleteResponse deleteResponse = client.delete(deleteRequest);
System.out.println("Document deleted: " + deleteResponse.getResult());
System.out.println("Found: " + deleteResponse.isFound());

Bulk Operations

import org.opensearch.action.bulk.BulkRequest;
import org.opensearch.action.bulk.BulkResponse;
import org.opensearch.action.bulk.BulkItemResponse;

// Create bulk request
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);

// Add multiple index operations
for (int i = 1; i <= 100; i++) {
    IndexRequest indexRequest = new IndexRequest("products");
    indexRequest.id(String.valueOf(i));
    indexRequest.source(Map.of(
        "name", "Product " + i,
        "price", Math.random() * 1000 + 10,
        "category", i % 2 == 0 ? "electronics" : "books",
        "created_at", "2024-01-" + String.format("%02d", (i % 28) + 1)
    ));
    
    bulkRequest.add(indexRequest);
}

// Add some update operations
UpdateRequest updateRequest = new UpdateRequest("products", "50");
updateRequest.doc(Map.of("featured", true, "priority", "high"));
bulkRequest.add(updateRequest);

// Add a delete operation
DeleteRequest deleteRequest = new DeleteRequest("products", "99");
bulkRequest.add(deleteRequest);

// Execute bulk request
BulkResponse bulkResponse = client.bulk(bulkRequest);

System.out.println("Bulk operation took: " + bulkResponse.getTook());
System.out.println("Has failures: " + bulkResponse.hasFailures());

if (bulkResponse.hasFailures()) {
    System.out.println("Failure message: " + bulkResponse.buildFailureMessage());
}

// Process individual results
int successCount = 0;
int failureCount = 0;

for (BulkItemResponse bulkItemResponse : bulkResponse) {
    if (bulkItemResponse.isFailed()) {
        failureCount++;
        BulkItemResponse.Failure failure = bulkItemResponse.getFailure();
        System.err.println("Failed operation for doc " + failure.getId() + ": " + failure.getMessage());
    } else {
        successCount++;
        DocWriteResponse response = bulkItemResponse.getResponse();
        System.out.println("Success: " + response.getResult() + " for doc " + response.getId());
    }
}

System.out.println("Successful operations: " + successCount);
System.out.println("Failed operations: " + failureCount);

Multi-Get Operations

import org.opensearch.action.get.MultiGetRequest;
import org.opensearch.action.get.MultiGetResponse;
import org.opensearch.action.get.MultiGetItemResponse;
import org.opensearch.search.fetch.subphase.FetchSourceContext;

// Create multi-get request
MultiGetRequest multiGetRequest = new MultiGetRequest();

// Add documents to retrieve
multiGetRequest.add("products", "1");
multiGetRequest.add("products", "2");
multiGetRequest.add("products", "3");

// Add item with specific field filtering
MultiGetRequest.Item item = new MultiGetRequest.Item("products", "4");
item.fetchSourceContext(new FetchSourceContext(true, new String[]{"name", "price"}, null));
multiGetRequest.add(item);

// Add item from different index
multiGetRequest.add("orders", "order_123");

// Execute multi-get
MultiGetResponse multiGetResponse = client.multiGet(multiGetRequest);

// Process results
for (MultiGetItemResponse itemResponse : multiGetResponse) {
    if (!itemResponse.isFailed()) {
        GetResponse response = itemResponse.getResponse();
        if (response.isExists()) {
            System.out.println("Document " + response.getId() + " from " + response.getIndex());
            System.out.println("Source: " + response.getSourceAsString());
        } else {
            System.out.println("Document " + response.getId() + " not found");
        }
    } else {
        System.err.println("Failed to retrieve document: " + itemResponse.getFailure().getMessage());
    }
}

Advanced Update with Scripts

import org.opensearch.script.Script;
import org.opensearch.script.ScriptType;

// Update with inline script
UpdateRequest scriptUpdateRequest = new UpdateRequest("products", "1");

Script incrementScript = new Script(
    ScriptType.INLINE,
    "painless",
    "ctx._source.view_count = (ctx._source.view_count ?: 0) + params.increment",
    Map.of("increment", 1)
);

scriptUpdateRequest.script(incrementScript);
scriptUpdateRequest.upsert(Map.of("view_count", 1)); // Create with initial value if doesn't exist

UpdateResponse scriptUpdateResponse = client.update(scriptUpdateRequest);
System.out.println("Script update result: " + scriptUpdateResponse.getResult());

// Update with conditional logic
UpdateRequest conditionalUpdate = new UpdateRequest("products", "2");

Script conditionalScript = new Script(
    ScriptType.INLINE,
    "painless",
    """
    if (ctx._source.price > params.threshold) {
        ctx._source.discount = params.discount_rate;
        ctx._source.sale_price = ctx._source.price * (1 - params.discount_rate);
    } else {
        ctx.op = 'noop';
    }
    """,
    Map.of(
        "threshold", 100.0,
        "discount_rate", 0.15
    )
);

conditionalUpdate.script(conditionalScript);
conditionalUpdate.detectNoop(true);

UpdateResponse conditionalResponse = client.update(conditionalUpdate);
System.out.println("Conditional update result: " + conditionalResponse.getResult());

Types

/**
 * Write request configuration for controlling when changes become visible
 */
interface WriteRequest<T extends WriteRequest<T>> {
    /**
     * Set refresh policy for the operation
     * @param refreshPolicy When to refresh the index
     */
    T setRefreshPolicy(RefreshPolicy refreshPolicy);
    
    /**
     * Get current refresh policy
     */
    RefreshPolicy getRefreshPolicy();
    
    /**
     * Refresh policy options
     */
    enum RefreshPolicy {
        /**
         * No refresh (changes may not be immediately searchable)
         */
        NONE,
        
        /**
         * Immediate refresh (changes immediately searchable, but impacts performance)
         */
        IMMEDIATE,
        
        /**
         * Wait until refresh (wait for next scheduled refresh)
         */
        WAIT_UNTIL
    }
}

/**
 * Version types for optimistic concurrency control
 */
enum VersionType {
    /**
     * Internal versioning (managed by OpenSearch)
     */
    INTERNAL,
    
    /**
     * External versioning (managed by client application)
     */
    EXTERNAL,
    
    /**
     * External versioning with greater-than-or-equal semantics
     */
    EXTERNAL_GTE
}

/**
 * Source filtering configuration for controlling which fields to return
 */
class FetchSourceContext implements Streamable {
    /**
     * Fetch all source fields
     */
    static final FetchSourceContext FETCH_SOURCE = new FetchSourceContext(true);
    
    /**
     * Don't fetch any source fields
     */
    static final FetchSourceContext DO_NOT_FETCH_SOURCE = new FetchSourceContext(false);
    
    /**
     * Create fetch source context with include/exclude patterns
     * @param fetchSource Whether to fetch source
     * @param includes Field patterns to include
     * @param excludes Field patterns to exclude
     */
    FetchSourceContext(boolean fetchSource, String[] includes, String[] excludes);
    
    /**
     * Check if source should be fetched
     */
    boolean fetchSource();
    
    /**
     * Get include patterns
     */
    String[] includes();
    
    /**
     * Get exclude patterns
     */
    String[] excludes();
}

/**
 * Validation exception for action request parameter errors
 */
class ActionRequestValidationException extends OpenSearchException {
    /**
     * Add validation error
     * @param error Error message to add
     */
    ActionRequestValidationException addValidationError(String error);
    
    /**
     * Get all validation errors
     */
    List<String> validationErrors();
}

/**
 * Script configuration for update operations
 */
class Script implements Streamable {
    /**
     * Create inline script
     * @param type Script type (INLINE, STORED, FILE)
     * @param lang Script language (painless, expression, etc.)
     * @param idOrCode Script ID (for stored) or code (for inline)
     * @param params Script parameters
     */
    Script(ScriptType type, String lang, String idOrCode, Map<String, Object> params);
    
    /**
     * Get script type
     */
    ScriptType getType();
    
    /**
     * Get script language
     */
    String getLang();
    
    /**
     * Get script ID or code
     */
    String getIdOrCode();
    
    /**
     * Get script parameters
     */
    Map<String, Object> getParams();
}

Install with Tessl CLI

npx tessl i tessl/maven-org-opensearch--opensearch

docs

action-framework.md

client-apis.md

cluster-management.md

index-management.md

index.md

plugin-framework.md

search-apis.md

tile.json