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

search-apis.mddocs/

Search APIs

Comprehensive search functionality including the Query DSL, aggregations, search builders, and advanced search features like scrolling and point-in-time searches. OpenSearch provides a rich set of APIs for executing complex search operations across distributed indices.

Capabilities

Core Search Operations

The primary search interfaces for executing queries against OpenSearch indices.

/**
 * Main search request class for executing queries against indices
 */
class SearchRequest extends ActionRequest {
    /**
     * Create search request for specified indices
     * @param indices Index names to search (empty for all indices)
     */
    SearchRequest(String... indices);
    
    /**
     * Set search source configuration
     * @param sourceBuilder Search source builder with query, aggregations, etc.
     */
    SearchRequest source(SearchSourceBuilder sourceBuilder);
    
    /**
     * Set routing for request
     * @param routing Routing value for shard selection
     */
    SearchRequest routing(String routing);
    
    /**
     * Set request timeout
     * @param timeout Timeout value (e.g., "1m", "30s")
     */
    SearchRequest timeout(String timeout);
    
    /**
     * Set search type
     * @param searchType Search execution type
     */
    SearchRequest searchType(SearchType searchType);
    
    /**
     * Set scroll timeout for scrollable searches
     * @param scroll Scroll timeout (e.g., "1m")
     */
    SearchRequest scroll(String scroll);
    
    /**
     * Get configured indices
     */
    String[] indices();
    
    /**
     * Get search source builder
     */
    SearchSourceBuilder source();
}

/**
 * Search operation response containing results and metadata
 */
class SearchResponse extends ActionResponse {
    /**
     * Get search hits container
     */
    SearchHits getHits();
    
    /**
     * Get aggregation results
     */
    Aggregations getAggregations();
    
    /**
     * Get scroll ID for pagination
     */
    String getScrollId();
    
    /**
     * Check if request timed out
     */
    boolean isTimedOut();
    
    /**
     * Get search execution time
     */
    TimeValue getTook();
    
    /**
     * Get number of shards searched
     */
    int getTotalShards();
    
    /**
     * Get number of successful shard searches
     */
    int getSuccessfulShards();
    
    /**
     * Get search failures
     */
    ShardSearchFailure[] getShardFailures();
}

Search Source Builder

Fluent API for constructing complex search queries with filters, aggregations, and result formatting.

/**
 * Builder for constructing search query DSL with fluent interface
 */
class SearchSourceBuilder implements Streamable {
    /**
     * Create empty search source builder
     */
    SearchSourceBuilder();
    
    /**
     * Set main query
     * @param query Query builder for search criteria
     */
    SearchSourceBuilder query(QueryBuilder query);
    
    /**
     * Add aggregation to search
     * @param aggregation Aggregation builder for statistical analysis
     */
    SearchSourceBuilder aggregation(AggregationBuilder aggregation);
    
    /**
     * Set number of results to return
     * @param size Maximum number of hits (default: 10)
     */
    SearchSourceBuilder size(int size);
    
    /**
     * Set starting offset for pagination
     * @param from Starting index for results (default: 0)
     */
    SearchSourceBuilder from(int from);
    
    /**
     * Add sort criteria
     * @param sort Sort builder for result ordering
     */
    SearchSourceBuilder sort(SortBuilder<?> sort);
    
    /**
     * Set timeout for search execution
     * @param timeout Execution timeout
     */
    SearchSourceBuilder timeout(TimeValue timeout);
    
    /**
     * Configure source field filtering
     * @param include Fields to include in results
     * @param exclude Fields to exclude from results
     */
    SearchSourceBuilder fetchSource(String[] include, String[] exclude);
    
    /**
     * Add highlighting configuration
     * @param highlight Highlight builder for result highlighting
     */
    SearchSourceBuilder highlighter(HighlightBuilder highlight);
    
    /**
     * Add post-filter query
     * @param postFilter Filter applied after aggregations
     */
    SearchSourceBuilder postFilter(QueryBuilder postFilter);
    
