Class SearchRequest

java.lang.Object
co.elastic.clients.elasticsearch._types.RequestBase
co.elastic.clients.elasticsearch.core.SearchRequest
All Implemented Interfaces:
JsonpSerializable

@JsonpDeserializable public class SearchRequest extends RequestBase implements JsonpSerializable
Run a search.

Get search hits that match the query defined in the request. You can provide search queries using the q query string parameter or the request body. If both are specified, only the query parameter is used.

If the Elasticsearch security features are enabled, you must have the read index privilege for the target data stream, index, or alias. For cross-cluster search, refer to the documentation about configuring CCS privileges. To search a point in time (PIT) for an alias, you must have the read index privilege for the alias's data streams or indices.

Search slicing

When paging through a large number of documents, it can be helpful to split the search into multiple slices to consume them independently with the slice and pit properties. By default the splitting is done first on the shards, then locally on each shard. The local splitting partitions the shard into contiguous ranges based on Lucene document IDs.

For instance if the number of shards is equal to 2 and you request 4 slices, the slices 0 and 2 are assigned to the first shard and the slices 1 and 3 are assigned to the second shard.

IMPORTANT: The same point-in-time ID should be used for all slices. If different PIT IDs are used, slices can overlap and miss documents. This situation can occur because the splitting criterion is based on Lucene document IDs, which are not stable across changes to the index.

