Update Java documentation for 5.0

Some of the methods have been removed or deprecated.

Also related to #21825.
This commit is contained in:
David Pilato 2016-11-28 17:33:40 +01:00
parent 69f35aa07f
commit f8cf9f790b
33 changed files with 189 additions and 199 deletions

View File

@ -16,7 +16,7 @@ AggregationBuilder aggregation =
AggregationBuilders AggregationBuilders
.dateHistogram("agg") .dateHistogram("agg")
.field("dateOfBirth") .field("dateOfBirth")
.interval(DateHistogramInterval.YEAR); .dateHistogramInterval(DateHistogramInterval.YEAR);
-------------------------------------------------- --------------------------------------------------
Or if you want to set an interval of 10 days: Or if you want to set an interval of 10 days:
@ -27,7 +27,7 @@ AggregationBuilder aggregation =
AggregationBuilders AggregationBuilders
.dateHistogram("agg") .dateHistogram("agg")
.field("dateOfBirth") .field("dateOfBirth")
.interval(DateHistogramInterval.days(10)); .dateHistogramInterval(DateHistogramInterval.days(10));
-------------------------------------------------- --------------------------------------------------

View File

@ -14,8 +14,9 @@ Here is an example on how to create the aggregation request:
-------------------------------------------------- --------------------------------------------------
AggregationBuilder aggregation = AggregationBuilder aggregation =
AggregationBuilders AggregationBuilders
.filters("agg", new KeyedFilter("men", QueryBuilders.termQuery("gender", "male")), .filters("agg",
new KeyedFilter("women", QueryBuilders.termQuery("gender", "female"))); new FiltersAggregator.KeyedFilter("men", QueryBuilders.termQuery("gender", "male")),
new FiltersAggregator.KeyedFilter("women", QueryBuilders.termQuery("gender", "female")));
-------------------------------------------------- --------------------------------------------------

View File