    /**
     * Set minimum score threshold
     * @param minScore Minimum score for returned documents
     */
    SearchSourceBuilder minScore(float minScore);
    
    /**
     * Get configured query
     */
    QueryBuilder query();
    
    /**
     * Get configured aggregations
     */
    List<AggregationBuilder> aggregations();
}

Query Builders

Comprehensive Query DSL implementation for building search criteria.

/**
 * Base interface for all query builders in the Query DSL
 */
interface QueryBuilder extends NamedWriteable, Rewriteable<QueryBuilder> {
    /**
     * Get query name for identification
     */
    String getWriteableName();
    
    /**
     * Rewrite query for optimization
     */
    QueryBuilder rewrite(QueryRewriteContext context) throws IOException;
}

/**
 * Boolean query builder for combining multiple queries with logical operators
 */
class BoolQueryBuilder implements QueryBuilder {
    /**
     * Create boolean query builder
     */
    BoolQueryBuilder();
    
    /**
     * Add query that must match (AND logic)
     * @param query Query that must be satisfied
     */
    BoolQueryBuilder must(QueryBuilder query);
    
    /**
     * Add query that must not match (NOT logic)
     * @param query Query that must not be satisfied
     */
    BoolQueryBuilder mustNot(QueryBuilder query);
    
    /**
     * Add query that should match (OR logic, affects scoring)
     * @param query Query that should be satisfied
     */
    BoolQueryBuilder should(QueryBuilder query);
    
    /**
     * Add filter query (no scoring)
     * @param query Filter query for exact matching
     */
    BoolQueryBuilder filter(QueryBuilder query);
    
    /**
     * Set minimum should match
     * @param minimumShouldMatch Minimum number of should clauses that must match
     */
    BoolQueryBuilder minimumShouldMatch(String minimumShouldMatch);
    
    /**
     * Set query boost factor
     * @param boost Boost multiplier for relevance scoring
     */
    BoolQueryBuilder boost(float boost);
}

/**
 * Match query builder for full-text search with analysis
 */
class MatchQueryBuilder implements QueryBuilder {
    /**
     * Create match query for field and value
     * @param name Field name to search
     * @param text Search text to match
     */
    MatchQueryBuilder(String name, Object text);
    
    /**
     * Set operator for multiple terms
     * @param operator AND or OR operator for term combination
     */
    MatchQueryBuilder operator(Operator operator);
    
    /**
     * Set analyzer for query text
     * @param analyzer Analyzer name for text processing
     */
    MatchQueryBuilder analyzer(String analyzer);
    
    /**
     * Set fuzziness for approximate matching
     * @param fuzziness Fuzziness configuration (AUTO, 0, 1, 2)
     */
    MatchQueryBuilder fuzziness(Fuzziness fuzziness);
    
    /**
     * Set minimum should match
     * @param minimumShouldMatch Minimum percentage or count of terms that should match
     */
    MatchQueryBuilder minimumShouldMatch(String minimumShouldMatch);
}

/**
 * Term query builder for exact term matching without analysis
 */
class TermQueryBuilder implements QueryBuilder {
    /**
     * Create term query for exact field value
     * @param name Field name
     * @param value Exact term value to match
     */
    TermQueryBuilder(String name, Object value);
    
    /**
     * Set boost factor
     * @param boost Relevance score boost multiplier
     */
    TermQueryBuilder boost(float boost);
}

/**
 * Range query builder for numeric and date range matching
 */
class RangeQueryBuilder implements QueryBuilder {
    /**
     * Create range query for field
     * @param fieldName Field name for range query
     */
    RangeQueryBuilder(String fieldName);
    
    /**
     * Set greater than or equal constraint
     * @param gte Minimum value (inclusive)
     */
    RangeQueryBuilder gte(Object gte);
    
    /**
     * Set greater than constraint
     * @param gt Minimum value (exclusive)
     */
    RangeQueryBuilder gt(Object gt);
    