See Also:
  • Field Details

  • Method Details

    • of

    • source

      @Nullable public final SourceConfig source()
      The source fields that are returned for matching documents. These fields are returned in the hits._source property of the search response. If the stored_fields property is specified, the _source property defaults to false. Otherwise, it defaults to true.

      API name: _source

    • aggregations

      public final Map<String,Aggregation> aggregations()
      Defines the aggregations that are run as part of the search request.

      API name: aggregations

    • allowNoIndices

      @Nullable public final Boolean allowNoIndices()
      If false, the request returns an error if any wildcard expression, index alias, or _all value targets only missing or closed indices. This behavior applies even if the request targets other open indices. For example, a request targeting foo*,bar* returns an error if an index starts with foo but no index starts with bar.

      API name: allow_no_indices

    • allowPartialSearchResults

      @Nullable public final Boolean allowPartialSearchResults()
      If true and there are shard request timeouts or shard failures, the request returns partial results. If false, it returns an error with no partial results.

      To override the default behavior, you can set the search.default_allow_partial_results cluster setting to false.

      API name: allow_partial_search_results

    • analyzeWildcard

      @Nullable public final Boolean analyzeWildcard()
      If true, wildcard and prefix queries are analyzed. This parameter can be used only when the q query string parameter is specified.

      API name: analyze_wildcard

    • analyzer

      @Nullable public final String analyzer()
      The analyzer to use for the query string. This parameter can be used only when the q query string parameter is specified.

      API name: analyzer

    • batchedReduceSize

      @Nullable public final Long batchedReduceSize()
      The number of shard results that should be reduced at once on the coordinating node. If the potential number of shards in the request can be large, this value should be used as a protection mechanism to reduce the memory overhead per search request.

      API name: batched_reduce_size

    • ccsMinimizeRoundtrips

      @Nullable public final Boolean ccsMinimizeRoundtrips()
      If true, network round-trips between the coordinating node and the remote clusters are minimized when running cross-cluster search (CCS) requests.

      API name: ccs_minimize_roundtrips

    • collapse

      @Nullable public final FieldCollapse collapse()
      Collapses search results the values of the specified field.

      API name: collapse

    • defaultOperator

      @Nullable public final Operator defaultOperator()
      The default operator for the query string query: AND or OR. This parameter can be used only when the q query string parameter is specified.

      API name: default_operator

    • df

      @Nullable public final String df()
      The field to use as a default when no field prefix is given in the query string. This parameter can be used only when the q query string parameter is specified.

      API name: df

    • docvalueFields

      public final List<FieldAndFormat> docvalueFields()
      An array of wildcard (*) field patterns. The request returns doc values for field names matching these patterns in the hits.fields property of the response.

      API name: docvalue_fields

    • expandWildcards

      public final List<ExpandWildcard> expandWildcards()
      The type of index that wildcard patterns can match. If the request can target data streams, this argument determines whether wildcard expressions match hidden data streams. It supports comma-separated values such as open,hidden.

      API name: expand_wildcards

    • explain

      @Nullable public final Boolean explain()
      If true, the request returns detailed information about score computation as part of a hit.

      API name: explain

    • ext

      public final Map<String,JsonData> ext()
      Configuration of search extensions defined by Elasticsearch plugins.

      API name: ext

    • fields

      public final List<FieldAndFormat> fields()
      An array of wildcard (*) field patterns. The request returns values for field names matching these patterns in the hits.fields property of the response.

      API name: fields

    • forceSyntheticSource

      @Nullable public final Boolean forceSyntheticSource()
      Should this request force synthetic _source? Use this to test if the mapping supports synthetic _source and to get a sense of the worst case performance. Fetches with this enabled will be slower the enabling synthetic source natively in the index.

      API name: force_synthetic_source

    • from

      @Nullable public final Integer from()
      The starting document offset, which must be non-negative. By default, you cannot page through more than 10,000 hits using the from and size parameters. To page through more hits, use the search_after parameter.

      API name: from

    • highlight

      @Nullable public final Highlight highlight()
      Specifies the highlighter to use for retrieving highlighted snippets from one or more fields in your search results.

      API name: highlight

    • ignoreThrottled

      @Deprecated @Nullable public final Boolean ignoreThrottled()
      Deprecated.
      7.16.0
      If true, concrete, expanded or aliased indices will be ignored when frozen.

      API name: ignore_throttled

    • ignoreUnavailable

      @Nullable public final Boolean ignoreUnavailable()
      If false, the request returns an error if it targets a missing or closed index.

      API name: ignore_unavailable

    • includeNamedQueriesScore

      @Nullable public final Boolean includeNamedQueriesScore()
      If true, the response includes the score contribution from any named queries.

      This functionality reruns each named query on every hit in a search response. Typically, this adds a small overhead to a request. However, using computationally expensive named queries on a large number of hits may add significant overhead.

      API name: include_named_queries_score

    • index

      public final List<String> index()
      A comma-separated list of data streams, indices, and aliases to search. It supports wildcards (*). To search all data streams and indices, omit this parameter or use * or _all.

      API name: index

    • indicesBoost

      public final List<NamedValue<Double>> indicesBoost()
      Boost the _score of documents from specified indices. The boost value is the factor by which scores are multiplied. A boost value greater than 1.0 increases the score. A boost value between 0 and 1.0 decreases the score.

      API name: indices_boost

    • knn

      public final List<KnnSearch> knn()
      The approximate kNN search to run.

      API name: knn

    • lenient

      @Nullable public final Boolean lenient()
      If true, format-based query failures (such as providing text to a numeric field) in the query string will be ignored. This parameter can be used only when the q query string parameter is specified.

      API name: lenient

    • maxConcurrentShardRequests

      @Nullable public final Integer maxConcurrentShardRequests()
      The number of concurrent shard requests per node that the search runs concurrently. This value should be used to limit the impact of the search on the cluster in order to limit the number of concurrent shard requests.

      API name: max_concurrent_shard_requests

    • minScore

      @Nullable public final Double minScore()
      The minimum _score for matching documents. Documents with a lower _score are not included in search results and results collected by aggregations.

      API name: min_score

    • pit

      @Nullable public final PointInTimeReference pit()
      Limit the search to a point in time (PIT). If you provide a PIT, you cannot specify an <index> in the request path.

      API name: pit

    • postFilter

      @Nullable public final Query postFilter()
      Use the post_filter parameter to filter search results. The search hits are filtered after the aggregations are calculated. A post filter has no impact on the aggregation results.

      API name: post_filter

    • preFilterShardSize

      @Nullable public final Long preFilterShardSize()
      A threshold that enforces a pre-filter roundtrip to prefilter search shards based on query rewriting if the number of shards the search request expands to exceeds the threshold. This filter roundtrip can limit the number of shards significantly if for instance a shard can not match any documents based on its rewrite method (if date filters are mandatory to match but the shard bounds and the query are disjoint). When unspecified, the pre-filter phase is executed if any of these conditions is met:
      • The request targets more than 128 shards.
      • The request targets one or more read-only index.
      • The primary sort of the query targets an indexed field.

      API name: pre_filter_shard_size

    • preference

      @Nullable public final String preference()
      The nodes and shards used for the search. By default, Elasticsearch selects from eligible nodes and shards using adaptive replica selection, accounting for allocation awareness. Valid values are:
      • _only_local to run the search only on shards on the local node.
      • _local to, if possible, run the search on shards on the local node, or if not, select shards using the default method.
      • _only_nodes:<node-id>,<node-id> to run the search on only the specified nodes IDs. If suitable shards exist on more than one selected node, use shards on those nodes using the default method. If none of the specified nodes are available, select shards from any available node using the default method.
      • _prefer_nodes:<node-id>,<node-id> to if possible, run the search on the specified nodes IDs. If not, select shards using the default method.
      • _shards:<shard>,<shard> to run the search only on the specified shards. You can combine this value with other preference values. However, the _shards value must come first. For example: _shards:2,3|_local.
      • <custom-string> (any string that does not start with _) to route searches with the same <custom-string> to the same shards in the same order.

      API name: preference

    • profile

      @Nullable public final Boolean profile()
      Set to true to return detailed timing information about the execution of individual components in a search request. NOTE: This is a debugging tool and adds significant overhead to search execution.

      API name: profile

    • q

      @Nullable public final String q()
      A query in the Lucene query string syntax. Query parameter searches do not support the full Elasticsearch Query DSL but are handy for testing.

      IMPORTANT: This parameter overrides the query parameter in the request body. If both parameters are specified, documents matching the query request body parameter are not returned.

      API name: q

    • query

      @Nullable public final Query query()
      The search definition using the Query DSL.

      API name: query

    • rank

      @Nullable public final Rank rank()
      The Reciprocal Rank Fusion (RRF) to use.

      API name: rank

    • requestCache

      @Nullable public final Boolean requestCache()
      If true, the caching of search results is enabled for requests where size is 0. It defaults to index level settings.

      API name: request_cache

    • rescore

      public final List<Rescore> rescore()
      Can be used to improve precision by reordering just the top (for example 100 - 500) documents returned by the query and post_filter phases.

      API name: rescore

    • retriever

      @Nullable public final Retriever retriever()
      A retriever is a specification to describe top documents returned from a search. A retriever replaces other elements of the search API that also return top documents such as query and knn.

      API name: retriever

    • routing

      @Nullable public final String routing()
      A custom value that is used to route operations to a specific shard.

      API name: routing

    • runtimeMappings

      public final Map<String,RuntimeField> runtimeMappings()
      One or more runtime fields in the search request. These fields take precedence over mapped fields with the same name.

      API name: runtime_mappings

    • scriptFields

      public final Map<String,ScriptField> scriptFields()
      Retrieve a script evaluation (based on different fields) for each hit.

      API name: script_fields

    • scroll

      @Nullable public final Time scroll()
      The period to retain the search context for scrolling. By default, this value cannot exceed 1d (24 hours). You can change this limit by using the search.max_keep_alive cluster-level setting.

      API name: scroll

    • searchAfter

      public final List<FieldValue> searchAfter()
      Used to retrieve the next page of hits using a set of sort values from the previous page.

      API name: search_after

    • searchType

      @Nullable public final SearchType searchType()
      Indicates how distributed term frequencies are calculated for relevance scoring.

      API name: search_type

    • seqNoPrimaryTerm

      @Nullable public final Boolean seqNoPrimaryTerm()
      If true, the request returns sequence number and primary term of the last modification of each hit.

      API name: seq_no_primary_term

    • size

      @Nullable public final Integer size()
      The number of hits to return, which must not be negative. By default, you cannot page through more than 10,000 hits using the from and size parameters. To page through more hits, use the search_after property.

      API name: size

    • slice

      @Nullable public final SlicedScroll slice()
      Split a scrolled search into multiple slices that can be consumed independently.

      API name: slice

    • sort

      public final List<SortOptions> sort()
      A comma-separated list of <field>:<direction> pairs.

      API name: sort

    • stats

      public final List<String> stats()
      The stats groups to associate with the search. Each group maintains a statistics aggregation for its associated searches. You can retrieve these stats using the indices stats API.

      API name: stats

    • storedFields

      public final List<String> storedFields()
      A comma-separated list of stored fields to return as part of a hit. If no fields are specified, no stored fields are included in the response. If this field is specified, the _source property defaults to false. You can pass _source: true to return both source fields and stored fields in the search response.

      API name: stored_fields

    • suggest

      @Nullable public final Suggester suggest()
      Defines a suggester that provides similar looking terms based on a provided text.

      API name: suggest

    • terminateAfter

      @Nullable public final Long terminateAfter()
      The maximum number of documents to collect for each shard. If a query reaches this limit, Elasticsearch terminates the query early. Elasticsearch collects documents before sorting.

      IMPORTANT: Use with caution. Elasticsearch applies this property to each shard handling the request. When possible, let Elasticsearch perform early termination automatically. Avoid specifying this property for requests that target data streams with backing indices across multiple data tiers.

      If set to 0 (default), the query does not terminate early.

      API name: terminate_after

    • timeout

      @Nullable public final String timeout()
      The period of time to wait for a response from each shard. If no response is received before the timeout expires, the request fails and returns an error. Defaults to no timeout.

      API name: timeout

    • trackScores

      @Nullable public final Boolean trackScores()
      If true, calculate and return document scores, even if the scores are not used for sorting.

      API name: track_scores

    • trackTotalHits

      @Nullable public final TrackHits trackTotalHits()
      Number of hits matching the query to count accurately. If true, the exact number of hits is returned at the cost of some performance. If false, the response does not include the total number of hits matching the query.

      API name: track_total_hits

    • version

      @Nullable public final Boolean version()
      If true, the request returns the document version as part of a hit.

      API name: version

    • serialize

      public void serialize(jakarta.json.stream.JsonGenerator generator, JsonpMapper mapper)
      Serialize this object to JSON.
      Specified by:
      serialize in interface JsonpSerializable
    • serializeInternal

      protected void serializeInternal(jakarta.json.stream.JsonGenerator generator, JsonpMapper mapper)
    • setupSearchRequestDeserializer

      protected static void setupSearchRequestDeserializer(ObjectDeserializer<SearchRequest.Builder> op)
    • createSearchEndpoint

      public static <TDocument> Endpoint<SearchRequest,SearchResponse<TDocument>,ErrorResponse> createSearchEndpoint(JsonpDeserializer<TDocument> tDocumentDeserializer)
      Create an "search" endpoint.