@ -36,7 +36,7 @@ Histogram agg = sr.getAggregations().get("agg");
// For each entry // For each entry
for (Histogram.Bucket entry : agg.getBuckets()) { for (Histogram.Bucket entry : agg.getBuckets()) {
Long key = (Long) entry.getKey(); // Key Double key = (Double) entry.getKey(); // Key
long docCount = entry.getDocCount(); // Doc count long docCount = entry.getDocCount(); // Doc count
logger.info("key [{}], doc_count [{}]", key, docCount); logger.info("key [{}], doc_count [{}]", key, docCount);

View File

@ -14,7 +14,7 @@ Here is an example on how to create the aggregation request:
-------------------------------------------------- --------------------------------------------------
AggregationBuilder aggregation = AggregationBuilder aggregation =
AggregationBuilders AggregationBuilders
.nested("agg").path("resellers") .nested("agg", "resellers")
.subAggregation( .subAggregation(
AggregationBuilders AggregationBuilders
.terms("name").field("resellers.name") .terms("name").field("resellers.name")

View File

@ -12,7 +12,7 @@ Here is an example on how to create the aggregation request:
[source,java] [source,java]
-------------------------------------------------- --------------------------------------------------
MetricsAggregationBuilder aggregation = AvgAggregationBuilder aggregation =
AggregationBuilders AggregationBuilders
.avg("agg") .avg("agg")
.field("height"); .field("height");

View File

@ -12,7 +12,7 @@ Here is an example on how to create the aggregation request:
[source,java] [source,java]
-------------------------------------------------- --------------------------------------------------
MetricsAggregationBuilder aggregation = CardinalityAggregationBuilder aggregation =
AggregationBuilders AggregationBuilders
.cardinality("agg") .cardinality("agg")
.field("tags"); .field("tags");

View File

@ -12,7 +12,7 @@ Here is an example on how to create the aggregation request:
[source,java] [source,java]
-------------------------------------------------- --------------------------------------------------
MetricsAggregationBuilder aggregation = ExtendedStatsAggregationBuilder aggregation =
AggregationBuilders AggregationBuilders
.extendedStats("agg") .extendedStats("agg")
.field("height"); .field("height");

View File

@ -13,7 +13,7 @@ Here is an example on how to create the aggregation request:
[source,java] [source,java]
-------------------------------------------------- --------------------------------------------------
GeoBoundsBuilder aggregation = GeoBoundsBuilder aggregation =
AggregationBuilders GeoBoundsAggregationBuilder
.geoBounds("agg") .geoBounds("agg")
.field("address.location") .field("address.location")
.wrapLongitude(true); .wrapLongitude(true);

View File

@ -12,7 +12,7 @@ Here is an example on how to create the aggregation request:
[source,java] [source,java]
-------------------------------------------------- --------------------------------------------------
MetricsAggregationBuilder aggregation = MaxAggregationBuilder aggregation =
AggregationBuilders AggregationBuilders
.max("agg") .max("agg")
.field("height"); .field("height");

View File

@ -12,7 +12,7 @@ Here is an example on how to create the aggregation request:
[source,java] [source,java]
-------------------------------------------------- --------------------------------------------------
MetricsAggregationBuilder aggregation = MinAggregationBuilder aggregation =
AggregationBuilders AggregationBuilders
.min("agg") .min("agg")
.field("height"); .field("height");

View File

@ -12,7 +12,7 @@ Here is an example on how to create the aggregation request:
[source,java] [source,java]
-------------------------------------------------- --------------------------------------------------
MetricsAggregationBuilder aggregation = PercentilesAggregationBuilder aggregation =
AggregationBuilders AggregationBuilders
.percentiles("agg") .percentiles("agg")
.field("height"); .field("height");
@ -22,7 +22,7 @@ You can provide your own percentiles instead of using defaults:
[source,java] [source,java]
-------------------------------------------------- --------------------------------------------------
MetricsAggregationBuilder aggregation = PercentilesAggregationBuilder aggregation =
AggregationBuilders AggregationBuilders
.percentiles("agg") .percentiles("agg")
.field("height") .field("height")

View File

@ -12,11 +12,11 @@ Here is an example on how to create the aggregation request:
[source,java] [source,java]
-------------------------------------------------- --------------------------------------------------
MetricsAggregationBuilder aggregation = PercentileRanksAggregationBuilder aggregation =
AggregationBuilders AggregationBuilders
.percentileRanks("agg") .percentileRanks("agg")
.field("height") .field("height")
.percentiles(1.24, 1.91, 2.22); .values(1.24, 1.91, 2.22);
-------------------------------------------------- --------------------------------------------------

View File

@ -11,21 +11,20 @@ Here is an example on how to create the aggregation request:
[source,java] [source,java]
-------------------------------------------------- --------------------------------------------------
MetricsAggregationBuilder aggregation = ScriptedMetricAggregationBuilder aggregation = AggregationBuilders
AggregationBuilders .scriptedMetric("agg")
.scriptedMetric("agg") .initScript(new Script("_agg['heights'] = []"))
.initScript("_agg['heights'] = []") .mapScript(new Script("if (doc['gender'].value == \"male\") " +
.mapScript(new Script("if (doc['gender'].value == \"male\") " + "{ _agg.heights.add(doc['height'].value) } " +
"{ _agg.heights.add(doc['height'].value) } " + "else " +
"else " + "{ _agg.heights.add(-1 * doc['height'].value) }"));
"{ _agg.heights.add(-1 * doc['height'].value) }"));
-------------------------------------------------- --------------------------------------------------
You can also specify a `combine` script which will be executed on each shard: You can also specify a `combine` script which will be executed on each shard:
[source,java] [source,java]
-------------------------------------------------- --------------------------------------------------
MetricsAggregationBuilder aggregation = ScriptedMetricAggregationBuilder aggregation =
AggregationBuilders AggregationBuilders
.scriptedMetric("agg") .scriptedMetric("agg")
.initScript(new Script("_agg['heights'] = []")) .initScript(new Script("_agg['heights'] = []"))
@ -40,7 +39,7 @@ You can also specify a `reduce` script which will be executed on the node which
[source,java] [source,java]
-------------------------------------------------- --------------------------------------------------
MetricsAggregationBuilder aggregation = ScriptedMetricAggregationBuilder aggregation =
AggregationBuilders AggregationBuilders
.scriptedMetric("agg") .scriptedMetric("agg")
.initScript(new Script("_agg['heights'] = []")) .initScript(new Script("_agg['heights'] = []"))

View File

@ -12,7 +12,7 @@ Here is an example on how to create the aggregation request:
[source,java] [source,java]
-------------------------------------------------- --------------------------------------------------
MetricsAggregationBuilder aggregation = StatsAggregationBuilder aggregation =
AggregationBuilders AggregationBuilders
.stats("agg") .stats("agg")
.field("height"); .field("height");

View File

@ -12,7 +12,7 @@ Here is an example on how to create the aggregation request:
[source,java] [source,java]
-------------------------------------------------- --------------------------------------------------
MetricsAggregationBuilder aggregation = SumAggregationBuilder aggregation =
AggregationBuilders AggregationBuilders
.sum("agg") .sum("agg")
.field("height"); .field("height");

View File

@ -12,7 +12,7 @@ Here is an example on how to create the aggregation request:
[source,java] [source,java]
-------------------------------------------------- --------------------------------------------------
MetricsAggregationBuilder aggregation = ValueCountAggregationBuilder aggregation =
AggregationBuilders AggregationBuilders
.count("agg") .count("agg")
.field("height"); .field("height");

View File

@ -19,6 +19,7 @@ FilterFunctionBuilder[] functions = {
new FunctionScoreQueryBuilder.FilterFunctionBuilder( new FunctionScoreQueryBuilder.FilterFunctionBuilder(
exponentialDecayFunction("age", 0L, 1L)) <3> exponentialDecayFunction("age", 0L, 1L)) <3>
}; };
QueryBuilder qb = QueryBuilders.functionScoreQuery(functions);
-------------------------------------------------- --------------------------------------------------
<1> Add a first function based on a query <1> Add a first function based on a query
<2> And randomize the score based on a given seed <2> And randomize the score based on a given seed

View File

@ -7,15 +7,9 @@ See {ref}/query-dsl-geo-distance-query.html[Geo Distance Query]
-------------------------------------------------- --------------------------------------------------
QueryBuilder qb = geoDistanceQuery("pin.location") <1> QueryBuilder qb = geoDistanceQuery("pin.location") <1>
.point(40, -70) <2> .point(40, -70) <2>
.distance(200, DistanceUnit.KILOMETERS) <3> .distance(200, DistanceUnit.KILOMETERS); <3>
.optimizeBbox("memory") <4>
.geoDistance(GeoDistance.ARC); <5>
-------------------------------------------------- --------------------------------------------------
<1> field <1> field
<2> center point <2> center point
<3> distance from center point <3> distance from center point
<4> optimize bounding box: `memory`, `indexed` or `none`
<5> distance computation mode: `GeoDistance.SLOPPY_ARC` (default), `GeoDistance.ARC` (slightly more precise but
significantly slower) or `GeoDistance.PLANE` (faster, but inaccurate on long distances and close to the poles)

View File

@ -1,26 +0,0 @@
[[java-query-dsl-geo-distance-range-query]]
==== Geo Distance Range Query
See {ref}/query-dsl-geo-distance-range-query.html[Geo Distance Range Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = geoDistanceRangeQuery("pin.location", <1>
new GeoPoint(40, -70)) <2>
.from("200km") <3>
.to("400km") <4>
.includeLower(true) <5>
.includeUpper(false) <6>
.optimizeBbox("memory") <7>
.geoDistance(GeoDistance.ARC); <8>
--------------------------------------------------
<1> field
<2> center point
<3> starting distance from center point
<4> ending distance from center point
<5> include lower value means that `from` is `gt` when `false` or `gte` when `true`
<6> include upper value means that `to` is `lt` when `false` or `lte` when `true`
<7> optimize bounding box: `memory`, `indexed` or `none`
<8> distance computation mode: `GeoDistance.SLOPPY_ARC` (default), `GeoDistance.ARC` (slightly more precise but
significantly slower) or `GeoDistance.PLANE` (faster, but inaccurate on long distances and close to the poles)

View File

@ -5,7 +5,7 @@ See {ref}/query-dsl-geo-polygon-query.html[Geo Polygon Query]
[source,java] [source,java]
-------------------------------------------------- --------------------------------------------------
List<GeoPoint> points = new ArrayList<GeoPoint>(); <1> List<GeoPoint> points = new ArrayList<>(); <1>
points.add(new GeoPoint(40, -70)); points.add(new GeoPoint(40, -70));
points.add(new GeoPoint(30, -80)); points.add(new GeoPoint(30, -80));
points.add(new GeoPoint(20, -90)); points.add(new GeoPoint(20, -90));

View File

@ -36,6 +36,4 @@ include::geo-bounding-box-query.asciidoc[]
include::geo-distance-query.asciidoc[] include::geo-distance-query.asciidoc[]
include::geo-distance-range-query.asciidoc[]
include::geo-polygon-query.asciidoc[] include::geo-polygon-query.asciidoc[]

View File

@ -39,31 +39,32 @@ import org.elasticsearch.common.geo.builders.ShapeBuilder;
[source,java] [source,java]
-------------------------------------------------- --------------------------------------------------
GeoShapeQueryBuilder qb = geoShapeQuery( List<Coordinate> points = new ArrayList<>();
"pin.location", <1> points.add(new Coordinate(0, 0));
ShapeBuilder.newMultiPoint() <2> points.add(new Coordinate(0, 10));
.point(0, 0) points.add(new Coordinate(10, 10));
.point(0, 10) points.add(new Coordinate(10, 0));
.point(10, 10) points.add(new Coordinate(0, 0));
.point(10, 0)
.point(0, 0));
qb.relation(ShapeRelation.WITHIN); <3>
QueryBuilder qb = geoShapeQuery(
"pin.location", <1>
ShapeBuilders.newMultiPoint(points) <2>
.relation(ShapeRelation.WITHIN); <3>
-------------------------------------------------- --------------------------------------------------
<1> field <1> field
<2> shape <2> shape
<3> relation can be `ShapeRelation.WITHIN`, `ShapeRelation.INTERSECTS` or `ShapeRelation.DISJOINT` <3> relation can be `ShapeRelation.CONTAINS`, `ShapeRelation.WITHIN`, `ShapeRelation.INTERSECTS` or `ShapeRelation.DISJOINT`
[source,java] [source,java]
-------------------------------------------------- --------------------------------------------------
// Using pre-indexed shapes // Using pre-indexed shapes
GeoShapeQueryBuilder qb = geoShapeQuery( QueryBuilder qb = geoShapeQuery(
"pin.location", <1> "pin.location", <1>
"DEU", <2> "DEU", <2>
"countries"); <3> "countries") <3>
qb.relation(ShapeRelation.WITHIN)) <4> .relation(ShapeRelation.WITHIN)) <4>
.indexedShapeIndex("shapes") <5> .indexedShapeIndex("shapes") <5>
.indexedShapePath("location"); <6> .indexedShapePath("location"); <6>
-------------------------------------------------- --------------------------------------------------
<1> field <1> field
<2> The ID of the document that containing the pre-indexed shape. <2> The ID of the document that containing the pre-indexed shape.

View File

@ -7,9 +7,11 @@ See {ref}/query-dsl-has-child-query.html[Has Child Query]
-------------------------------------------------- --------------------------------------------------
QueryBuilder qb = hasChildQuery( QueryBuilder qb = hasChildQuery(
"blog_tag", <1> "blog_tag", <1>
termQuery("tag","something") <2> termQuery("tag","something"), <2>
ScoreMode.Avg <3>
); );
-------------------------------------------------- --------------------------------------------------
<1> child type to query against <1> child type to query against
<2> query <2> query
<3> score mode can be `ScoreMode.Avg`, `ScoreMode.Max`, `ScoreMode.Min`, `ScoreMode.None` or `ScoreMode.Total`

View File

@ -7,8 +7,10 @@ See {ref}/query-dsl-has-parent-query.html[Has Parent]
-------------------------------------------------- --------------------------------------------------
QueryBuilder qb = hasParentQuery( QueryBuilder qb = hasParentQuery(
"blog", <1> "blog", <1>
termQuery("tag","something") <2> termQuery("tag","something"), <2>
false <3>
); );
-------------------------------------------------- --------------------------------------------------
<1> parent type to query against <1> parent type to query against
<2> query <2> query
<3> whether the score from the parent hit should propogate to the child hit

View File

@ -9,10 +9,10 @@ QueryBuilder qb = nestedQuery(
"obj1", <1> "obj1", <1>
boolQuery() <2> boolQuery() <2>
.must(matchQuery("obj1.name", "blue")) .must(matchQuery("obj1.name", "blue"))
.must(rangeQuery("obj1.count").gt(5)) .must(rangeQuery("obj1.count").gt(5)),
) ScoreMode.Avg <3>
.scoreMode(ScoreMode.Avg); <3> );
-------------------------------------------------- --------------------------------------------------
<1> path to nested document <1> path to nested document
<2> your query. Any fields referenced inside the query must use the complete path (fully qualified). <2> your query. Any fields referenced inside the query must use the complete path (fully qualified).
<3> score mode could be `max`, `total`, `avg` (default) or `none` <3> score mode could be `ScoreMode.Max`, `ScoreMode.Min`, `ScoreMode.Total`, `ScoreMode.Avg` or `ScoreMode.None`

View File

@ -25,10 +25,10 @@ You can use it then with:
-------------------------------------------------- --------------------------------------------------
QueryBuilder qb = scriptQuery( QueryBuilder qb = scriptQuery(
new Script( new Script(
"myscript", <1> "myscript", <1>
ScriptType.FILE, <2> ScriptType.FILE, <2>
"painless", <3> "painless", <3>
ImmutableMap.of("param1", 5)) <4> Collections.singletonMap("param1", 5)) <4>
); );
-------------------------------------------------- --------------------------------------------------
<1> Script name <1> Script name

View File

@ -7,7 +7,7 @@ See {ref}/query-dsl-span-containing-query.html[Span Containing Query]
-------------------------------------------------- --------------------------------------------------
QueryBuilder qb = spanContainingQuery( QueryBuilder qb = spanContainingQuery(
spanNearQuery(spanTermQuery("field1","bar"), 5) <1> spanNearQuery(spanTermQuery("field1","bar"), 5) <1>
.clause(spanTermQuery("field1","baz")) .addClause(spanTermQuery("field1","baz"))
.inOrder(true), .inOrder(true),
spanTermQuery("field1","foo")); <2> spanTermQuery("field1","foo")); <2>
-------------------------------------------------- --------------------------------------------------

View File

@ -8,13 +8,11 @@ See {ref}/query-dsl-span-near-query.html[Span Near Query]
QueryBuilder qb = spanNearQuery( QueryBuilder qb = spanNearQuery(
spanTermQuery("field","value1"), <1> spanTermQuery("field","value1"), <1>
12) <2> 12) <2>
.clause(spanTermQuery("field","value2")) <1> .addClause(spanTermQuery("field","value2")) <1>
.clause(spanTermQuery("field","value3")) <1> .addClause(spanTermQuery("field","value3")) <1>
.inOrder(false) <3> .inOrder(false); <3>
.collectPayloads(false); <4>
-------------------------------------------------- --------------------------------------------------
<1> span term queries <1> span term queries
<2> slop factor: the maximum number of intervening unmatched positions <2> slop factor: the maximum number of intervening unmatched positions
<3> whether matches are required to be in-order <3> whether matches are required to be in-order
<4> collect payloads or not

View File

@ -6,9 +6,9 @@ See {ref}/query-dsl-span-or-query.html[Span Or Query]
[source,java] [source,java]
-------------------------------------------------- --------------------------------------------------
QueryBuilder qb = spanOrQuery( QueryBuilder qb = spanOrQuery(
spanTermQuery("field","value1")) <1> spanTermQuery("field","value1")) <1>
.clause(spanTermQuery("field","value2")) <1> .addClause(spanTermQuery("field","value2")) <1>
.clause(spanTermQuery("field","value3")); <1> .addClause(spanTermQuery("field","value3")); <1>
-------------------------------------------------- --------------------------------------------------
<1> span term queries <1> span term queries

View File

@ -7,7 +7,7 @@ See {ref}/query-dsl-span-within-query.html[Span Within Query]
-------------------------------------------------- --------------------------------------------------
QueryBuilder qb = spanWithinQuery( QueryBuilder qb = spanWithinQuery(
spanNearQuery(spanTermQuery("field1", "bar"), 5) <1> spanNearQuery(spanTermQuery("field1", "bar"), 5) <1>
.clause(spanTermQuery("field1", "baz")) .addClause(spanTermQuery("field1", "baz"))
.inOrder(true), .inOrder(true),
spanTermQuery("field1", "foo")); <2> spanTermQuery("field1", "foo")); <2>
-------------------------------------------------- --------------------------------------------------

View File

@ -26,8 +26,6 @@ This query finds percolator queries based on documents.
include::mlt-query.asciidoc[] include::mlt-query.asciidoc[]
include::template-query.asciidoc[]
include::script-query.asciidoc[] include::script-query.asciidoc[]
include::percolate-query.asciidoc[] include::percolate-query.asciidoc[]

View File

@ -1,89 +0,0 @@
[[java-query-dsl-template-query]]
==== Template Query
See {ref}/search-template.html[Search Template] documentation
In order to use the `template` query from the Java API
the lang-mustache module dependency should be on the classpath and
the transport client should be loaded with the lang-mustache plugin:
[source,java]
--------------------------------------------------
TransportClient transportClient = TransportClient.builder()
.settings(Settings.builder().put("node.name", "node"))
.addPlugin(MustachePlugin.class)
.build();
transportClient.addTransportAddress(
new InetSocketTransportAddress(new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 9300))
);
--------------------------------------------------
Define your template parameters as a `Map<String,Object>`:
[source,java]
--------------------------------------------------
Map<String, Object> template_params = new HashMap<>();
template_params.put("param_gender", "male");
--------------------------------------------------
You can use your stored search templates in `config/scripts`.
For example, if you have a file named `config/scripts/template_gender.mustache` containing:
[source,js]
--------------------------------------------------
{
"template" : {
"query" : {
"match" : {
"gender" : "{{param_gender}}"
}
}
}
}
--------------------------------------------------
// NOTCONSOLE
Define your template query:
[source,java]
--------------------------------------------------
QueryBuilder qb = new TemplateQueryBuilder(
"gender_template", <1>
ScriptService.ScriptType.FILE, <2>
template_params); <3>
--------------------------------------------------
<1> template name
<2> template stored on disk in `gender_template.mustache`
<3> parameters
You can also store your template in the cluster state:
[source,java]
--------------------------------------------------
client.admin().cluster().preparePutStoredScript()
.setScriptLang("mustache")
.setId("template_gender")
.setSource(new BytesArray(
"{\n" +
" \"template\" : {\n" +
" \"query\" : {\n" +
" \"match\" : {\n" +
" \"gender\" : \"{{param_gender}}\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}")).get();
--------------------------------------------------
To execute a stored templates, use `ScriptService.ScriptType.STORED`:
[source,java]
--------------------------------------------------
QueryBuilder qb = new TemplateQueryBuilder(
"gender_template", <1>
ScriptType.STORED, <2>
template_params); <3>
--------------------------------------------------
<1> template name
<2> template stored in the cluster state
<3> parameters

View File

@ -21,8 +21,7 @@ SearchResponse response = client.prepareSearch("index1", "index2")
.setQuery(QueryBuilders.termQuery("multi", "test")) // Query .setQuery(QueryBuilders.termQuery("multi", "test")) // Query
.setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18)) // Filter .setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18)) // Filter
.setFrom(0).setSize(60).setExplain(true) .setFrom(0).setSize(60).setExplain(true)
.execute() .get();
.actionGet();
-------------------------------------------------- --------------------------------------------------
Note that all parameters are optional. Here is the smallest search call Note that all parameters are optional. Here is the smallest search call
@ -31,7 +30,7 @@ you can write:
[source,java] [source,java]
-------------------------------------------------- --------------------------------------------------
// MatchAll on the whole cluster with all default options // MatchAll on the whole cluster with all default options
SearchResponse response = client.prepareSearch().execute().actionGet(); SearchResponse response = client.prepareSearch().get();
-------------------------------------------------- --------------------------------------------------
NOTE: Although the Java API defines the additional search types QUERY_AND_FETCH and NOTE: Although the Java API defines the additional search types QUERY_AND_FETCH and
@ -58,7 +57,7 @@ SearchResponse scrollResp = client.prepareSearch(test)
.addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC) .addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC)
.setScroll(new TimeValue(60000)) .setScroll(new TimeValue(60000))
.setQuery(qb) .setQuery(qb)
.setSize(100).execute().actionGet(); //max of 100 hits will be returned for each scroll .setSize(100).get(); //max of 100 hits will be returned for each scroll
//Scroll until no hits are returned //Scroll until no hits are returned
do { do {
for (SearchHit hit : scrollResp.getHits().getHits()) { for (SearchHit hit : scrollResp.getHits().getHits()) {
@ -85,7 +84,7 @@ SearchRequestBuilder srb2 = client
MultiSearchResponse sr = client.prepareMultiSearch() MultiSearchResponse sr = client.prepareMultiSearch()
.add(srb1) .add(srb1)
.add(srb2) .add(srb2)
.execute().actionGet(); .get();
// You will get all individual responses from MultiSearchResponse#getResponses() // You will get all individual responses from MultiSearchResponse#getResponses()
long nbHits = 0; long nbHits = 0;
@ -113,7 +112,7 @@ SearchResponse sr = client.prepareSearch()
.field("birth") .field("birth")
.dateHistogramInterval(DateHistogramInterval.YEAR) .dateHistogramInterval(DateHistogramInterval.YEAR)
) )
.execute().actionGet(); .get();
// Get your facet results // Get your facet results
Terms agg1 = sr.getAggregations().get("agg1"); Terms agg1 = sr.getAggregations().get("agg1");
@ -142,3 +141,115 @@ if (sr.isTerminatedEarly()) {
} }
-------------------------------------------------- --------------------------------------------------
<1> Finish after 1000 docs <1> Finish after 1000 docs
[[java-search-template]]
==== Search Template
See {ref}/search-template.html[Search Template] documentation
Define your template parameters as a `Map<String,Object>`:
[source,java]
--------------------------------------------------
Map<String, Object> template_params = new HashMap<>();
template_params.put("param_gender", "male");
--------------------------------------------------
You can use your stored search templates in `config/scripts`.
For example, if you have a file named `config/scripts/template_gender.mustache` containing:
[source,js]
--------------------------------------------------
{
"template" : {
"query" : {
"match" : {
"gender" : "{{param_gender}}"
}
}
}
}
--------------------------------------------------
// NOTCONSOLE
Create your search template request:
[source,java]
--------------------------------------------------
SearchResponse sr = new SearchTemplateRequestBuilder(client)
.setScript("template_gender") <1>
.setScriptType(ScriptService.ScriptType.FILE) <2>
.setScriptParams(template_params) <3>
.setRequest(new SearchRequest()) <4>
.get() <5>
.getResponse(); <6>
--------------------------------------------------
<1> template name
<2> template stored on disk in `gender_template.mustache`
<3> parameters
<4> set the execution context (ie. define the index name here)
<5> execute and get the template response
<6> get from the template response the search response itself
You can also store your template in the cluster state:
[source,java]
--------------------------------------------------
client.admin().cluster().preparePutStoredScript()
.setScriptLang("mustache")
.setId("template_gender")
.setSource(new BytesArray(
"{\n" +
" \"template\" : {\n" +
" \"query\" : {\n" +
" \"match\" : {\n" +
" \"gender\" : \"{{param_gender}}\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}")).get();
--------------------------------------------------
To execute a stored templates, use `ScriptService.ScriptType.STORED`:
[source,java]
--------------------------------------------------
SearchResponse sr = new SearchTemplateRequestBuilder(client)
.setScript("template_gender") <1>
.setScriptType(ScriptService.ScriptType.STORED) <2>
.setScriptParams(template_params) <3>
.setRequest(new SearchRequest()) <4>
.get() <5>
.getResponse(); <6>
--------------------------------------------------
<1> template name
<2> template stored in the cluster state
<3> parameters
<4> set the execution context (ie. define the index name here)
<5> execute and get the template response
<6> get from the template response the search response itself
You can also execute inline templates:
[source,java]
--------------------------------------------------
sr = new SearchTemplateRequestBuilder(client)
.setScript("{\n" + <1>
" \"query\" : {\n" +
" \"match\" : {\n" +
" \"gender\" : \"{{param_gender}}\"\n" +
" }\n" +
" }\n" +
"}")
.setScriptType(ScriptService.ScriptType.INLINE) <2>
.setScriptParams(template_params) <3>
.setRequest(new SearchRequest()) <4>
.get() <5>
.getResponse(); <6>
--------------------------------------------------
<1> template name
<2> template is passed inline
<3> parameters
<4> set the execution context (ie. define the index name here)
<5> execute and get the template response
<6> get from the template response the search response itself