    /**
     * Set less than or equal constraint
     * @param lte Maximum value (inclusive)  
     */
    RangeQueryBuilder lte(Object lte);
    
    /**
     * Set less than constraint
     * @param lt Maximum value (exclusive)
     */
    RangeQueryBuilder lt(Object lt);
    
    /**
     * Set format for date parsing
     * @param format Date format string
     */
    RangeQueryBuilder format(String format);
}

Query Builders Factory

Static factory methods for creating query builders.

/**
 * Static factory class for creating query builders
 */
class QueryBuilders {
    /**
     * Create match-all query (matches every document)
     */
    static MatchAllQueryBuilder matchAllQuery();
    
    /**
     * Create match query for full-text search
     * @param name Field name
     * @param text Search text
     */
    static MatchQueryBuilder matchQuery(String name, Object text);
    
    /**
     * Create multi-match query across multiple fields
     * @param text Search text
     * @param fieldNames Fields to search
     */
    static MultiMatchQueryBuilder multiMatchQuery(Object text, String... fieldNames);
    
    /**
     * Create term query for exact matching
     * @param name Field name
     * @param value Exact value to match
     */
    static TermQueryBuilder termQuery(String name, Object value);
    
    /**
     * Create terms query for matching multiple exact values
     * @param name Field name
     * @param values Array of exact values to match
     */
    static TermsQueryBuilder termsQuery(String name, Object... values);
    
    /**
     * Create range query for numeric/date ranges
     * @param name Field name
     */
    static RangeQueryBuilder rangeQuery(String name);
    
    /**
     * Create boolean query for combining multiple queries
     */
    static BoolQueryBuilder boolQuery();
    
    /**
     * Create wildcard query for pattern matching
     * @param name Field name
     * @param query Wildcard pattern (* and ?)
     */
    static WildcardQueryBuilder wildcardQuery(String name, String query);
    
    /**
     * Create fuzzy query for approximate matching
     * @param name Field name
     * @param value Search value
     */
    static FuzzyQueryBuilder fuzzyQuery(String name, Object value);
    
    /**
     * Create nested query for nested object fields
     * @param path Nested object path
     * @param query Query to apply to nested objects
     * @param scoreMode Score calculation mode
     */
    static NestedQueryBuilder nestedQuery(String path, QueryBuilder query, ScoreMode scoreMode);
}

Aggregation Framework

Statistical and analytical computations over search results.

/**
 * Base interface for all aggregation builders
 */
interface AggregationBuilder extends NamedWriteable {
    /**
     * Get aggregation name
     */
    String getName();
    
    /**
     * Get aggregation type
     */
    String getType();
    
    /**
     * Add sub-aggregation
     * @param aggregation Child aggregation builder
     */
    AggregationBuilder subAggregation(AggregationBuilder aggregation);
}

/**
 * Collection of aggregation results from search response
 */
class Aggregations implements Iterable<Aggregation> {
    /**
     * Get aggregation by name
     * @param name Aggregation name
     */
    Aggregation get(String name);
    
    /**
     * Get all aggregations as map
     */
    Map<String, Aggregation> asMap();
    
    /**
     * Get list of all aggregations
     */
    List<Aggregation> asList();
}

/**
 * Terms aggregation builder for grouping by field values
 */
class TermsAggregationBuilder implements AggregationBuilder {
    /**
     * Create terms aggregation
     * @param name Aggregation name
     */
    TermsAggregationBuilder(String name);
    
    /**
     * Set field to group by
     * @param field Field name for grouping
     */
    TermsAggregationBuilder field(String field);
    
    /**
     * Set number of top terms to return
     * @param size Maximum number of buckets
     */
    TermsAggregationBuilder size(int size);
    
    /**
     * Set ordering criteria
     * @param order Sort order for buckets
     */
    TermsAggregationBuilder order(BucketOrder order);
    
