0
# Search APIs
1
2
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.
3
4
## Capabilities
5
6
### Core Search Operations
7
8
The primary search interfaces for executing queries against OpenSearch indices.
9
10
```java { .api }
11
/**
12
* Main search request class for executing queries against indices
13
*/
14
class SearchRequest extends ActionRequest {
15
/**
16
* Create search request for specified indices
17
* @param indices Index names to search (empty for all indices)
18
*/
19
SearchRequest(String... indices);
20
21
/**
22
* Set search source configuration
23
* @param sourceBuilder Search source builder with query, aggregations, etc.
24
*/
25
SearchRequest source(SearchSourceBuilder sourceBuilder);
26
27
/**
28
* Set routing for request
29
* @param routing Routing value for shard selection
30
*/
31
SearchRequest routing(String routing);
32
33
/**
34
* Set request timeout
35
* @param timeout Timeout value (e.g., "1m", "30s")
36
*/
37
SearchRequest timeout(String timeout);
38
39
/**
40
* Set search type
41
* @param searchType Search execution type
42
*/
43
SearchRequest searchType(SearchType searchType);
44
45
/**
46
* Set scroll timeout for scrollable searches
47
* @param scroll Scroll timeout (e.g., "1m")
48
*/
49
SearchRequest scroll(String scroll);
50
51
/**
52
* Get configured indices
53
*/
54
String[] indices();
55
56
/**
57
* Get search source builder
58
*/
59
SearchSourceBuilder source();
60
}
61
62
/**
63
* Search operation response containing results and metadata
64
*/
65
class SearchResponse extends ActionResponse {
66
/**
67
* Get search hits container
68
*/
69
SearchHits getHits();
70
71
/**
72
* Get aggregation results
73
*/
74
Aggregations getAggregations();
75
76
/**
77
* Get scroll ID for pagination
78
*/
79
String getScrollId();
80
81
/**
82
* Check if request timed out
83
*/
84
boolean isTimedOut();
85
86
/**
87
* Get search execution time
88
*/
89
TimeValue getTook();
90
91
/**
92
* Get number of shards searched
93
*/
94
int getTotalShards();
95
96
/**
97
* Get number of successful shard searches
98
*/
99
int getSuccessfulShards();
100
101
/**
102
* Get search failures
103
*/
104
ShardSearchFailure[] getShardFailures();
105
}
106
```
107
108
### Search Source Builder
109
110
Fluent API for constructing complex search queries with filters, aggregations, and result formatting.
111
112
```java { .api }
113
/**
114
* Builder for constructing search query DSL with fluent interface
115
*/
116
class SearchSourceBuilder implements Streamable {
117
/**
118
* Create empty search source builder
119
*/
120
SearchSourceBuilder();
121
122
/**
123
* Set main query
124
* @param query Query builder for search criteria
125
*/
126
SearchSourceBuilder query(QueryBuilder query);
127
128
/**
129
* Add aggregation to search
130
* @param aggregation Aggregation builder for statistical analysis
131
*/
132
SearchSourceBuilder aggregation(AggregationBuilder aggregation);
133
134
/**
135
* Set number of results to return
136
* @param size Maximum number of hits (default: 10)
137
*/
138
SearchSourceBuilder size(int size);
139
140
/**
141
* Set starting offset for pagination
142
* @param from Starting index for results (default: 0)
143
*/
144
SearchSourceBuilder from(int from);
145
146
/**
147
* Add sort criteria
148
* @param sort Sort builder for result ordering
149
*/
150
SearchSourceBuilder sort(SortBuilder<?> sort);
151
152
/**
153
* Set timeout for search execution
154
* @param timeout Execution timeout
155
*/
156
SearchSourceBuilder timeout(TimeValue timeout);
157
158
/**
159
* Configure source field filtering
160
* @param include Fields to include in results
161
* @param exclude Fields to exclude from results
162
*/
163
SearchSourceBuilder fetchSource(String[] include, String[] exclude);
164
165
/**
166
* Add highlighting configuration
167
* @param highlight Highlight builder for result highlighting
168
*/
169
SearchSourceBuilder highlighter(HighlightBuilder highlight);
170
171
/**
172
* Add post-filter query
173
* @param postFilter Filter applied after aggregations
174
*/
175
SearchSourceBuilder postFilter(QueryBuilder postFilter);
176
177
/**
178
* Set minimum score threshold
179
* @param minScore Minimum score for returned documents
180
*/
181
SearchSourceBuilder minScore(float minScore);
182
183
/**
184
* Get configured query
185
*/
186
QueryBuilder query();
187
188
/**
189
* Get configured aggregations
190
*/
191
List<AggregationBuilder> aggregations();
192
}
193
```
194
195
### Query Builders
196
197
Comprehensive Query DSL implementation for building search criteria.
198
199
```java { .api }
200
/**
201
* Base interface for all query builders in the Query DSL
202
*/
203
interface QueryBuilder extends NamedWriteable, Rewriteable<QueryBuilder> {
204
/**
205
* Get query name for identification
206
*/
207
String getWriteableName();
208
209
/**
210
* Rewrite query for optimization
211
*/
212
QueryBuilder rewrite(QueryRewriteContext context) throws IOException;
213
}
214
215
/**
216
* Boolean query builder for combining multiple queries with logical operators
217
*/
218
class BoolQueryBuilder implements QueryBuilder {
219
/**
220
* Create boolean query builder
221
*/
222
BoolQueryBuilder();
223
224
/**
225
* Add query that must match (AND logic)
226
* @param query Query that must be satisfied
227
*/
228
BoolQueryBuilder must(QueryBuilder query);
229
230
/**
231
* Add query that must not match (NOT logic)
232
* @param query Query that must not be satisfied
233
*/
234
BoolQueryBuilder mustNot(QueryBuilder query);
235
236
/**
237
* Add query that should match (OR logic, affects scoring)
238
* @param query Query that should be satisfied
239
*/
240
BoolQueryBuilder should(QueryBuilder query);
241
242
/**
243
* Add filter query (no scoring)
244
* @param query Filter query for exact matching
245
*/
246
BoolQueryBuilder filter(QueryBuilder query);
247
248
/**
249
* Set minimum should match
250
* @param minimumShouldMatch Minimum number of should clauses that must match
251
*/
252
BoolQueryBuilder minimumShouldMatch(String minimumShouldMatch);
253
254
/**
255
* Set query boost factor
256
* @param boost Boost multiplier for relevance scoring
257
*/
258
BoolQueryBuilder boost(float boost);
259
}
260
261
/**
262
* Match query builder for full-text search with analysis
263
*/
264
class MatchQueryBuilder implements QueryBuilder {
265
/**
266
* Create match query for field and value
267
* @param name Field name to search
268
* @param text Search text to match
269
*/
270
MatchQueryBuilder(String name, Object text);
271
272
/**
273
* Set operator for multiple terms
274
* @param operator AND or OR operator for term combination
275
*/
276
MatchQueryBuilder operator(Operator operator);
277
278
/**
279
* Set analyzer for query text
280
* @param analyzer Analyzer name for text processing
281
*/
282
MatchQueryBuilder analyzer(String analyzer);
283
284
/**
285
* Set fuzziness for approximate matching
286
* @param fuzziness Fuzziness configuration (AUTO, 0, 1, 2)
287
*/
288
MatchQueryBuilder fuzziness(Fuzziness fuzziness);
289
290
/**
291
* Set minimum should match
292
* @param minimumShouldMatch Minimum percentage or count of terms that should match
293
*/
294
MatchQueryBuilder minimumShouldMatch(String minimumShouldMatch);
295
}
296
297
/**
298
* Term query builder for exact term matching without analysis
299
*/
300
class TermQueryBuilder implements QueryBuilder {
301
/**
302
* Create term query for exact field value
303
* @param name Field name
304
* @param value Exact term value to match
305
*/
306
TermQueryBuilder(String name, Object value);
307
308
/**
309
* Set boost factor
310
* @param boost Relevance score boost multiplier
311
*/
312
TermQueryBuilder boost(float boost);
313
}
314
315
/**
316
* Range query builder for numeric and date range matching
317
*/
318
class RangeQueryBuilder implements QueryBuilder {
319
/**
320
* Create range query for field
321
* @param fieldName Field name for range query
322
*/
323
RangeQueryBuilder(String fieldName);
324
325
/**
326
* Set greater than or equal constraint
327
* @param gte Minimum value (inclusive)
328
*/
329
RangeQueryBuilder gte(Object gte);
330
331
/**
332
* Set greater than constraint
333
* @param gt Minimum value (exclusive)
334
*/
335
RangeQueryBuilder gt(Object gt);
336
337
/**
338
* Set less than or equal constraint
339
* @param lte Maximum value (inclusive)
340
*/
341
RangeQueryBuilder lte(Object lte);
342
343
/**
344
* Set less than constraint
345
* @param lt Maximum value (exclusive)
346
*/
347
RangeQueryBuilder lt(Object lt);
348
349
/**
350
* Set format for date parsing
351
* @param format Date format string
352
*/
353
RangeQueryBuilder format(String format);
354
}
355
```
356
357
### Query Builders Factory
358
359
Static factory methods for creating query builders.
360
361
```java { .api }
362
/**
363
* Static factory class for creating query builders
364
*/
365
class QueryBuilders {
366
/**
367
* Create match-all query (matches every document)
368
*/
369
static MatchAllQueryBuilder matchAllQuery();
370
371
/**
372
* Create match query for full-text search
373
* @param name Field name
374
* @param text Search text
375
*/
376
static MatchQueryBuilder matchQuery(String name, Object text);
377
378
/**
379
* Create multi-match query across multiple fields
380
* @param text Search text
381
* @param fieldNames Fields to search
382
*/
383
static MultiMatchQueryBuilder multiMatchQuery(Object text, String... fieldNames);
384
385
/**
386
* Create term query for exact matching
387
* @param name Field name
388
* @param value Exact value to match
389
*/
390
static TermQueryBuilder termQuery(String name, Object value);
391
392
/**
393
* Create terms query for matching multiple exact values
394
* @param name Field name
395
* @param values Array of exact values to match
396
*/
397
static TermsQueryBuilder termsQuery(String name, Object... values);
398
399
/**
400
* Create range query for numeric/date ranges
401
* @param name Field name
402
*/
403
static RangeQueryBuilder rangeQuery(String name);
404
405
/**
406
* Create boolean query for combining multiple queries
407
*/
408
static BoolQueryBuilder boolQuery();
409
410
/**
411
* Create wildcard query for pattern matching
412
* @param name Field name
413
* @param query Wildcard pattern (* and ?)
414
*/
415
static WildcardQueryBuilder wildcardQuery(String name, String query);
416
417
/**
418
* Create fuzzy query for approximate matching
419
* @param name Field name
420
* @param value Search value
421
*/
422
static FuzzyQueryBuilder fuzzyQuery(String name, Object value);
423
424
/**
425
* Create nested query for nested object fields
426
* @param path Nested object path
427
* @param query Query to apply to nested objects
428
* @param scoreMode Score calculation mode
429
*/
430
static NestedQueryBuilder nestedQuery(String path, QueryBuilder query, ScoreMode scoreMode);
431
}
432
```
433
434
### Aggregation Framework
435
436
Statistical and analytical computations over search results.
437
438
```java { .api }
439
/**
440
* Base interface for all aggregation builders
441
*/
442
interface AggregationBuilder extends NamedWriteable {
443
/**
444
* Get aggregation name
445
*/
446
String getName();
447
448
/**
449
* Get aggregation type
450
*/
451
String getType();
452
453
/**
454
* Add sub-aggregation
455
* @param aggregation Child aggregation builder
456
*/
457
AggregationBuilder subAggregation(AggregationBuilder aggregation);
458
}
459
460
/**
461
* Collection of aggregation results from search response
462
*/
463
class Aggregations implements Iterable<Aggregation> {
464
/**
465
* Get aggregation by name
466
* @param name Aggregation name
467
*/
468
Aggregation get(String name);
469
470
/**
471
* Get all aggregations as map
472
*/
473
Map<String, Aggregation> asMap();
474
475
/**
476
* Get list of all aggregations
477
*/
478
List<Aggregation> asList();
479
}
480
481
/**
482
* Terms aggregation builder for grouping by field values
483
*/
484
class TermsAggregationBuilder implements AggregationBuilder {
485
/**
486
* Create terms aggregation
487
* @param name Aggregation name
488
*/
489
TermsAggregationBuilder(String name);
490
491
/**
492
* Set field to group by
493
* @param field Field name for grouping
494
*/
495
TermsAggregationBuilder field(String field);
496
497
/**
498
* Set number of top terms to return
499
* @param size Maximum number of buckets
500
*/
501
TermsAggregationBuilder size(int size);
502
503
/**
504
* Set ordering criteria
505
* @param order Sort order for buckets
506
*/
507
TermsAggregationBuilder order(BucketOrder order);
508
509
/**
510
* Set minimum document count for inclusion
511
* @param minDocCount Minimum documents required per bucket
512
*/
513
TermsAggregationBuilder minDocCount(long minDocCount);
514
}
515
516
/**
517
* Date histogram aggregation builder for time-based grouping
518
*/
519
class DateHistogramAggregationBuilder implements AggregationBuilder {
520
/**
521
* Create date histogram aggregation
522
* @param name Aggregation name
523
*/
524
DateHistogramAggregationBuilder(String name);
525
526
/**
527
* Set field for date grouping
528
* @param field Date field name
529
*/
530
DateHistogramAggregationBuilder field(String field);
531
532
/**
533
* Set calendar interval
534
* @param interval Calendar interval (month, week, day, hour, etc.)
535
*/
536
DateHistogramAggregationBuilder calendarInterval(DateHistogramInterval interval);
537
538
/**
539
* Set fixed interval
540
* @param interval Fixed time interval (30s, 1m, 1h, etc.)
541
*/
542
DateHistogramAggregationBuilder fixedInterval(DateHistogramInterval interval);
543
544
/**
545
* Set time zone
546
* @param timeZone Time zone for date calculations
547
*/
548
DateHistogramAggregationBuilder timeZone(ZoneId timeZone);
549
}
550
```
551
552
### Multi-Search Operations
553
554
Batch multiple search requests for efficient execution.
555
556
```java { .api }
557
/**
558
* Multiple search requests executed in a single batch operation
559
*/
560
class MultiSearchRequest extends ActionRequest {
561
/**
562
* Create multi-search request
563
*/
564
MultiSearchRequest();
565
566
/**
567
* Add search request to batch
568
* @param searchRequest Individual search request
569
*/
570
MultiSearchRequest add(SearchRequest searchRequest);
571
572
/**
573
* Add search request with request item
574
* @param searchRequestItem Search request with metadata
575
*/
576
MultiSearchRequest add(SearchRequestItem searchRequestItem);
577
578
/**
579
* Get number of search requests
580
*/
581
int numberOfSearchRequests();
582
583
/**
584
* Get search requests list
585
*/
586
List<SearchRequest> requests();
587
}
588
589
/**
590
* Response for multi-search operations containing individual responses
591
*/
592
class MultiSearchResponse extends ActionResponse {
593
/**
594
* Get array of individual search responses
595
*/
596
MultiSearchResponse.Item[] getResponses();
597
598
/**
599
* Individual multi-search response item
600
*/
601
static class Item {
602
/**
603
* Check if response contains failure
604
*/
605
boolean isFailure();
606
607
/**
608
* Get search response (null if failed)
609
*/
610
SearchResponse getResponse();
611
612
/**
613
* Get failure exception (null if successful)
614
*/
615
Exception getFailure();
616
}
617
}
618
```
619
620
### Search Scrolling and Point-in-Time
621
622
APIs for handling large result sets and consistent snapshots.
623
624
```java { .api }
625
/**
626
* Scroll search request for paginating through large result sets
627
*/
628
class SearchScrollRequest extends ActionRequest {
629
/**
630
* Create scroll request with scroll ID
631
* @param scrollId Scroll context ID from previous search
632
*/
633
SearchScrollRequest(String scrollId);
634
635
/**
636
* Set scroll timeout
637
* @param scroll Scroll context timeout (e.g., "1m")
638
*/
639
SearchScrollRequest scroll(String scroll);
640
641
/**
642
* Get scroll ID
643
*/
644
String scrollId();
645
}
646
647
/**
648
* Clear scroll request to release scroll context resources
649
*/
650
class ClearScrollRequest extends ActionRequest {
651
/**
652
* Create clear scroll request
653
*/
654
ClearScrollRequest();
655
656
/**
657
* Add scroll ID to clear
658
* @param scrollId Scroll context ID to release
659
*/
660
void addScrollId(String scrollId);
661
662
/**
663
* Set scroll IDs to clear
664
* @param scrollIds List of scroll context IDs
665
*/
666
void setScrollIds(List<String> scrollIds);
667
}
668
669
/**
670
* Point-in-time search request for consistent snapshots across searches
671
*/
672
class CreatePitRequest extends ActionRequest {
673
/**
674
* Create PIT request for indices
675
* @param indices Index names for point-in-time snapshot
676
*/
677
CreatePitRequest(String... indices);
678
679
/**
680
* Set PIT keepalive time
681
* @param keepAlive How long to keep PIT context active
682
*/
683
CreatePitRequest keepAlive(TimeValue keepAlive);
684
685
/**
686
* Set routing for PIT creation
687
* @param routing Routing value for shard selection
688
*/
689
CreatePitRequest routing(String routing);
690
}
691
692
/**
693
* Point-in-time creation response containing PIT ID
694
*/
695
class CreatePitResponse extends ActionResponse {
696
/**
697
* Get point-in-time ID for subsequent searches
698
*/
699
String getId();
700
701
/**
702
* Get creation time
703
*/
704
long getCreationTime();
705
}
706
707
/**
708
* Delete point-in-time request to release PIT resources
709
*/
710
class DeletePitRequest extends ActionRequest {
711
/**
712
* Create delete PIT request
713
*/
714
DeletePitRequest();
715
716
/**
717
* Add PIT ID to delete
718
* @param pitId Point-in-time ID to release
719
*/
720
void addPitId(String pitId);
721
722
/**
723
* Set PIT IDs to delete
724
* @param pitIds List of PIT IDs to release
725
*/
726
void setPitIds(List<String> pitIds);
727
}
728
```
729
730
### Point-in-Time Builder
731
732
Configuration for point-in-time search context.
733
734
```java { .api }
735
/**
736
* Builder for point-in-time search configuration
737
*/
738
class PointInTimeBuilder implements Streamable {
739
/**
740
* Create PIT builder with ID
741
* @param id Point-in-time ID from CreatePitResponse
742
*/
743
PointInTimeBuilder(String id);
744
745
/**
746
* Set keepalive time for PIT context
747
* @param keepAlive Duration to keep PIT active
748
*/
749
PointInTimeBuilder setKeepAlive(TimeValue keepAlive);
750
751
/**
752
* Get PIT ID
753
*/
754
String getId();
755
756
/**
757
* Get keepalive time
758
*/
759
TimeValue getKeepAlive();
760
}
761
```
762
763
## Usage Examples
764
765
### Basic Search Operations
766
767
```java
768
import org.opensearch.action.search.SearchRequest;
769
import org.opensearch.action.search.SearchResponse;
770
import org.opensearch.search.builder.SearchSourceBuilder;
771
import org.opensearch.index.query.QueryBuilders;
772
import org.opensearch.search.SearchHit;
773
774
// Simple match query
775
SearchRequest searchRequest = new SearchRequest("products");
776
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
777
searchSourceBuilder.query(QueryBuilders.matchQuery("name", "laptop"));
778
searchSourceBuilder.size(10);
779
searchRequest.source(searchSourceBuilder);
780
781
SearchResponse searchResponse = client.search(searchRequest);
782
System.out.println("Total hits: " + searchResponse.getHits().getTotalHits().value);
783
784
for (SearchHit hit : searchResponse.getHits()) {
785
System.out.println("Document ID: " + hit.getId());
786
System.out.println("Source: " + hit.getSourceAsString());
787
System.out.println("Score: " + hit.getScore());
788
}
789
```
790
791
### Complex Boolean Query
792
793
```java
794
import org.opensearch.index.query.BoolQueryBuilder;
795
import org.opensearch.index.query.RangeQueryBuilder;
796
797
// Complex boolean query with multiple criteria
798
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery()
799
.must(QueryBuilders.matchQuery("category", "electronics"))
800
.must(QueryBuilders.rangeQuery("price").gte(100).lte(1000))
801
.should(QueryBuilders.termQuery("brand", "apple"))
802
.should(QueryBuilders.termQuery("brand", "samsung"))
803
.mustNot(QueryBuilders.termQuery("status", "discontinued"))
804
.minimumShouldMatch("1");
805
806
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
807
.query(boolQuery)
808
.size(20)
809
.from(0);
810
811
SearchRequest searchRequest = new SearchRequest("products");
812
searchRequest.source(searchSourceBuilder);
813
```
814
815
### Aggregations
816
817
```java
818
import org.opensearch.search.aggregations.AggregationBuilders;
819
import org.opensearch.search.aggregations.bucket.terms.Terms;
820
import org.opensearch.search.aggregations.metrics.Avg;
821
822
// Terms aggregation with sub-aggregation
823
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
824
.query(QueryBuilders.matchAllQuery())
825
.aggregation(
826
AggregationBuilders.terms("categories")
827
.field("category.keyword")
828
.size(10)
829
.subAggregation(
830
AggregationBuilders.avg("avg_price")
831
.field("price")
832
)
833
)
834
.size(0); // Don't return documents, only aggregations
835
836
SearchRequest searchRequest = new SearchRequest("products");
837
searchRequest.source(searchSourceBuilder);
838
SearchResponse searchResponse = client.search(searchRequest);
839
840
Terms categories = searchResponse.getAggregations().get("categories");
841
for (Terms.Bucket bucket : categories.getBuckets()) {
842
System.out.println("Category: " + bucket.getKeyAsString());
843
System.out.println("Doc count: " + bucket.getDocCount());
844
845
Avg avgPrice = bucket.getAggregations().get("avg_price");
846
System.out.println("Average price: " + avgPrice.getValue());
847
}
848
```
849
850
### Scrolling for Large Results
851
852
```java
853
import org.opensearch.action.search.SearchScrollRequest;
854
import org.opensearch.common.unit.TimeValue;
855
856
// Initial scroll search
857
SearchRequest searchRequest = new SearchRequest("large_index");
858
searchRequest.scroll(TimeValue.timeValueMinutes(1L));
859
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
860
.query(QueryBuilders.matchAllQuery())
861
.size(1000); // Large batch size
862
searchRequest.source(searchSourceBuilder);
863
864
SearchResponse searchResponse = client.search(searchRequest);
865
String scrollId = searchResponse.getScrollId();
866
867
// Continue scrolling
868
while (searchResponse.getHits().getHits().length > 0) {
869
// Process current batch
870
for (SearchHit hit : searchResponse.getHits()) {
871
// Process document
872
System.out.println(hit.getSourceAsString());
873
}
874
875
// Get next batch
876
SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
877
scrollRequest.scroll(TimeValue.timeValueMinutes(1L));
878
searchResponse = client.scroll(scrollRequest);
879
scrollId = searchResponse.getScrollId();
880
}
881
882
// Clean up scroll context
883
ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
884
clearScrollRequest.addScrollId(scrollId);
885
client.clearScroll(clearScrollRequest);
886
```
887
888
### Point-in-Time Search
889
890
```java
891
import org.opensearch.action.search.CreatePitRequest;
892
import org.opensearch.action.search.CreatePitResponse;
893
import org.opensearch.search.builder.PointInTimeBuilder;
894
895
// Create point-in-time
896
CreatePitRequest createPitRequest = new CreatePitRequest("products");
897
createPitRequest.keepAlive(TimeValue.timeValueMinutes(5));
898
CreatePitResponse createPitResponse = client.createPit(createPitRequest);
899
String pitId = createPitResponse.getId();
900
901
// Search with PIT for consistency
902
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
903
.query(QueryBuilders.matchAllQuery())
904
.pointInTimeBuilder(new PointInTimeBuilder(pitId))
905
.size(100)
906
.sort("_shard_doc");
907
908
SearchRequest searchRequest = new SearchRequest();
909
searchRequest.source(searchSourceBuilder);
910
SearchResponse searchResponse = client.search(searchRequest);
911
912
// Clean up PIT
913
DeletePitRequest deletePitRequest = new DeletePitRequest();
914
deletePitRequest.addPitId(pitId);
915
client.deletePit(deletePitRequest);
916
```
917
918
## Types
919
920
```java { .api }
921
/**
922
* Search hits container with total count and individual hits
923
*/
924
class SearchHits implements Streamable, Iterable<SearchHit> {
925
/**
926
* Get total hits information
927
*/
928
TotalHits getTotalHits();
929
930
/**
931
* Get maximum score across all hits
932
*/
933
float getMaxScore();
934
935
/**
936
* Get array of search hits
937
*/
938
SearchHit[] getHits();
939
940
/**
941
* Get search hits as list
942
*/
943
List<SearchHit> asList();
944
}
945
946
/**
947
* Individual search result hit
948
*/
949
class SearchHit implements Streamable {
950
/**
951
* Get document ID
952
*/
953
String getId();
954
955
/**
956
* Get document index
957
*/
958
String getIndex();
959
960
/**
961
* Get relevance score
962
*/
963
float getScore();
964
965
/**
966
* Get document source as string
967
*/
968
String getSourceAsString();
969
970
/**
971
* Get document source as map
972
*/
973
Map<String, Object> getSourceAsMap();
974
975
/**
976
* Get highlighted fragments
977
*/
978
Map<String, HighlightField> getHighlightFields();
979
}
980
981
/**
982
* Search execution types
983
*/
984
enum SearchType {
985
/**
986
* Default search type with query then fetch phases
987
*/
988
QUERY_THEN_FETCH,
989
990
/**
991
* Distributed frequency search for accurate scoring
992
*/
993
DFS_QUERY_THEN_FETCH
994
}
995
996
/**
997
* Score calculation modes for nested queries
998
*/
999
enum ScoreMode {
1000
/**
1001
* Use average score of matching nested documents
1002
*/
1003
Avg,
1004
1005
/**
1006
* Use maximum score of matching nested documents
1007
*/
1008
Max,
1009
1010
/**
1011
* Use minimum score of matching nested documents
1012
*/
1013
Min,
1014
1015
/**
1016
* Use sum of scores from matching nested documents
1017
*/
1018
Sum,
1019
1020
/**
1021
* No scoring (filter context)
1022
*/
1023
None
1024
}
1025
```