Professional Documents
Culture Documents
API Elastic Queries
API Elastic Queries
(/downloads)
(/contact?storm=glo
header-
en)
Docs (/guide)
Java REST Client [7.0] (index.html) » Java High Level REST Client
On this page
(java-rest-high.html) » Search APIs (_search_apis.html) » Search
Search Request
API
Synchronous Execution
« Search APIs (_search_apis.html) Search Scroll API » (java-rest-high-
Asynchronous Execution
search-scroll.html)
SearchResponse
Search API
Getting Started
Search Request Videos
The SearchRequest is used for any operation that has to do
with searching documents, aggregations, suggestions and also Starting
o�ers ways of requesting highlighting on the resulting Elasticsearch
documents. Introduction to
In its most basic form, we can add a query to the request: Kibana
Logstash
SearchRequest searchRequest = new SearchRequest
Starter Guide
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilde
searchSourceBuilder.query(QueryBuilders.matchAllQuery
searchRequest.source(searchSourceBuilder);
1
7.0 (current)
Creates the SeachRequest . Without arguments this runs
against all indices. Overview (java-rest-
overview.html)
Most search parameters are added to the
Java Low Level REST Clien
SearchSourceBuilder . It o�ers setters for everything that
(java-rest-low.html
goes into the search request body.
Java High Level REST
Add a match_all query to the SearchSourceBuilder . Client (java-rest-high.htm
Getting started
Add the SearchSourceBuilder to the SeachRequest . high-getting-started.html
Document APIs
Optional arguments high-supported-apis.html
Let’s �rst look at some of the optional arguments of a Search APIs
SearchRequest : (_search_apis.html
Search API (
SearchRequest searchRequest = new SearchRequest
high-search.html
Multi-Search API
Set a routing parameter rest-high-multi-
search.html
searchRequest.indicesOptions(IndicesOptions.lenientExpandOpen
Search Template API
(java-rest-high-search-
template.html
Setting IndicesOptions controls how unavailable indices
Multi-Search-Template
are resolved and how wildcard expressions are expanded
API (java-rest-high-mult
search-template.html
searchRequest.preference("_local");
Field Capabilities API
(java-rest-high-�eld-
caps.html)
2
Ranking Evaluation API
Use the preference parameter e.g. to execute the search to
(java-rest-high-rank-
Tasks APIs
Create a SearchSourceBuilder with default options. (_tasks_apis.html
Script APIs
Set the query. Can be any type of QueryBuilder (_script_apis.html
Licensing APIs
Set the from option that determines the result index to (_licensing_apis.html
start searching from. Defaults to 0.
Machine Learning APIs
(_machine_learning_apis.h
Set the size option that determines the number of search
Migration APIs
hits to return. Defaults to 10.
(_migration_apis.html
Set an optional timeout that controls how long the search Rollup APIs
Security APIs
Graph APIs
3
(_graph_apis.html
SearchRequest searchRequest = new SearchRequest
searchRequest.indices("posts"); CCR APIs (_ccr_apis.html
searchRequest.source(sourceBuilder); Index Lifecycle
Management APIs
(_index_lifecycle_managem
matchQueryBuilder.fuzziness(Fuzziness.AUTO);
matchQueryBuilder.prefixLength(3);
matchQueryBuilder.maxExpansions(10);
4
QueryBuilders utility class. This class provides helper
methods that can be used to create QueryBuilder objects
using a �uent programming style:
searchSourceBuilder.query(matchQueryBuilder);
Specifying Sorting
The SearchSourceBuilder allows to add one or more
SortBuilder instances. There are four special
implementations (Field-, Score-, GeoDistance- and
ScriptSortBuilder).
sourceBuilder.sort(new ScoreSortBuilder().order
sourceBuilder.sort(new FieldSortBuilder("_id").
Source �ltering
By default, search requests return the contents of the
5
document _source but like in the Rest API you can overwrite
this behavior. For example, you can turn o� _source retrieval
completely:
sourceBuilder.fetchSource(false);
Requesting Highlighting
Highlighting search results can be achieved by setting a
HighlightBuilder on the SearchSourceBuilder . Di�erent
highlighting behaviour can be de�ned for each �elds by adding
one or more HighlightBuilder.Field instances to a
HighlightBuilder .
6
Set the �eld highlighter type
Requesting Aggregations
Aggregations can be added to the search by �rst creating the
appropriate AggregationBuilder and then setting it on the
SearchSourceBuilder . In the following example we create a
terms aggregation on company names with a sub-aggregation
on the average age of employees in the company:
7
Requesting Suggestions
To add Suggestions to the search request, use one of the
SuggestionBuilder implementations that are easily
accessible from the SuggestBuilders factory class.
Suggestion builders need to be added to the top level
SuggestBuilder , which itself can be set on the
SearchSourceBuilder .
8
SearchResponse will contain the pro�ling results (java-rest-
high-search.html#java-rest-high-search-response-pro�le).
Synchronous Execution
When executing a SearchRequest in the following manner, the
client waits for the SearchResponse to be returned before
continuing with code execution:
In cases where the server returns a 4xx or 5xx error code, the
high-level client tries to parse the response body error details
instead and then throws a generic ElasticsearchException
and adds the original ResponseException as a suppressed
exception to it.
Asynchronous Execution
Executing a SearchRequest can also be done in an
asynchronous fashion so that the client can return directly.
Users need to specify how the response or potential failures
will be handled by passing the request and a listener to the
asynchronous search method:
client.searchAsync(searchRequest, RequestOptions
9
immediately. Once it is completed the ActionListener is
called back using the onResponse method if the execution
successfully completed or using the onFailure method if it
failed. Failure scenarios and expected exceptions are the same
as in the synchronous execution case.
@Override
public void onFailure(Exception e) {
}
};
SearchResponse
The SearchResponse that is returned by executing the search
provides details about the search execution itself as well as
access to the documents returned. First, there is useful
information about the request execution itself, like the HTTP
status code, execution time or whether the request terminated
early or timed out:
10
RestStatus status = searchResponse.status();
TimeValue took = searchResponse.getTook();
Boolean terminatedEarly = searchResponse.isTerminatedEarly
boolean timedOut = searchResponse.isTimedOut();
Retrieving SearchHits
To get access to the returned documents, we need to �rst get
the SearchHits contained in the response:
11
that can be iterated over:
Retrieving Highlighting
If requested (java-rest-high-search.html#java-rest-high-search-
request-highlighting), highlighted text fragments can be
retrieved from each SearchHit in the result. The hit object
o�ers access to a map of �eld names to HighlightField
instances, each of which contains one or many highlighted text
fragments:
12
SearchHits hits = searchResponse.getHits();
for (SearchHit hit : hits.getHits()) {
Map<String, HighlightField> highlightFields
HighlightField highlight = highlightFields.
Text[] fragments = highlight.fragments();
String fragmentString = fragments[0].string
}
13
Retrieving Aggregations
Aggregations can be retrieved from the SearchResponse by
�rst getting the root of the aggregation tree, the
Aggregations object, and then getting the aggregation by
name.
14
There are also getters that return all top level aggregations as
a list:
And last but not least you can iterate over all aggregations and
then e.g. decide how to further process them based on their
type:
Retrieving Suggestions
To get back the suggestions from a SearchResponse , use the
Suggest object as an entry point and then retrieve the nested
suggestion objects:
15
Suggestions can be retrieved by name. You need to assign
them to the correct type of Suggestion class (here
TermSuggestion ), otherwise a ClassCastException is
thrown
Here is a sample code that shows how to iterate over all the
pro�ling results of every shard:
16
Retrieve the key that identi�es which shard the
ProfileShardResult belongs to
List<QueryProfileShardResult> queryProfileShardResults
profileShardResult.getQueryProfileResults
for (QueryProfileShardResult queryProfileResult
17
Retrieve the pro�le results for the sub-queries (if any)
18
AggregationProfileShardResult aggsProfileResults
profileShardResult.getAggregationProfileResults
for (ProfileResult profileResult : aggsProfileResults
String aggName = profileResult.getQueryName
long aggTimeInMillis = profileResult.getTime
List<ProfileResult> profiledChildren = profileResult
}
19
PRODUCTS > SOLUTIONS > RESOURCES ABOUT > (
(/PRODUCTS) (/SOLUTIONS) Blog (/blog) Careers/Jobs (
Elasticsearch (/products Logging (/solutions/logging)
Cloud Status (https://cloud- /careers)
/elasticsearch) Metrics (/solutions/metrics)
status.elastic.co) Our Source Code
Kibana (/products/kibana) Site Search (/solutions/site-
Community (/community) /our-source-code
Beats (/products/beats) search)
Customers & Use Cases Teams (/about/teams
Logstash (/products Security Analytics
(/use-cases) Board of Directors
/logstash) (/solutions/security-
Documentation (/guide) /teams/board
Stack Features (formerly analytics)
Elastic{ON} Events Leadership (/about/teams
X-Pack) (/products/stack) APM (/solutions/apm)
(/elasticon) /leadership)
Security (/products/stack App Search (/solutions/app-
Forums Contact (/contact
/security) search)
(https://discuss.elastic.co/) Our Story (/about/history-
Alerting (/products/stack Google Site Search
Meetups (/community of-elasticsearch
/alerting) Alternative (/google-site-
/meetups) Why Open Source
Canvas (/products/stack search-alternative)
Subscriptions /why-open-source
/canvas)
ELASTIC CLOUD > (/subscriptions) Distributed by Intention
Monitoring (/products/stack (/CLOUD) Support Portal (/about/distributed
/monitoring) Elasticsearch Service (/cloud
(https://support.elastic.co) Partners (/about/partners
Graph (/products/stack /elasticsearch-service)
Videos & Webinars (/videos) Media (/about/press
/graph) AWS Elasticsearch Service
Training (/training) Investor Relations
Reporting (/products/stack Comparison (/aws-
(https://ir.elastic.co
/reporting) elasticsearch-service)
Elastic Store
Machine Learning Elastic App Search Service
(https://www.elastic.shop
(/products/stack/machine- (/cloud/app-search-service)
()
learning) Elastic Site Search Service
(/products/stack
/elasticsearch-sql)
Elasticsearch-Hadoop
(/products/hadoop)
(/products/ece)
()
20
FOLLOW US
(/)
21