    /**
     * Set minimum document count for inclusion
     * @param minDocCount Minimum documents required per bucket
     */
    TermsAggregationBuilder minDocCount(long minDocCount);
}

/**
 * Date histogram aggregation builder for time-based grouping
 */
class DateHistogramAggregationBuilder implements AggregationBuilder {
    /**
     * Create date histogram aggregation
     * @param name Aggregation name
     */
    DateHistogramAggregationBuilder(String name);
    
    /**
     * Set field for date grouping
     * @param field Date field name
     */
    DateHistogramAggregationBuilder field(String field);
    
    /**
     * Set calendar interval
     * @param interval Calendar interval (month, week, day, hour, etc.)
     */
    DateHistogramAggregationBuilder calendarInterval(DateHistogramInterval interval);
    
    /**
     * Set fixed interval
     * @param interval Fixed time interval (30s, 1m, 1h, etc.)
     */
    DateHistogramAggregationBuilder fixedInterval(DateHistogramInterval interval);
    
    /**
     * Set time zone
     * @param timeZone Time zone for date calculations
     */
    DateHistogramAggregationBuilder timeZone(ZoneId timeZone);
}

Multi-Search Operations

Batch multiple search requests for efficient execution.

/**
 * Multiple search requests executed in a single batch operation
 */
class MultiSearchRequest extends ActionRequest {
    /**
     * Create multi-search request
     */
    MultiSearchRequest();
    
    /**
     * Add search request to batch
     * @param searchRequest Individual search request
     */
    MultiSearchRequest add(SearchRequest searchRequest);
    
    /**
     * Add search request with request item
     * @param searchRequestItem Search request with metadata
     */
    MultiSearchRequest add(SearchRequestItem searchRequestItem);
    
    /**
     * Get number of search requests
     */
    int numberOfSearchRequests();
    
    /**
     * Get search requests list
     */
    List<SearchRequest> requests();
}

/**
 * Response for multi-search operations containing individual responses
 */
class MultiSearchResponse extends ActionResponse {
    /**
     * Get array of individual search responses
     */
    MultiSearchResponse.Item[] getResponses();
    
    /**
     * Individual multi-search response item
     */
    static class Item {
        /**
         * Check if response contains failure
         */
        boolean isFailure();
        
        /**
         * Get search response (null if failed)
         */
        SearchResponse getResponse();
        
        /**
         * Get failure exception (null if successful)
         */
        Exception getFailure();
    }
}

Search Scrolling and Point-in-Time

APIs for handling large result sets and consistent snapshots.

/**
 * Scroll search request for paginating through large result sets
 */
class SearchScrollRequest extends ActionRequest {
    /**
     * Create scroll request with scroll ID
     * @param scrollId Scroll context ID from previous search
     */
    SearchScrollRequest(String scrollId);
    
    /**
     * Set scroll timeout
     * @param scroll Scroll context timeout (e.g., "1m")
     */
    SearchScrollRequest scroll(String scroll);
    
    /**
     * Get scroll ID
     */
    String scrollId();
}

/**
 * Clear scroll request to release scroll context resources
 */
class ClearScrollRequest extends ActionRequest {
    /**
     * Create clear scroll request
     */
    ClearScrollRequest();
    
    /**
     * Add scroll ID to clear
     * @param scrollId Scroll context ID to release
     */
    void addScrollId(String scrollId);
    
    /**
     * Set scroll IDs to clear
     * @param scrollIds List of scroll context IDs
     */
    void setScrollIds(List<String> scrollIds);
}

/**
 * Point-in-time search request for consistent snapshots across searches
 */
class CreatePitRequest extends ActionRequest {
    /**
     * Create PIT request for indices
     * @param indices Index names for point-in-time snapshot
     */
    CreatePitRequest(String... indices);
    
    /**
     * Set PIT keepalive time
     * @param keepAlive How long to keep PIT context active
     */
    CreatePitRequest keepAlive(TimeValue keepAlive);
    
    /**
     * Set routing for PIT creation
     * @param routing Routing value for shard selection
     */
    CreatePitRequest routing(String routing);
}

/**
 * Point-in-time creation response containing PIT ID
 */
class CreatePitResponse extends ActionResponse {
    /**
     * Get point-in-time ID for subsequent searches
     */
    String getId();
    
    /**
     * Get creation time
     */
    long getCreationTime();
}

/**
 * Delete point-in-time request to release PIT resources
 */
class DeletePitRequest extends ActionRequest {
    /**
     * Create delete PIT request
     */
    DeletePitRequest();
    
    /**
     * Add PIT ID to delete
     * @param pitId Point-in-time ID to release
     */
    void addPitId(String pitId);
    
    /**
     * Set PIT IDs to delete
     * @param pitIds List of PIT IDs to release
     */
    void setPitIds(List<String> pitIds);
}

Point-in-Time Builder

Configuration for point-in-time search context.

/**
 * Builder for point-in-time search configuration
 */
class PointInTimeBuilder implements Streamable {
    /**
     * Create PIT builder with ID
     * @param id Point-in-time ID from CreatePitResponse
     */
    PointInTimeBuilder(String id);
    
    /**
     * Set keepalive time for PIT context
     * @param keepAlive Duration to keep PIT active
     */
    PointInTimeBuilder setKeepAlive(TimeValue keepAlive);
    
    /**
     * Get PIT ID
     */
    String getId();
    
    /**
     * Get keepalive time
     */
    TimeValue getKeepAlive();
}

Usage Examples

Basic Search Operations

import org.opensearch.action.search.SearchRequest;
import org.opensearch.action.search.SearchResponse;
import org.opensearch.search.builder.SearchSourceBuilder;
import org.opensearch.index.query.QueryBuilders;
import org.opensearch.search.SearchHit;

// Simple match query
SearchRequest searchRequest = new SearchRequest("products");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("name", "laptop"));
searchSourceBuilder.size(10);
searchRequest.source(searchSourceBuilder);

SearchResponse searchResponse = client.search(searchRequest);
System.out.println("Total hits: " + searchResponse.getHits().getTotalHits().value);

for (SearchHit hit : searchResponse.getHits()) {
    System.out.println("Document ID: " + hit.getId());
    System.out.println("Source: " + hit.getSourceAsString());
    System.out.println("Score: " + hit.getScore());
}

Complex Boolean Query

import org.opensearch.index.query.BoolQueryBuilder;
import org.opensearch.index.query.RangeQueryBuilder;

// Complex boolean query with multiple criteria
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery()
    .must(QueryBuilders.matchQuery("category", "electronics"))
    .must(QueryBuilders.rangeQuery("price").gte(100).lte(1000))
    .should(QueryBuilders.termQuery("brand", "apple"))
    .should(QueryBuilders.termQuery("brand", "samsung"))
    .mustNot(QueryBuilders.termQuery("status", "discontinued"))
    .minimumShouldMatch("1");

SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
    .query(boolQuery)
    .size(20)
    .from(0);

SearchRequest searchRequest = new SearchRequest("products");
searchRequest.source(searchSourceBuilder);

Aggregations

import org.opensearch.search.aggregations.AggregationBuilders;
import org.opensearch.search.aggregations.bucket.terms.Terms;
import org.opensearch.search.aggregations.metrics.Avg;

// Terms aggregation with sub-aggregation
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
    .query(QueryBuilders.matchAllQuery())
    .aggregation(
        AggregationBuilders.terms("categories")
            .field("category.keyword")
            .size(10)
            .subAggregation(
                AggregationBuilders.avg("avg_price")
                    .field("price")
            )
    )
    .size(0); // Don't return documents, only aggregations

SearchRequest searchRequest = new SearchRequest("products");
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest);

Terms categories = searchResponse.getAggregations().get("categories");
for (Terms.Bucket bucket : categories.getBuckets()) {
    System.out.println("Category: " + bucket.getKeyAsString());
    System.out.println("Doc count: " + bucket.getDocCount());
    
    Avg avgPrice = bucket.getAggregations().get("avg_price");
    System.out.println("Average price: " + avgPrice.getValue());
}

Scrolling for Large Results

import org.opensearch.action.search.SearchScrollRequest;
import org.opensearch.common.unit.TimeValue;

// Initial scroll search
SearchRequest searchRequest = new SearchRequest("large_index");
searchRequest.scroll(TimeValue.timeValueMinutes(1L));
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
    .query(QueryBuilders.matchAllQuery())
    .size(1000); // Large batch size
searchRequest.source(searchSourceBuilder);

SearchResponse searchResponse = client.search(searchRequest);
String scrollId = searchResponse.getScrollId();

// Continue scrolling
while (searchResponse.getHits().getHits().length > 0) {
    // Process current batch
    for (SearchHit hit : searchResponse.getHits()) {
        // Process document
        System.out.println(hit.getSourceAsString());
    }
    
    // Get next batch
    SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
    scrollRequest.scroll(TimeValue.timeValueMinutes(1L));
    searchResponse = client.scroll(scrollRequest);
    scrollId = searchResponse.getScrollId();
}

// Clean up scroll context
ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
clearScrollRequest.addScrollId(scrollId);
client.clearScroll(clearScrollRequest);

Point-in-Time Search

import org.opensearch.action.search.CreatePitRequest;
import org.opensearch.action.search.CreatePitResponse;
import org.opensearch.search.builder.PointInTimeBuilder;

// Create point-in-time
CreatePitRequest createPitRequest = new CreatePitRequest("products");
createPitRequest.keepAlive(TimeValue.timeValueMinutes(5));
CreatePitResponse createPitResponse = client.createPit(createPitRequest);
String pitId = createPitResponse.getId();

// Search with PIT for consistency
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
    .query(QueryBuilders.matchAllQuery())
    .pointInTimeBuilder(new PointInTimeBuilder(pitId))
    .size(100)
    .sort("_shard_doc");

SearchRequest searchRequest = new SearchRequest();
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest);

// Clean up PIT
DeletePitRequest deletePitRequest = new DeletePitRequest();
deletePitRequest.addPitId(pitId);
client.deletePit(deletePitRequest);

Types

/**
 * Search hits container with total count and individual hits
 */
class SearchHits implements Streamable, Iterable<SearchHit> {
    /**
     * Get total hits information
     */
    TotalHits getTotalHits();
    
    /**
     * Get maximum score across all hits
     */
    float getMaxScore();
    
    /**
     * Get array of search hits
     */
    SearchHit[] getHits();
    
    /**
     * Get search hits as list
     */
    List<SearchHit> asList();
}

/**
 * Individual search result hit
 */
class SearchHit implements Streamable {
    /**
     * Get document ID
     */
    String getId();
    
    /**
     * Get document index
     */
    String getIndex();
    
    /**
     * Get relevance score
     */
    float getScore();
    
    /**
     * Get document source as string
     */
    String getSourceAsString();
    
    /**
     * Get document source as map
     */
    Map<String, Object> getSourceAsMap();
    
    /**
     * Get highlighted fragments
     */
    Map<String, HighlightField> getHighlightFields();
}

/**
 * Search execution types
 */
enum SearchType {
    /**
     * Default search type with query then fetch phases
     */
    QUERY_THEN_FETCH,
    
    /**
     * Distributed frequency search for accurate scoring
     */
    DFS_QUERY_THEN_FETCH
}

/**
 * Score calculation modes for nested queries
 */
enum ScoreMode {
    /**
     * Use average score of matching nested documents
     */
    Avg,
    
    /**
     * Use maximum score of matching nested documents  
     */
    Max,
    
    /**
     * Use minimum score of matching nested documents
     */
    Min,
    
    /**
     * Use sum of scores from matching nested documents
     */
    Sum,
    
    /**
     * No scoring (filter context)
     */
    None
}

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