[doc] Reorganize and clean Java documentation

This commit reorganizes the docs to make Java API docs looking more like the REST docs.
Also, with 2.0.0, FilterBuilders don't exist anymore but only QueryBuilders.

Also, all docs api move now to docs/java-api/docs dir as for REST doc.

Remove removed queries/filters
-----

* Remove Constant Score Query with filter
* Remove Fuzzy Like This (Field) Query (flt and flt_field)
* Remove FilterBuilders

Move filters to queries
-----

* Move And Filter to And Query
* Move Bool Filter to Bool Query
* Move Exists Filter to Exists Query
* Move Geo Bounding Box Filter to Geo Bounding Box Query
* Move Geo Distance Filter to Geo Distance Query
* Move Geo Distance Range Filter to Geo Distance Range Query
* Move Geo Polygon Filter to Geo Polygon Query
* Move Geo Shape Filter to Geo Shape Query
* Move Has Child Filter by Has Child Query
* Move Has Parent Filter by Has Parent Query
* Move Ids Filter by Ids Query
* Move Limit Filter to Limit Query
* Move MatchAll Filter to MatchAll Query
* Move Missing Filter to Missing Query
* Move Nested Filter to Nested Query
* Move Not Filter to Not Query
* Move Or Filter to Or Query
* Move Range Filter to Range Query
* Move Ids Filter to Ids Query
* Move Term Filter to Term Query
* Move Terms Filter to Terms Query
* Move Type Filter to Type Query

Add missing queries
-----

* Add Common Terms Query
* Add Filtered Query
* Add Function Score Query
* Add Geohash Cell Query
* Add Regexp Query
* Add Script Query
* Add Simple Query String Query
* Add Span Containing Query
* Add Span Multi Term Query
* Add Span Within Query

Reorganize the documentation
-----

* Organize by full text queries
* Organize by term level queries
* Organize by compound queries
* Organize by joining queries
* Organize by geo queries
* Organize by specialized queries
* Organize by span queries
* Move Boosting Query
* Move DisMax Query
* Move Fuzzy Query
* Move Indices Query
* Move Match Query
* Move Mlt Query
* Move Multi Match Query
* Move Prefix Query
* Move Query String Query
* Move Span First Query
* Move Span Near Query
* Move Span Not Query
* Move Span Or Query
* Move Span Term Query
* Move Template Query
* Move Wildcard Query

Add some missing pages
----

* Add multi get API
* Add indexed-scripts link

Also closes #7826
Related to https://github.com/elastic/elasticsearch/pull/11477#issuecomment-114745934
This commit is contained in:
David Pilato 2015-06-24 23:27:19 +02:00
parent e429b8d190
commit 1e35674eb0
72 changed files with 1477 additions and 1271 deletions

View File

@ -3,8 +3,8 @@
You can use the *Java client* in multiple ways:
* Perform standard <<index_,index>>, <<get,get>>,
<<delete,delete>> and <<search,search>> operations on an
* Perform standard <<java-docs-index,index>>, <<java-docs-get,get>>,
<<java-docs-delete,delete>> and <<java-search,search>> operations on an
existing cluster
* Perform administrative tasks on a running cluster
* Start full nodes when you want to run Elasticsearch embedded in your

View File

@ -8,7 +8,6 @@ and across one or more types. The query can be provided using the
[source,java]
--------------------------------------------------
import static org.elasticsearch.index.query.FilterBuilders.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
CountResponse response = client.prepareCount("test")

View File

@ -1,21 +0,0 @@
[[delete-by-query]]
== Delete By Query API
The delete by query API allows one to delete documents from one or more
indices and one or more types based on a <<query-dsl-queries,query>>. Here
is an example:
[source,java]
--------------------------------------------------
import static org.elasticsearch.index.query.FilterBuilders.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
DeleteByQueryResponse response = client.prepareDeleteByQuery("test")
.setQuery(termQuery("_type", "type1"))
.execute()
.actionGet();
--------------------------------------------------
For more information on the delete by query operation, check out the
{ref}/docs-delete-by-query.html[delete_by_query API]
docs.

View File

@ -0,0 +1,32 @@
[[java-docs]]
== Document APIs
This section describes the following CRUD APIs:
.Single document APIs
* <<java-docs-index>>
* <<java-docs-get>>
* <<java-docs-delete>>
* <<java-docs-update>>
.Multi-document APIs
* <<java-docs-multi-get>>
* <<java-docs-bulk>>
* <<java-docs-delete-by-query>>
NOTE: All CRUD APIs are single-index APIs. The `index` parameter accepts a single
index name, or an `alias` which points to a single index.
include::docs/index_.asciidoc[]
include::docs/get.asciidoc[]
include::docs/delete.asciidoc[]
include::docs/update.asciidoc[]
include::docs/multi-get.asciidoc[]
include::docs/bulk.asciidoc[]
include::docs/delete-by-query.asciidoc[]

View File

@ -1,5 +1,5 @@
[[bulk]]
== Bulk API
[[java-docs-bulk]]
=== Bulk API
The bulk API allows one to index and delete several documents in a
single request. Here is a sample usage:
@ -31,14 +31,14 @@ bulkRequest.add(client.prepareIndex("twitter", "tweet", "2")
)
);
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
BulkResponse bulkResponse = bulkRequest.get();
if (bulkResponse.hasFailures()) {
// process failures by iterating through each bulk response item
}
--------------------------------------------------
[float]
== Using Bulk Processor
[[java-docs-bulk-processor]]
=== Using Bulk Processor
The `BulkProcessor` class offers a simple interface to flush bulk operations automatically based on the number or size
of requests, or after a given period.

View File

@ -0,0 +1,34 @@
[[java-docs-delete-by-query]]
=== Delete By Query API
The delete by query API allows one to delete documents from one or more
indices and one or more types based on a <<java-query-dsl,query>>.
It's available as a plugin so you need to explicitly declare it in your project:
[source,xml]
--------------------------------------------------
<dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>elasticsearch-delete-by-query</artifactId>
<version>${es.version}</version>
</dependency>
--------------------------------------------------
To use it from Java, you can do the following:
[source,java]
--------------------------------------------------
import static org.elasticsearch.index.query.QueryBuilders.*;
DeleteByQueryResponse response = client
.prepareDeleteByQuery("test") <1>
.setQuery(termQuery("_type", "type1")) <2>
.get();
--------------------------------------------------
<1> index name
<2> query
For more information on the delete by query operation, check out the
{ref}/docs-delete-by-query.html[delete_by_query API]
docs.

View File

@ -1,5 +1,5 @@
[[delete]]
== Delete API
[[java-docs-delete]]
=== Delete API
The delete API allows one to delete a typed JSON document from a specific
index based on its id. The following example deletes the JSON document
@ -8,17 +8,15 @@ from an index called twitter, under a type called tweet, with id valued
[source,java]
--------------------------------------------------
DeleteResponse response = client.prepareDelete("twitter", "tweet", "1")
.execute()
.actionGet();
DeleteResponse response = client.prepareDelete("twitter", "tweet", "1").get();
--------------------------------------------------
For more information on the delete operation, check out the
{ref}/docs-delete.html[delete API] docs.
[[operation-threading]]
=== Operation Threading
[[java-docs-delete-thread]]
==== Operation Threading
The delete API allows to set the threading model the operation will be
performed when the actual execution of the API is performed on the same
@ -35,6 +33,5 @@ is executed on a different thread. Here is an example that sets it to
--------------------------------------------------
DeleteResponse response = client.prepareDelete("twitter", "tweet", "1")
.setOperationThreaded(false)
.execute()
.actionGet();
.get();
--------------------------------------------------

View File

@ -1,5 +1,5 @@
[[get]]
== Get API
[[java-docs-get]]
=== Get API
The get API allows to get a typed JSON document from the index based on
its id. The following example gets a JSON document from an index called
@ -7,16 +7,15 @@ twitter, under a type called tweet, with id valued 1:
[source,java]
--------------------------------------------------
GetResponse response = client.prepareGet("twitter", "tweet", "1")
.execute()
.actionGet();
GetResponse response = client.prepareGet("twitter", "tweet", "1").get();
--------------------------------------------------
For more information on the get operation, check out the REST
{ref}/docs-get.html[get] docs.
=== Operation Threading
[[java-docs-get-thread]]
==== Operation Threading
The get API allows to set the threading model the operation will be
performed when the actual execution of the API is performed on the same
@ -33,6 +32,5 @@ is executed on a different thread. Here is an example that sets it to
--------------------------------------------------
GetResponse response = client.prepareGet("twitter", "tweet", "1")
.setOperationThreaded(false)
.execute()
.actionGet();
.get();
--------------------------------------------------

View File

@ -1,12 +1,12 @@
[[index_]]
== Index API
[[java-docs-index]]
=== Index API
The index API allows one to index a typed JSON document into a specific
index and make it searchable.
[[generate]]
=== Generate JSON document
[[java-docs-index-generate]]
==== Generate JSON document
There are several different ways of generating a JSON document:
@ -26,7 +26,8 @@ use it. The `jsonBuilder` is highly optimized JSON generator that
directly constructs a `byte[]`.
==== Do It Yourself
[[java-docs-index-generate-diy]]
===== Do It Yourself
Nothing really difficult here but note that you will have to encode
dates according to the
@ -42,8 +43,8 @@ String json = "{" +
--------------------------------------------------
[[using-map]]
==== Using Map
[[java-docs-index-generate-using-map]]
===== Using Map
Map is a key:values pair collection. It represents a JSON structure:
@ -56,8 +57,8 @@ json.put("message","trying out Elasticsearch");
--------------------------------------------------
[[beans]]
==== Serialize your beans
[[java-docs-index-generate-beans]]
===== Serialize your beans
Elasticsearch already uses Jackson but shades it under
`org.elasticsearch.common.jackson` package. +
@ -90,8 +91,8 @@ byte[] json = mapper.writeValueAsBytes(yourbeaninstance);
--------------------------------------------------
[[helpers]]
==== Use Elasticsearch helpers
[[java-docs-index-generate-helpers]]
===== Use Elasticsearch helpers
Elasticsearch provides built-in helpers to generate JSON content.
@ -121,8 +122,8 @@ String json = builder.string();
--------------------------------------------------
[[index-doc]]
=== Index document
[[java-docs-index-doc]]
==== Index document
The following example indexes a JSON document into an index called
twitter, under a type called tweet, with id valued 1:
@ -139,8 +140,7 @@ IndexResponse response = client.prepareIndex("twitter", "tweet", "1")
.field("message", "trying out Elasticsearch")
.endObject()
)
.execute()
.actionGet();
.get();
--------------------------------------------------
Note that you can also index your documents as JSON String and that you
@ -156,8 +156,7 @@ String json = "{" +
IndexResponse response = client.prepareIndex("twitter", "tweet")
.setSource(json)
.execute()
.actionGet();
.get();
--------------------------------------------------
`IndexResponse` object will give you a report:
@ -180,7 +179,8 @@ For more information on the index operation, check out the REST
{ref}/docs-index_.html[index] docs.
=== Operation Threading
[[java-docs-index-thread]]
==== Operation Threading
The index API allows one to set the threading model the operation will be
performed when the actual execution of the API is performed on the same

View File

@ -0,0 +1,30 @@
[[java-docs-multi-get]]
=== Multi Get API
The multi get API allows to get a list of documents based on their `index`, `type` and `id`:
[source,java]
--------------------------------------------------
MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
.add("twitter", "tweet", "1") <1>
.add("twitter", "tweet", "2", "3", "4") <2>
.add("another", "type", "foo") <3>
.get();
for (MultiGetItemResponse itemResponse : multiGetItemResponses) { <4>
GetResponse response = itemResponse.getResponse();
if (response.isExists()) { <5>
String json = response.getSourceAsString(); <6>
}
}
--------------------------------------------------
<1> get by a single id
<2> or by a list of ids for the same index / type
<3> you can also get from another index
<4> iterate over the result set
<5> you can check if the document exists
<6> access to the `_source` field
For more information on the multi get operation, check out the REST
{ref}/docs-multi-get.html[multi get] docs.

View File

@ -1,5 +1,5 @@
[[java-update-api]]
== Update API
[[java-docs-update]]
=== Update API
You can either create an `UpdateRequest` and send it to the client:
@ -38,8 +38,8 @@ In that case, you'll need to use `ScriptService.ScriptType.FILE`
Note that you can't provide both `script` and `doc`.
[[java-update-api-script]]
=== Update by script
[[java-docs-update-api-script]]
==== Update by script
The update API allows to update a document based on a script provided:
@ -51,8 +51,8 @@ client.update(updateRequest).get();
--------------------------------------------------
[[java-update-api-merge-docs]]
=== Update by merging documents
[[java-docs-update-api-merge-docs]]
==== Update by merging documents
The update API also support passing a partial document, which will be merged into the existing document (simple
recursive merge, inner merging of objects, replacing core "keys/values" and arrays). For example:
@ -68,8 +68,8 @@ client.update(updateRequest).get();
--------------------------------------------------
[[java-update-api-upsert]]
=== Upsert
[[java-docs-update-api-upsert]]
==== Upsert
There is also support for `upsert`. If the document already exists, the content of the `upsert`
element will be used to index the fresh doc:

View File

@ -1,11 +0,0 @@
[[java-facets]]
== Facets
Faceted search refers to a way to explore large amounts of data by displaying
summaries about various partitions of the data and later allowing to narrow
the navigation to a specific partition.
In Elasticsearch, `facets` are also the name of a feature that allowed to
compute these summaries. `facets` have been replaced by
<<java-aggs, aggregations>> in Elasticsearch 1.0, which are a superset
of facets.

View File

@ -11,7 +11,7 @@ operations are completely asynchronous in nature (either accepts a
listener, or returns a future).
Additionally, operations on a client may be accumulated and executed in
<<bulk,Bulk>>.
<<java-docs-bulk,Bulk>>.
Note, all the APIs are exposed through the
Java API (actually, the Java API is used internally to execute them).
@ -80,29 +80,16 @@ You should define a `module.xml` file like this:
include::client.asciidoc[]
include::index_.asciidoc[]
include::get.asciidoc[]
include::delete.asciidoc[]
include::update.asciidoc[]
include::bulk.asciidoc[]
include::docs.asciidoc[]
include::search.asciidoc[]
include::count.asciidoc[]
include::delete-by-query.asciidoc[]
include::facets.asciidoc[]
include::aggs.asciidoc[]
include::percolate.asciidoc[]
include::query-dsl-queries.asciidoc[]
include::query-dsl-filters.asciidoc[]
include::query-dsl.asciidoc[]
include::indexed-scripts.asciidoc[]

View File

@ -1,559 +0,0 @@
[[query-dsl-filters]]
== Query DSL - Filters
elasticsearch provides a full Java query DSL in a similar manner to the
REST {ref}/query-dsl.html[Query DSL]. The factory for filter
builders is `FilterBuilders`.
Once your query is ready, you can use the <<search,Search API>>.
See also how to build <<query-dsl-queries,Queries>>.
To use `QueryBuilders` or `FilterBuilders` just import them in your class:
[source,java]
--------------------------------------------------
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.elasticsearch.index.query.FilterBuilders.*;
--------------------------------------------------
Note that you can easily print (aka debug) JSON generated queries using
`toString()` method on `FilterBuilder` object.
[[and-filter]]
=== And Filter
See {ref}/query-dsl-and-filter.html[And Filter]
[source,java]
--------------------------------------------------
FilterBuilder filter = andFilter(
rangeFilter("postDate").from("2010-03-01").to("2010-04-01"), <1>
prefixFilter("name.second", "ba")); <1>
--------------------------------------------------
<1> filters
Note that you can cache the result using
`AndFilterBuilder#cache(boolean)` method. See <<query-dsl-filters-caching>>.
[[bool-filter]]
=== Bool Filter
See {ref}/query-dsl-bool-filter.html[Bool Filter]
[source,java]
--------------------------------------------------
FilterBuilder filter = boolFilter()
.must(termFilter("tag", "wow")) <1>
.mustNot(rangeFilter("age").from("10").to("20")) <2>
.should(termFilter("tag", "sometag")) <3>
.should(termFilter("tag", "sometagtag")); <3>
--------------------------------------------------
<1> must filter
<2> must not filter
<3> should filter
Note that you can cache the result using
`BoolFilterBuilder#cache(boolean)` method. See <<query-dsl-filters-caching>>.
[[exists-filter]]
=== Exists Filter
See {ref}/query-dsl-exists-filter.html[Exists Filter].
[source,java]
--------------------------------------------------
FilterBuilder filter = existsFilter("user"); <1>
--------------------------------------------------
<1> field
[[ids-filter]]
=== Ids Filter
See {ref}/query-dsl-ids-filter.html[IDs Filter]
[source,java]
--------------------------------------------------
FilterBuilder filter = idsFilter("my_type", "type2")
.addIds("1", "4", "100");
FilterBuilder filter = idsFilter() <1>
.addIds("1", "4", "100");
--------------------------------------------------
<1> type is optional
[[limit-filter]]
=== Limit Filter
See {ref}/query-dsl-limit-filter.html[Limit Filter]
[source,java]
--------------------------------------------------
FilterBuilder filter = limitFilter(100); <1>
--------------------------------------------------
<1> number of documents per shard
[[type-filter]]
=== Type Filter
See {ref}/query-dsl-type-filter.html[Type Filter]
[source,java]
--------------------------------------------------
FilterBuilder filter = typeFilter("my_type"); <1>
--------------------------------------------------
<1> type
[[geo-bbox-filter]]
=== Geo Bounding Box Filter
See {ref}/query-dsl-geo-bounding-box-filter.html[Geo
Bounding Box Filter]
[source,java]
--------------------------------------------------
FilterBuilder filter = geoBoundingBoxFilter("pin.location") <1>
.topLeft(40.73, -74.1) <2>
.bottomRight(40.717, -73.99); <3>
--------------------------------------------------
<1> field
<2> bounding box top left point
<3> bounding box bottom right point
Note that you can cache the result using
`GeoBoundingBoxFilterBuilder#cache(boolean)` method. See
<<query-dsl-filters-caching>>.
[[geo-distance-filter]]
=== GeoDistance Filter
See {ref}/query-dsl-geo-distance-filter.html[Geo
Distance Filter]
[source,java]
--------------------------------------------------
FilterBuilder filter = geoDistanceFilter("pin.location") <1>
.point(40, -70) <2>
.distance(200, DistanceUnit.KILOMETERS) <3>
.optimizeBbox("memory") <4>
.geoDistance(GeoDistance.ARC); <5>
--------------------------------------------------
<1> field
<2> 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)
Note that you can cache the result using
`GeoDistanceFilterBuilder#cache(boolean)` method. See
<<query-dsl-filters-caching>>.
[[geo-distance-range-filter]]
=== Geo Distance Range Filter
See {ref}/query-dsl-geo-distance-range-filter.html[Geo
Distance Range Filter]
[source,java]
--------------------------------------------------
FilterBuilder filter = geoDistanceRangeFilter("pin.location") <1>
.point(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)
Note that you can cache the result using
`GeoDistanceRangeFilterBuilder#cache(boolean)` method. See
<<query-dsl-filters-caching>>.
[[geo-poly-filter]]
=== Geo Polygon Filter
See {ref}/query-dsl-geo-polygon-filter.html[Geo Polygon
Filter]
[source,java]
--------------------------------------------------
FilterBuilder filter = geoPolygonFilter("pin.location") <1>
.addPoint(40, -70) <2>
.addPoint(30, -80) <2>
.addPoint(20, -90); <2>
--------------------------------------------------
<1> field
<2> add your polygon of points a document should fall within
Note that you can cache the result using
`GeoPolygonFilterBuilder#cache(boolean)` method. See
<<query-dsl-filters-caching>>.
[[geo-shape-filter]]
=== Geo Shape Filter
See {ref}/query-dsl-geo-shape-filter.html[Geo Shape
Filter]
Note: the `geo_shape` type uses `Spatial4J` and `JTS`, both of which are
optional dependencies. Consequently you must add `Spatial4J` and `JTS`
to your classpath in order to use this type:
[source,xml]
-----------------------------------------------
<dependency>
<groupId>com.spatial4j</groupId>
<artifactId>spatial4j</artifactId>
<version>0.4.1</version> <1>
</dependency>
<dependency>
<groupId>com.vividsolutions</groupId>
<artifactId>jts</artifactId>
<version>1.13</version> <2>
<exclusions>
<exclusion>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
</exclusion>
</exclusions>
</dependency>
-----------------------------------------------
<1> check for updates in http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.spatial4j%22%20AND%20a%3A%22spatial4j%22[Maven Central]
<2> check for updates in http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.vividsolutions%22%20AND%20a%3A%22jts%22[Maven Central]
[source,java]
--------------------------------------------------
// Import Spatial4J shapes
import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.shape.Shape;
import com.spatial4j.core.shape.impl.RectangleImpl;
// Also import ShapeRelation
import org.elasticsearch.common.geo.ShapeRelation;
--------------------------------------------------
[source,java]
--------------------------------------------------
// Shape within another
FilterBuilder filter = geoShapeFilter(
"location", <1>
new RectangleImpl(0,10,0,10,SpatialContext.GEO) <2>
)
.relation(ShapeRelation.WITHIN); <3>
--------------------------------------------------
<1> field
<2> shape
<3> relation
[source,java]
--------------------------------------------------
// Intersect shapes
FilterBuilder filter = geoShapeFilter(
"location", <1>
new PointImpl(0, 0, SpatialContext.GEO) <2>
)
.relation(ShapeRelation.INTERSECTS); <3>
--------------------------------------------------
<1> field
<2> shape
<3> relation
[source,java]
--------------------------------------------------
// Using pre-indexed shapes
FilterBuilder filter = geoShapeFilter(
"location", <1>
"New Zealand", <2>
"countries") <3>
.relation(ShapeRelation.DISJOINT); <4>
--------------------------------------------------
<1> field
<2> indexed shape id
<3> index type of the indexed shapes
<4> relation
[[has-child-parent-filter]]
=== Has Child / Has Parent Filters
See:
* {ref}/query-dsl-has-child-filter.html[Has Child Filter]
* {ref}/query-dsl-has-parent-filter.html[Has Parent Filter]
[source,java]
--------------------------------------------------
// Has Child
QueryBuilder qb = hasChildFilter(
"blog_tag", <1>
termFilter("tag","something") <2>
);
--------------------------------------------------
<1> child type to query against
<2> filter (could be also a query)
[source,java]
--------------------------------------------------
// Has Parent
QueryBuilder qb = hasParentFilter(
"blog", <1>
termFilter("tag","something") <2>
);
--------------------------------------------------
<1> parent type to query against
<2> filter (could be also a query)
[[match-all-filter]]
=== Match All Filter
See {ref}/query-dsl-match-all-filter.html[Match All Filter]
[source,java]
--------------------------------------------------
FilterBuilder filter = matchAllFilter();
--------------------------------------------------
[[missing-filter]]
=== Missing Filter
See {ref}/query-dsl-missing-filter.html[Missing Filter]
[source,java]
--------------------------------------------------
FilterBuilder filter = missingFilter("user") <1>
.existence(true) <2>
.nullValue(true); <3>
--------------------------------------------------
<1> field
<2> find missing field that doesnt exist
<3> find missing field with an explicit `null` value
[[not-filter]]
=== Not Filter
See {ref}/query-dsl-not-filter.html[Not Filter]
[source,java]
--------------------------------------------------
FilterBuilder filter = notFilter(
rangeFilter("price").from("1").to("2") <1>
);
--------------------------------------------------
<1> filter
[[or-filter]]
=== Or Filter
See {ref}/query-dsl-or-filter.html[Or Filter]
[source,java]
--------------------------------------------------
FilterBuilder filter = orFilter(
termFilter("name.second", "banon"), <1>
termFilter("name.nick", "kimchy") <1>
);
--------------------------------------------------
<1> filters
Note that you can cache the result using
`OrFilterBuilder#cache(boolean)` method. See <<query-dsl-filters-caching>>.
[[prefix-filter]]
=== Prefix Filter
See {ref}/query-dsl-prefix-filter.html[Prefix Filter]
[source,java]
--------------------------------------------------
FilterBuilder filter = prefixFilter(
"user", <1>
"ki" <2>
);
--------------------------------------------------
<1> field
<2> prefix
Note that you can cache the result using
`PrefixFilterBuilder#cache(boolean)` method. See <<query-dsl-filters-caching>>.
[[query-filter]]
=== Query Filter
See {ref}/query-dsl-query-filter.html[Query Filter]
[source,java]
--------------------------------------------------
FilterBuilder filter = queryFilter(
queryStringQuery("this AND that OR thus") <1>
);
--------------------------------------------------
<1> query you want to wrap as a filter
Note that you can cache the result using
`QueryFilterBuilder#cache(boolean)` method. See <<query-dsl-filters-caching>>.
[[range-filter]]
=== Range Filter
See {ref}/query-dsl-range-filter.html[Range Filter]
[source,java]
--------------------------------------------------
FilterBuilder filter = rangeFilter("age") <1>
.from("10") <2>
.to("20") <3>
.includeLower(true) <4>
.includeUpper(false); <5>
--------------------------------------------------
<1> field
<2> from
<3> to
<4> include lower value means that `from` is `gt` when `false` or `gte` when `true`
<5> include upper value means that `to` is `lt` when `false` or `lte` when `true`
[source,java]
--------------------------------------------------
// A simplified form using gte, gt, lt or lte
FilterBuilder filter = rangeFilter("age") <1>
.gte("10") <2>
.lt("20"); <3>
--------------------------------------------------
<1> field
<2> set `from` to 10 and `includeLower` to true
<3> set `to` to 20 and `includeUpper` to false
Note that you can ask not to cache the result using
`RangeFilterBuilder#cache(boolean)` method. See <<query-dsl-filters-caching>>.
[[script-filter]]
=== Script Filter
See {ref}/query-dsl-script-filter.html[Script Filter]
[source,java]
--------------------------------------------------
FilterBuilder filter = scriptFilter(
"doc['age'].value > param1" <1>
).addParam("param1", 10); <2>
--------------------------------------------------
<1> script to execute
<2> parameters
Note that you can cache the result using
`ScriptFilterBuilder#cache(boolean)` method. See <<query-dsl-filters-caching>>.
[[term-filter]]
=== Term Filter
See {ref}/query-dsl-term-filter.html[Term Filter]
[source,java]
--------------------------------------------------
FilterBuilder filter = termFilter(
"user", <1>
"kimchy" <2>
);
--------------------------------------------------
<1> field
<2> value
Note that you can ask not to cache the result using
`TermFilterBuilder#cache(boolean)` method. See <<query-dsl-filters-caching>>.
[[terms-filter]]
=== Terms Filter
See {ref}/query-dsl-terms-filter.html[Terms Filter]
[source,java]
--------------------------------------------------
FilterBuilder filter = termsFilter(
"user", <1>
"kimchy", <2>
"elasticsearch" <2>
)
.execution("plain"); <3>
--------------------------------------------------
<1> field
<2> terms
<3> execution mode: could be `plain`, `fielddata`, `bool`, `and`, `or`, `bool_nocache`, `and_nocache` or `or_nocache`
Note that you can ask not to cache the result using
`TermsFilterBuilder#cache(boolean)` method. See <<query-dsl-filters-caching>>.
[[nested-filter]]
=== Nested Filter
See {ref}/query-dsl-nested-filter.html[Nested Filter]
[source,java]
--------------------------------------------------
FilterBuilder filter = nestedFilter("obj1", <1>
boolFilter() <2>
.must(termFilter("obj1.name", "blue"))
.must(rangeFilter("obj1.count").gt(5))
);
--------------------------------------------------
<1> path to nested document
<2> filter
Note that you can ask not to cache the result using
`NestedFilterBuilder#cache(boolean)` method. See <<query-dsl-filters-caching>>.
[[query-dsl-filters-caching]]
=== Caching
By default, some filters are cached or not cached. You can have a fine
tuning control using `cache(boolean)` method when exists. For example:
[source,java]
--------------------------------------------------
FilterBuilder filter = andFilter(
rangeFilter("postDate").from("2010-03-01").to("2010-04-01"),
prefixFilter("name.second", "ba")
)
.cache(true); <1>
--------------------------------------------------
<1> force caching filter

View File

@ -1,542 +0,0 @@
[[query-dsl-queries]]
== Query DSL - Queries
elasticsearch provides a full Java query dsl in a similar manner to the
REST {ref}/query-dsl.html[Query DSL]. The factory for query
builders is `QueryBuilders`. Once your query is ready, you can use the
<<search,Search API>>.
See also how to build <<query-dsl-filters,Filters>>
To use `QueryBuilders` or `FilterBuilders` just import them in your class:
[source,java]
--------------------------------------------------
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.elasticsearch.index.query.FilterBuilders.*;
--------------------------------------------------
Note that you can easily print (aka debug) JSON generated queries using
`toString()` method on `QueryBuilder` object.
The `QueryBuilder` can then be used with any API that accepts a query,
such as `count` and `search`.
[[match]]
=== Match Query
See {ref}/query-dsl-match-query.html[Match Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = matchQuery(
"name", <1>
"kimchy elasticsearch" <2>
);
--------------------------------------------------
<1> field
<2> text
[[multimatch]]
=== MultiMatch Query
See {ref}/query-dsl-multi-match-query.html[MultiMatch
Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = multiMatchQuery(
"kimchy elasticsearch", <1>
"user", "message" <2>
);
--------------------------------------------------
<1> text
<2> fields
[[bool]]
=== Boolean Query
See {ref}/query-dsl-bool-query.html[Boolean Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = boolQuery()
.must(termQuery("content", "test1")) <1>
.must(termQuery("content", "test4")) <1>
.mustNot(termQuery("content", "test2")) <2>
.should(termQuery("content", "test3")); <3>
--------------------------------------------------
<1> must query
<2> must not query
<3> should query
[[boosting]]
=== Boosting Query
See {ref}/query-dsl-boosting-query.html[Boosting Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = boostingQuery()
.positive(termQuery("name","kimchy")) <1>
.negative(termQuery("name","dadoonet")) <2>
.negativeBoost(0.2f); <3>
--------------------------------------------------
<1> query that will promote documents
<2> query that will demote documents
<3> negative boost
[[ids]]
=== IDs Query
See {ref}/query-dsl-ids-query.html[IDs Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = idsQuery().ids("1", "2"); <1>
--------------------------------------------------
<1> document ids
[[constant-score]]
=== Constant Score Query
See {ref}/query-dsl-constant-score-query.html[Constant
Score Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = constantScoreQuery(
termFilter("name","kimchy") <1>
)
.boost(2.0f); <2>
--------------------------------------------------
<1> you can use a filter
<2> filter score
[source,java]
--------------------------------------------------
QueryBuilder qb = constantScoreQuery(
termQuery("name","kimchy") <1>
)
.boost(2.0f); <2>
--------------------------------------------------
<1> you can use a query
<2> query score
[[dismax]]
=== Disjunction Max Query
See {ref}/query-dsl-dis-max-query.html[Disjunction Max
Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = disMaxQuery()
.add(termQuery("name","kimchy")) <1>
.add(termQuery("name","elasticsearch")) <2>
.boost(1.2f) <3>
.tieBreaker(0.7f); <4>
--------------------------------------------------
<1> add your queries
<2> add your queries
<3> boost factor
<4> tie breaker
[[flt]]
=== Fuzzy Like This (Field) Query (flt and flt_field)
See:
* {ref}/query-dsl-flt-query.html[Fuzzy Like This Query]
* {ref}/query-dsl-flt-field-query.html[Fuzzy Like This Field Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = fuzzyLikeThisQuery("name.first", "name.last") <1>
.likeText("text like this one") <2>
.maxQueryTerms(12); <3>
--------------------------------------------------
<1> fields
<2> text
<3> max num of Terms in generated queries
[source,java]
--------------------------------------------------
QueryBuilder qb = fuzzyLikeThisFieldQuery("name.first") <1>
.likeText("text like this one") <2>
.maxQueryTerms(12); <3>
--------------------------------------------------
<1> field
<2> text
<3> max num of Terms in generated queries
[[fuzzy]]
=== FuzzyQuery
See {ref}/query-dsl-fuzzy-query.html[Fuzzy Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = fuzzyQuery(
"name", <1>
"kimzhy" <2>
);
--------------------------------------------------
<1> field
<2> text
[[has-child-parent]]
=== Has Child / Has Parent
See:
* {ref}/query-dsl-has-child-query.html[Has Child Query]
* {ref}/query-dsl-has-parent-query.html[Has Parent]
[source,java]
--------------------------------------------------
// Has Child
QueryBuilder qb = hasChildQuery(
"blog_tag", <1>
termQuery("tag","something") <2>
);
--------------------------------------------------
<1> child type to query against
<2> query (could be also a filter)
// Has Parent
[source,java]
--------------------------------------------------
QueryBuilder qb = hasParentQuery(
"blog", <1>
termQuery("tag","something") <2>
);
--------------------------------------------------
<1> parent type to query against
<2> query (could be also a filter)
[[match-all]]
=== MatchAll Query
See {ref}/query-dsl-match-all-query.html[Match All
Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = matchAllQuery();
--------------------------------------------------
[[mlt]]
=== More Like This Query (mlt)
See:
* {ref}/query-dsl-mlt-query.html[More Like This Query]
[source,java]
--------------------------------------------------
// mlt Query
QueryBuilder qb = moreLikeThisQuery("name.first", "name.last") <1>
.likeText("text like this one") <2>
.minTermFreq(1) <3>
.maxQueryTerms(12); <4>
--------------------------------------------------
<1> fields
<2> text
<3> ignore threshold
<4> max num of Terms in generated queries
[[prefix]]
=== Prefix Query
See {ref}/query-dsl-prefix-query.html[Prefix Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = prefixQuery(
"brand", <1>
"heine" <2>
);
--------------------------------------------------
<1> field
<2> prefix
[[query-string]]
=== QueryString Query
See {ref}/query-dsl-query-string-query.html[QueryString Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = queryStringQuery("+kimchy -elasticsearch"); <1>
--------------------------------------------------
<1> text
[[java-range]]
=== Range Query
See {ref}/query-dsl-range-query.html[Range Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = rangeQuery("price") <1>
.from(5) <2>
.to(10) <3>
.includeLower(true) <4>
.includeUpper(false); <5>
--------------------------------------------------
<1> field
<2> from
<3> to
<4> include lower value means that `from` is `gt` when `false` or `gte` when `true`
<5> include upper value means that `to` is `lt` when `false` or `lte` when `true`
=== Span Queries (first, near, not, or, term)
See:
* {ref}/query-dsl-span-term-query.html[Span Term Query]
* {ref}/query-dsl-span-first-query.html[Span First Query]
* {ref}/query-dsl-span-near-query.html[Span Near Query]
* {ref}/query-dsl-span-not-query.html[Span Not Query]
* {ref}/query-dsl-span-or-query.html[Span Or Query]
[source,java]
--------------------------------------------------
// Span Term
QueryBuilder qb = spanTermQuery(
"user", <1>
"kimchy" <2>
);
--------------------------------------------------
<1> field
<2> value
[source,java]
--------------------------------------------------
// Span First
QueryBuilder qb = spanFirstQuery(
spanTermQuery("user", "kimchy"), <1>
3 <2>
);
--------------------------------------------------
<1> query
<2> max end position
[source,java]
--------------------------------------------------
// Span Near
QueryBuilder qb = spanNearQuery()
.clause(spanTermQuery("field","value1")) <1>
.clause(spanTermQuery("field","value2")) <1>
.clause(spanTermQuery("field","value3")) <1>
.slop(12) <2>
.inOrder(false) <3>
.collectPayloads(false); <4>
--------------------------------------------------
<1> span term queries
<2> slop factor: the maximum number of intervening unmatched positions
<3> whether matches are required to be in-order
<4> collect payloads or not
[source,java]
--------------------------------------------------
// Span Not
QueryBuilder qb = spanNotQuery()
.include(spanTermQuery("field","value1")) <1>
.exclude(spanTermQuery("field","value2")); <2>
--------------------------------------------------
<1> span query whose matches are filtered
<2> span query whose matches must not overlap those returned
[source,java]
--------------------------------------------------
// Span Or
QueryBuilder qb = spanOrQuery()
.clause(spanTermQuery("field","value1")) <1>
.clause(spanTermQuery("field","value2")) <1>
.clause(spanTermQuery("field","value3")); <1>
--------------------------------------------------
<1> span term queries
[[term]]
=== Term Query
See {ref}/query-dsl-term-query.html[Term Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = termQuery(
"name", <1>
"kimchy"); <2>
--------------------------------------------------
<1> field
<2> value
[[java-terms]]
=== Terms Query
See {ref}/query-dsl-terms-query.html[Terms Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = termsQuery("tags", <1>
"blue", "pill") <2>
.minimumMatch(1); <3>
--------------------------------------------------
<1> field
<2> values
<3> how many terms must match at least
[[wildcard]]
=== Wildcard Query
See {ref}/query-dsl-wildcard-query.html[Wildcard Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = wildcardQuery("user", "k?mc*");
--------------------------------------------------
[[nested]]
=== Nested Query
See {ref}/query-dsl-nested-query.html[Nested Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = nestedQuery(
"obj1", <1>
boolQuery() <2>
.must(matchQuery("obj1.name", "blue"))
.must(rangeQuery("obj1.count").gt(5))
)
.scoreMode("avg"); <3>
--------------------------------------------------
<1> path to nested document
<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`
[[indices]]
=== Indices Query
See {ref}/query-dsl-indices-query.html[Indices Query]
[source,java]
--------------------------------------------------
// Using another query when no match for the main one
QueryBuilder qb = indicesQuery(
termQuery("tag", "wow"), <1>
"index1", "index2" <2>
)
.noMatchQuery(termQuery("tag", "kow")); <3>
--------------------------------------------------
<1> query to be executed on selected indices
<2> selected indices
<3> query to be executed on non matching indices
[source,java]
--------------------------------------------------
// Using all (match all) or none (match no documents)
QueryBuilder qb = indicesQuery(
termQuery("tag", "wow"), <1>
"index1", "index2" <2>
)
.noMatchQuery("all"); <3>
--------------------------------------------------
<1> query to be executed on selected indices
<2> selected indices
<3> `none` (to match no documents), and `all` (to match all documents). Defaults to `all`.
[[geo-shape]]
=== GeoShape Query
See {ref}/query-dsl-geo-shape-query.html[GeoShape Query]
Note: the `geo_shape` type uses `Spatial4J` and `JTS`, both of which are
optional dependencies. Consequently you must add `Spatial4J` and `JTS`
to your classpath in order to use this type:
[source,xml]
--------------------------------------------------
<dependency>
<groupId>com.spatial4j</groupId>
<artifactId>spatial4j</artifactId>
<version>0.4.1</version> <1>
</dependency>
<dependency>
<groupId>com.vividsolutions</groupId>
<artifactId>jts</artifactId>
<version>1.13</version> <2>
<exclusions>
<exclusion>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
</exclusion>
</exclusions>
</dependency>
--------------------------------------------------
<1> check for updates in http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.spatial4j%22%20AND%20a%3A%22spatial4j%22[Maven Central]
<2> check for updates in http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.vividsolutions%22%20AND%20a%3A%22jts%22[Maven Central]
[source,java]
--------------------------------------------------
// Import Spatial4J shapes
import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.shape.Shape;
import com.spatial4j.core.shape.impl.RectangleImpl;
// Also import ShapeRelation
import org.elasticsearch.common.geo.ShapeRelation;
--------------------------------------------------
[source,java]
--------------------------------------------------
// Shape within another
QueryBuilder qb = geoShapeQuery(
"location", <1>
new RectangleImpl(0,10,0,10,SpatialContext.GEO) <2>
)
.relation(ShapeRelation.WITHIN); <3>
--------------------------------------------------
<1> field
<2> shape
<3> relation
[source,java]
--------------------------------------------------
// Intersect shapes
QueryBuilder qb = geoShapeQuery(
"location", <1>
new PointImpl(0, 0, SpatialContext.GEO) <2>
)
.relation(ShapeRelation.INTERSECTS); <3>
--------------------------------------------------
<1> field
<2> shape
<3> relation
[source,java]
--------------------------------------------------
// Using pre-indexed shapes
QueryBuilder qb = geoShapeQuery(
"location", <1>
"New Zealand", <2>
"countries") <3>
.relation(ShapeRelation.DISJOINT); <4>
--------------------------------------------------
<1> field
<2> indexed shape id
<3> index type of the indexed shapes
<4> relation

View File

@ -0,0 +1,38 @@
[[java-query-dsl]]
== Query DSL
Elasticsearch provides a full Java query dsl in a similar manner to the
REST {ref}/query-dsl.html[Query DSL]. The factory for query
builders is `QueryBuilders`. Once your query is ready, you can use the
<<java-search,Search API>>.
To use `QueryBuilders` just import them in your class:
[source,java]
--------------------------------------------------
import static org.elasticsearch.index.query.QueryBuilders.*;
--------------------------------------------------
Note that you can easily print (aka debug) JSON generated queries using
`toString()` method on `QueryBuilder` object.
The `QueryBuilder` can then be used with any API that accepts a query,
such as `count` and `search`.
include::query-dsl/match-all-query.asciidoc[]
include::query-dsl/full-text-queries.asciidoc[]
include::query-dsl/term-level-queries.asciidoc[]
include::query-dsl/compound-queries.asciidoc[]
include::query-dsl/joining-queries.asciidoc[]
include::query-dsl/geo-queries.asciidoc[]
include::query-dsl/special-queries.asciidoc[]
include::query-dsl/span-queries.asciidoc[]

View File

@ -0,0 +1,15 @@
[[java-query-dsl-and-query]]
==== And Query
deprecated[2.0.0, Use the `bool` query instead]
See {ref}/query-dsl-and-query.html[And Query]
[source,java]
--------------------------------------------------
QueryBuilder query = andQuery(
rangeQuery("postDate").from("2010-03-01").to("2010-04-01"), <1>
prefixQuery("name.second", "ba")); <1>
--------------------------------------------------
<1> queries

View File

@ -0,0 +1,18 @@
[[java-query-dsl-bool-query]]
==== Bool Query
See {ref}/query-dsl-bool-query.html[Bool Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = boolQuery()
.must(termQuery("content", "test1")) <1>
.must(termQuery("content", "test4")) <1>
.mustNot(termQuery("content", "test2")) <2>
.should(termQuery("content", "test3")); <3>
--------------------------------------------------
<1> must query
<2> must not query
<3> should query

View File

@ -0,0 +1,16 @@
[[java-query-dsl-boosting-query]]
==== Boosting Query
See {ref}/query-dsl-boosting-query.html[Boosting Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = boostingQuery()
.positive(termQuery("name","kimchy")) <1>
.negative(termQuery("name","dadoonet")) <2>
.negativeBoost(0.2f); <3>
--------------------------------------------------
<1> query that will promote documents
<2> query that will demote documents
<3> negative boost

View File

@ -0,0 +1,12 @@
[[java-query-dsl-common-terms-query]]
==== Common Terms Query
See {ref}/query-dsl-common-terms-query.html[Common Terms Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = commonTermsQuery("name", <1>
"kimchy"); <2>
--------------------------------------------------
<1> field
<2> value

View File

@ -0,0 +1,69 @@
[[java-compound-queries]]
=== Compound queries
Compound queries wrap other compound or leaf queries, either to combine their
results and scores, to change their behaviour, or to switch from query to
filter context.
The queries in this group are:
<<java-query-dsl-constant-score-query,`constant_score` query>>::
A query which wraps another query, but executes it in filter context. All
matching documents are given the same ``constant'' `_score`.
<<java-query-dsl-bool-query,`bool` query>>::
The default query for combining multiple leaf or compound query clauses, as
`must`, `should`, `must_not`, or `filter` clauses. The `must` and `should`
clauses have their scores combined -- the more matching clauses, the better --
while the `must_not` and `filter` clauses are executed in filter context.
<<java-query-dsl-dis-max-query,`dis_max` query>>::
A query which accepts multiple queries, and returns any documents which match
any of the query clauses. While the `bool` query combines the scores from all
matching queries, the `dis_max` query uses the score of the single best-
matching query clause.
<<java-query-dsl-function-score-query,`function_score` query>>::
Modify the scores returned by the main query with functions to take into
account factors like popularity, recency, distance, or custom algorithms
implemented with scripting.
<<java-query-dsl-boosting-query,`boosting` query>>::
Return documents which match a `positive` query, but reduce the score of
documents which also match a `negative` query.
<<java-query-dsl-indices-query,`indices` query>>::
Execute one query for the specified indices, and another for other indices.
<<java-query-dsl-and-query,`and`>>, <<java-query-dsl-or-query,`or`>>, <<java-query-dsl-not-query,`not`>>::
Synonyms for the `bool` query.
<<java-query-dsl-filtered-query,`filtered` query>>::
Combine a query clause in query context with another in filter context. deprecated[2.0.0,Use the `bool` query instead]
<<java-query-dsl-limit-query,`limit` query>>::
Limits the number of documents examined per shard. deprecated[1.6.0]
include::constant-score-query.asciidoc[]
include::bool-query.asciidoc[]
include::dis-max-query.asciidoc[]
include::function-score-query.asciidoc[]
include::boosting-query.asciidoc[]
include::indices-query.asciidoc[]
include::and-query.asciidoc[]
include::not-query.asciidoc[]
include::or-query.asciidoc[]
include::filtered-query.asciidoc[]
include::limit-query.asciidoc[]

View File

@ -0,0 +1,14 @@
[[java-query-dsl-constant-score-query]]
==== Constant Score Query
See {ref}/query-dsl-constant-score-query.html[Constant Score Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = constantScoreQuery(
termQuery("name","kimchy") <1>
)
.boost(2.0f); <2>
--------------------------------------------------
<1> your query
<2> query score

View File

@ -0,0 +1,17 @@
[[java-query-dsl-dis-max-query]]
==== Dis Max Query
See {ref}/query-dsl-dis-max-query.html[Dis Max Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = disMaxQuery()
.add(termQuery("name", "kimchy")) <1>
.add(termQuery("name", "elasticsearch")) <2>
.boost(1.2f) <3>
.tieBreaker(0.7f); <4>
--------------------------------------------------
<1> add your queries
<2> add your queries
<3> boost factor
<4> tie breaker

View File

@ -0,0 +1,11 @@
[[java-query-dsl-exists-query]]
==== Exists Query
See {ref}/query-dsl-exists-query.html[Exists Query].
[source,java]
--------------------------------------------------
QueryBuilder qb = existsQuery("name"); <1>
--------------------------------------------------
<1> field

View File

@ -0,0 +1,17 @@
[[java-query-dsl-filtered-query]]
==== Filtered Query
deprecated[2.0.0, Use the `bool` query instead with a `must` clause for the query and a `filter` clause for the filter]
See {ref}/query-dsl-filtered-query.html[Filtered Query].
[source,java]
--------------------------------------------------
QueryBuilder qb = filteredQuery(
matchQuery("name", "kimchy"), <1>
rangeQuery("dateOfBirth").from("1900").to("2100") <2>
);
--------------------------------------------------
<1> query which will be used for scoring
<2> query which will only be used for filtering the result set

View File

@ -0,0 +1,44 @@
[[java-full-text-queries]]
=== Full text queries
The high-level full text queries are usually used for running full text
queries on full text fields like the body of an email. They understand how the
field being queried is analyzed and will apply each field's
`analyzer` (or `search_analyzer`) to the query string before executing.
The queries in this group are:
<<java-query-dsl-match-query,`match` query>>::
The standard query for performing full text queries, including fuzzy matching
and phrase or proximity queries.
<<java-query-dsl-multi-match-query,`multi_match` query>>::
The multi-field version of the `match` query.
<<java-query-dsl-common-terms-query,`common_terms` query>>::
A more specialized query which gives more preference to uncommon words.
<<java-query-dsl-query-string-query,`query_string` query>>::
Supports the compact Lucene query string syntax,
allowing you to specify AND|OR|NOT conditions and multi-field search
within a single query string. For expert users only.
<<java-query-dsl-simple-query-string-query,`simple_query_string`>>::
A simpler, more robust version of the `query_string` syntax suitable
for exposing directly to users.
include::match-query.asciidoc[]
include::multi-match-query.asciidoc[]
include::common-terms-query.asciidoc[]
include::query-string-query.asciidoc[]
include::simple-query-string-query.asciidoc[]

View File

@ -0,0 +1,27 @@
[[java-query-dsl-function-score-query]]
==== Function Score Query
See {ref}/query-dsl-function-score-query.html[Function Score Query].
To use `ScoreFunctionBuilders` just import them in your class:
[source,java]
--------------------------------------------------
import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.*;
--------------------------------------------------
[source,java]
--------------------------------------------------
QueryBuilder qb = functionScoreQuery()
.add(
matchQuery("name", "kimchy"), <1>
randomFunction("ABCDEF") <2>
)
.add(
exponentialDecayFunction("age", 0L, 1L) <3>
);
--------------------------------------------------
<1> Add a first function based on a query
<2> And randomize the score based on a given seed
<3> Add another function based on the age field

View File

@ -0,0 +1,15 @@
[[java-query-dsl-fuzzy-query]]
==== Fuzzy Query
See {ref}/query-dsl-fuzzy-query.html[Fuzzy Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = fuzzyQuery(
"name", <1>
"kimzhy" <2>
);
--------------------------------------------------
<1> field
<2> text

View File

@ -0,0 +1,16 @@
[[java-query-dsl-geo-bounding-box-query]]
==== Geo Bounding Box Query
See {ref}/query-dsl-geo-bounding-box-query.html[Geo Bounding Box Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = geoBoundingBoxQuery("pin.location") <1>
.topLeft(40.73, -74.1) <2>
.bottomRight(40.717, -73.99); <3>
--------------------------------------------------
<1> field
<2> bounding box top left point
<3> bounding box bottom right point

View File

@ -0,0 +1,21 @@
[[java-query-dsl-geo-distance-query]]
==== Geo Distance Query
See {ref}/query-dsl-geo-distance-query.html[Geo Distance Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = geoDistanceQuery("pin.location") <1>
.point(40, -70) <2>
.distance(200, DistanceUnit.KILOMETERS) <3>
.optimizeBbox("memory") <4>
.geoDistance(GeoDistance.ARC); <5>
--------------------------------------------------
<1> field
<2> 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

@ -0,0 +1,26 @@
[[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>
.point(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

@ -0,0 +1,15 @@
[[java-query-dsl-geo-polygon-query]]
==== Geo Polygon Query
See {ref}/query-dsl-geo-polygon-query.html[Geo Polygon Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = geoPolygonQuery("pin.location") <1>
.addPoint(40, -70) <2>
.addPoint(30, -80) <2>
.addPoint(20, -90); <2>
--------------------------------------------------
<1> field
<2> add your polygon of points a document should fall within

View File

@ -0,0 +1,49 @@
[[java-geo-queries]]
=== Geo queries
Elasticsearch supports two types of geo data:
`geo_point` fields which support lat/lon pairs, and
`geo_shape` fields, which support points, lines, circles, polygons, multi-polygons etc.
The queries in this group are:
<<java-query-dsl-geo-shape-query,`geo_shape`>> query::
Find document with geo-shapes which either intersect, are contained by, or
do not interesect with the specified geo-shape.
<<java-query-dsl-geo-bounding-box-query,`geo_bounding_box`>> query::
Finds documents with geo-points that fall into the specified rectangle.
<<java-query-dsl-geo-distance-query,`geo_distance`>> query::
Finds document with geo-points within the specified distance of a central
point.
<<java-query-dsl-geo-distance-range-query,`geo_distance_range`>> query::
Like the `geo_point` query, but the range starts at a specified distance
from the central point.
<<java-query-dsl-geo-polygon-query,`geo_polygon`>> query::
Find documents with geo-points within the specified polygon.
<<java-query-dsl-geohash-cell-query,`geohash_cell`>> query::
Find geo-points whose geohash intersects with the geohash of the specified
point.
include::geo-shape-query.asciidoc[]
include::geo-bounding-box-query.asciidoc[]
include::geo-distance-query.asciidoc[]
include::geo-distance-range-query.asciidoc[]
include::geo-polygon-query.asciidoc[]
include::geohash-cell-query.asciidoc[]

View File

@ -0,0 +1,72 @@
[[java-query-dsl-geo-shape-query]]
==== GeoShape Query
See {ref}/query-dsl-geo-shape-query.html[Geo Shape Query]
Note: the `geo_shape` type uses `Spatial4J` and `JTS`, both of which are
optional dependencies. Consequently you must add `Spatial4J` and `JTS`
to your classpath in order to use this type:
[source,xml]
-----------------------------------------------
<dependency>
<groupId>com.spatial4j</groupId>
<artifactId>spatial4j</artifactId>
<version>0.4.1</version> <1>
</dependency>
<dependency>
<groupId>com.vividsolutions</groupId>
<artifactId>jts</artifactId>
<version>1.13</version> <2>
<exclusions>
<exclusion>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
</exclusion>
</exclusions>
</dependency>
-----------------------------------------------
<1> check for updates in http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.spatial4j%22%20AND%20a%3A%22spatial4j%22[Maven Central]
<2> check for updates in http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.vividsolutions%22%20AND%20a%3A%22jts%22[Maven Central]
[source,java]
--------------------------------------------------
// Import ShapeRelationn and ShapeBuilder
import org.elasticsearch.common.geo.ShapeRelation;
import org.elasticsearch.common.geo.builders.ShapeBuilder;
--------------------------------------------------
[source,java]
--------------------------------------------------
QueryBuilder qb = geoShapeQuery(
"pin.location", <1>
ShapeBuilder.newMultiPoint() <2>
.point(0, 0)
.point(0, 10)
.point(10, 10)
.point(10, 0)
.point(0, 0),
ShapeRelation.WITHIN); <3>
--------------------------------------------------
<1> field
<2> shape
<3> relation can be `ShapeRelation.WITHIN`, `ShapeRelation.INTERSECTS` or `ShapeRelation.DISJOINT`
[source,java]
--------------------------------------------------
// Using pre-indexed shapes
QueryBuilder qb = geoShapeQuery(
"pin.location", <1>
"DEU", <2>
"countries", <3>
ShapeRelation.WITHIN) <4>
.indexedShapeIndex("shapes") <5>
.indexedShapePath("location"); <6>
--------------------------------------------------
<1> field
<2> The ID of the document that containing the pre-indexed shape.
<3> Index type where the pre-indexed shape is.
<4> relation
<5> Name of the index where the pre-indexed shape is. Defaults to 'shapes'.
<6> The field specified as path containing the pre-indexed shape. Defaults to 'shape'.

View File

@ -0,0 +1,17 @@
[[java-query-dsl-geohash-cell-query]]
==== Geohash Cell Query
See {ref}/query-dsl-geohash-cell-query.html[Geohash Cell Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = geoHashCellQuery("pin.location", <1>
new GeoPoint(13.4080, 52.5186)) <2>
.neighbors(true) <3>
.precision(3); <4>
--------------------------------------------------
<1> field
<2> point. Can also be a hash like `u30`
<3> The `neighbors` option of the filter offers the possibility to filter cells
next to the given cell.
<4> precision level

View File

@ -0,0 +1,15 @@
[[java-query-dsl-has-child-query]]
==== Has Child Query
See {ref}/query-dsl-has-child-query.html[Has Child Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = hasChildQuery(
"blog_tag", <1>
termQuery("tag","something") <2>
);
--------------------------------------------------
<1> child type to query against
<2> query

View File

@ -0,0 +1,14 @@
[[java-query-dsl-has-parent-query]]
==== Has Parent Query
See {ref}/query-dsl-has-parent-query.html[Has Parent]
[source,java]
--------------------------------------------------
QueryBuilder qb = hasParentQuery(
"blog", <1>
termQuery("tag","something") <2>
);
--------------------------------------------------
<1> parent type to query against
<2> query

View File

@ -0,0 +1,16 @@
[[java-query-dsl-ids-query]]
==== Ids Query
See {ref}/query-dsl-ids-query.html[Ids Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = idsQuery("my_type", "type2")
.addIds("1", "4", "100");
QueryBuilder qb = idsQuery() <1>
.addIds("1", "4", "100");
--------------------------------------------------
<1> type is optional

View File

@ -0,0 +1,29 @@
[[java-query-dsl-indices-query]]
==== Indices Query
See {ref}/query-dsl-indices-query.html[Indices Query]
[source,java]
--------------------------------------------------
// Using another query when no match for the main one
QueryBuilder qb = indicesQuery(
termQuery("tag", "wow"), <1>
"index1", "index2" <2>
).noMatchQuery(termQuery("tag", "kow")); <3>
--------------------------------------------------
<1> query to be executed on selected indices
<2> selected indices
<3> query to be executed on non matching indices
[source,java]
--------------------------------------------------
// Using all (match all) or none (match no documents)
QueryBuilder qb = indicesQuery(
termQuery("tag", "wow"), <1>
"index1", "index2" <2>
).noMatchQuery("all"); <3>
--------------------------------------------------
<1> query to be executed on selected indices
<2> selected indices
<3> `none` (to match no documents), and `all` (to match all documents). Defaults to `all`.

View File

@ -0,0 +1,28 @@
[[java-joining-queries]]
=== Joining queries
Performing full SQL-style joins in a distributed system like Elasticsearch is
prohibitively expensive. Instead, Elasticsearch offers two forms of join
which are designed to scale horizontally.
<<java-query-dsl-nested-query,`nested` query>>::
Documents may contains fields of type `nested`. These
fields are used to index arrays of objects, where each object can be queried
(with the `nested` query) as an independent document.
<<java-query-dsl-has-child-query,`has_child`>> and <<java-query-dsl-has-parent-query,`has_parent`>> queries::
A parent-child relationship can exist between two
document types within a single index. The `has_child` query returns parent
documents whose child documents match the specified query, while the
`has_parent` query returns child documents whose parent document matches the
specified query.
include::nested-query.asciidoc[]
include::has-child-query.asciidoc[]
include::has-parent-query.asciidoc[]

View File

@ -0,0 +1,13 @@
[[java-query-dsl-limit-query]]
==== Limit Query
deprecated[1.6.0, Use <<java-search-terminate-after,terminateAfter()>> instead]
See {ref}/query-dsl-limit-query.html[Limit Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = limitQuery(100); <1>
--------------------------------------------------
<1> number of documents per shard

View File

@ -0,0 +1,9 @@
[[java-query-dsl-match-all-query]]
=== Match All Query
See {ref}/query-dsl-match-all-query.html[Match All Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = matchAllQuery();
--------------------------------------------------

View File

@ -0,0 +1,15 @@
[[java-query-dsl-match-query]]
==== Match Query
See {ref}/query-dsl-match-query.html[Match Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = matchQuery(
"name", <1>
"kimchy elasticsearch" <2>
);
--------------------------------------------------
<1> field
<2> text

View File

@ -0,0 +1,15 @@
[[java-query-dsl-missing-query]]
==== Missing Query
See {ref}/query-dsl-missing-query.html[Missing Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = missingQuery("user"); <1>
.existence(true) <2>
.nullValue(true); <3>
--------------------------------------------------
<1> field
<2> find missing field that doesnt exist
<3> find missing field with an explicit `null` value

View File

@ -0,0 +1,17 @@
[[java-query-dsl-mlt-query]]
==== More Like This Query (mlt)
See:
* {ref}/query-dsl-mlt-query.html[More Like This Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = moreLikeThisQuery("name.first", "name.last") <1>
.like("text like this one") <2>
.minTermFreq(1) <3>
.maxQueryTerms(12); <4>
--------------------------------------------------
<1> fields
<2> text
<3> ignore threshold
<4> max num of Terms in generated queries

View File

@ -0,0 +1,14 @@
[[java-query-dsl-multi-match-query]]
==== Multi Match Query
See {ref}/query-dsl-multi-match-query.html[Multi Match Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = multiMatchQuery(
"kimchy elasticsearch", <1>
"user", "message" <2>
);
--------------------------------------------------
<1> text
<2> fields

View File

@ -0,0 +1,18 @@
[[java-query-dsl-nested-query]]
==== Nested Query
See {ref}/query-dsl-nested-query.html[Nested Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = nestedQuery(
"obj1", <1>
boolQuery() <2>
.must(matchQuery("obj1.name", "blue"))
.must(rangeQuery("obj1.count").gt(5))
)
.scoreMode("avg"); <3>
--------------------------------------------------
<1> path to nested document
<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`

View File

@ -0,0 +1,15 @@
[[java-query-dsl-not-query]]
==== Not Query
See {ref}/query-dsl-not-query.html[Not Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = notQuery(
rangeQuery("price").from("1").to("2") <1>
);
--------------------------------------------------
<1> query

View File

@ -0,0 +1,16 @@
[[java-query-dsl-or-query]]
==== Or Query
deprecated[2.0.0, Use the `bool` query instead]
See {ref}/query-dsl-or-query.html[Or Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = orQuery(
rangeQuery("price").from(1).to(2), <1>
matchQuery("name", "joe") <1>
);
--------------------------------------------------
<1> queries

View File

@ -0,0 +1,16 @@
[[java-query-dsl-prefix-query]]
==== Prefix Query
See {ref}/query-dsl-prefix-query.html[Prefix Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = prefixQuery(
"brand", <1>
"heine" <2>
);
--------------------------------------------------
<1> field
<2> prefix

View File

@ -0,0 +1,10 @@
[[java-query-dsl-query-string-query]]
==== Query String Query
See {ref}/query-dsl-query-string-query.html[Query String Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = queryStringQuery("+kimchy -elasticsearch"); <1>
--------------------------------------------------
<1> text

View File

@ -0,0 +1,29 @@
[[java-query-dsl-range-query]]
==== Range Query
See {ref}/query-dsl-range-query.html[Range Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = rangeQuery("price") <1>
.from(5) <2>
.to(10) <3>
.includeLower(true) <4>
.includeUpper(false); <5>
--------------------------------------------------
<1> field
<2> from
<3> to
<4> include lower value means that `from` is `gt` when `false` or `gte` when `true`
<5> include upper value means that `to` is `lt` when `false` or `lte` when `true`
[source,java]
--------------------------------------------------
// A simplified form using gte, gt, lt or lte
QueryBuilder qb = rangeQuery("age") <1>
.gte("10") <2>
.lt("20"); <3>
--------------------------------------------------
<1> field
<2> set `from` to 10 and `includeLower` to `true`
<3> set `to` to 20 and `includeUpper` to `false`

View File

@ -0,0 +1,13 @@
[[java-query-dsl-regexp-query]]
==== Regexp Query
See {ref}/query-dsl-regexp-query.html[Regexp Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = regexpQuery(
"name.first", <1>
"s.*y"); <2>
--------------------------------------------------
<1> field
<2> regexp

View File

@ -0,0 +1,39 @@
[[java-query-dsl-script-query]]
==== Script Query
See {ref}/query-dsl-script-query.html[Script Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = scriptQuery(
new Script("doc['num1'].value > 1") <1>
);
--------------------------------------------------
<1> inlined script
If you have stored on each data node a script named `mygroovyscript.groovy` with:
[source,groovy]
--------------------------------------------------
doc['num1'].value > param1
--------------------------------------------------
You can use it then with:
[source,java]
--------------------------------------------------
QueryBuilder qb = scriptQuery(
new Script(
"mygroovyscript", <1>
ScriptService.ScriptType.FILE, <2>
"groovy", <3>
ImmutableMap.of("param1", 5)) <4>
);
--------------------------------------------------
<1> Script name
<2> Script type: either `ScriptType.FILE`, `ScriptType.INLINE` or `ScriptType.INDEXED`
<3> Scripting engine
<4> Parameters as a `Map` of `<String, Object>`
æ

View File

@ -0,0 +1,10 @@
[[java-query-dsl-simple-query-string-query]]
==== Simple Query String Query
See {ref}/query-dsl-simple-query-string-query.html[Simple Query String Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = simpleQueryStringQuery("+kimchy -elasticsearch"); <1>
--------------------------------------------------
<1> text

View File

@ -0,0 +1,19 @@
[[java-query-dsl-span-containing-query]]
==== Span Containing Query
See {ref}/query-dsl-span-containing-query.html[Span Containing Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = spanContainingQuery()
.little(spanTermQuery("field1","foo")) <1>
.big(spanNearQuery() <2>
.clause(spanTermQuery("field1","bar"))
.clause(spanTermQuery("field1","baz"))
.slop(5)
.inOrder(true)
);
--------------------------------------------------
<1> `little` part
<2> `big` part

View File

@ -0,0 +1,15 @@
[[java-query-dsl-span-first-query]]
==== Span First Query
See {ref}/query-dsl-span-first-query.html[Span First Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = spanFirstQuery(
spanTermQuery("user", "kimchy"), <1>
3 <2>
);
--------------------------------------------------
<1> query
<2> max end position

View File

@ -0,0 +1,14 @@
[[java-query-dsl-span-multi-term-query]]
==== Span Multi Term Query
See {ref}/query-dsl-span-multi-term-query.html[Span Multi Term Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = spanMultiTermQueryBuilder(
prefixQuery("user", "ki") <1>
);
--------------------------------------------------
<1> Can be any builder extending the `MultiTermQueryBuilder` class. For example: `FuzzyQueryBuilder`,
`PrefixQueryBuilder`, `RangeQueryBuilder`, `RegexpQueryBuilder` or `WildcardQueryBuilder`.

View File

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

View File

@ -0,0 +1,14 @@
[[java-query-dsl-span-not-query]]
==== Span Not Query
See {ref}/query-dsl-span-not-query.html[Span Not Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = spanNotQuery()
.include(spanTermQuery("field","value1")) <1>
.exclude(spanTermQuery("field","value2")); <2>
--------------------------------------------------
<1> span query whose matches are filtered
<2> span query whose matches must not overlap those returned

View File

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

View File

@ -0,0 +1,65 @@
[[java-span-queries]]
=== Span queries
Span queries are low-level positional queries which provide expert control
over the order and proximity of the specified terms. These are typically used
to implement very specific queries on legal documents or patents.
Span queries cannot be mixed with non-span queries (with the exception of the `span_multi` query).
The queries in this group are:
<<java-query-dsl-span-term-query,`span_term` query>>::
The equivalent of the <<java-query-dsl-term-query,`term` query>> but for use with
other span queries.
<<java-query-dsl-span-multi-term-query,`span_multi` query>>::
Wraps a <<java-query-dsl-term-query,`term`>>, <<java-query-dsl-range-query,`range`>>,
<<java-query-dsl-prefix-query,`prefix`>>, <<java-query-dsl-wildcard-query,`wildcard`>>,
<<java-query-dsl-regexp-query,`regexp`>>, or <<java-query-dsl-fuzzy-query,`fuzzy`>> query.
<<java-query-dsl-span-first-query,`span_first` query>>::
Accepts another span query whose matches must appear within the first N
positions of the field.
<<java-query-dsl-span-near-query,`span_near` query>>::
Accepts multiple span queries whose matches must be within the specified distance of each other, and possibly in the same order.
<<java-query-dsl-span-or-query,`span_or` query>>::
Combines multiple span queries -- returns documents which match any of the
specified queries.
<<java-query-dsl-span-not-query,`span_not` query>>::
Wraps another span query, and excludes any documents which match that query.
<<java-query-dsl-span-containing-query,`span_containing` query>>::
Accepts a list of span queries, but only returns those spans which also match a second span query.
<<java-query-dsl-span-within-query,`span_within` query>>::
The result from a single span query is returned as long is its span falls
within the spans returned by a list of other span queries.
include::span-term-query.asciidoc[]
include::span-multi-term-query.asciidoc[]
include::span-first-query.asciidoc[]
include::span-near-query.asciidoc[]
include::span-or-query.asciidoc[]
include::span-not-query.asciidoc[]
include::span-containing-query.asciidoc[]
include::span-within-query.asciidoc[]

View File

@ -0,0 +1,15 @@
[[java-query-dsl-span-term-query]]
==== Span Term Query
See {ref}/query-dsl-span-term-query.html[Span Term Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = spanTermQuery(
"user", <1>
"kimchy" <2>
);
--------------------------------------------------
<1> field
<2> value

View File

@ -0,0 +1,18 @@
[[java-query-dsl-span-within-query]]
==== Span Within Query
See {ref}/query-dsl-span-within-query.html[Span Within Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = spanWithinQuery()
.little(spanTermQuery("field1", "foo")) <1>
.big(spanNearQuery() <2>
.clause(spanTermQuery("field1", "bar"))
.clause(spanTermQuery("field1", "baz"))
.slop(5)
.inOrder(true)
);
--------------------------------------------------
<1> `little` part
<2> `big` part

View File

@ -0,0 +1,29 @@
[[java-specialized-queries]]
=== Specialized queries
This group contains queries which do not fit into the other groups:
<<java-query-dsl-mlt-query,`more_like_this` query>>::
This query finds documents which are similar to the specified text, document,
or collection of documents.
<<java-query-dsl-template-query,`template` query>>::
The `template` query accepts a Mustache template (either inline, indexed, or
from a file), and a map of parameters, and combines the two to generate the
final query to execute.
<<java-query-dsl-script-query,`script` query>>::
This query allows a script to act as a filter. Also see the
<<java-query-dsl-function-score-query,`function_score` query>>.
include::mlt-query.asciidoc[]
include::template-query.asciidoc[]
include::script-query.asciidoc[]

View File

@ -0,0 +1,71 @@
[[java-query-dsl-template-query]]
==== Template Query
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}}"
}
}
}
}
--------------------------------------------------
Define your template query:
[source,java]
--------------------------------------------------
QueryBuilder qb = templateQuery(
"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 a special index named `.scripts`:
[source,java]
--------------------------------------------------
client.preparePutIndexedScript("mustache", "template_gender",
"{\n" +
" \"template\" : {\n" +
" \"query\" : {\n" +
" \"match\" : {\n" +
" \"gender\" : \"{{param_gender}}\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}").get();
--------------------------------------------------
To execute an indexed templates, use `ScriptService.ScriptType.INDEXED`:
[source,java]
--------------------------------------------------
QueryBuilder qb = templateQuery(
"gender_template", <1>
ScriptService.ScriptType.INDEXED, <2>
template_params); <3>
--------------------------------------------------
<1> template name
<2> template stored in an index
<3> parameters

View File

@ -0,0 +1,93 @@
[[java-term-level-queries]]
=== Term level queries
While the <<java-full-text-queries,full text queries>> will analyze the query
string before executing, the _term-level queries_ operate on the exact terms
that are stored in the inverted index.
These queries are usually used for structured data like numbers, dates, and
enums, rather than full text fields. Alternatively, they allow you to craft
low-level queries, foregoing the analysis process.
The queries in this group are:
<<java-query-dsl-term-query,`term` query>>::
Find documents which contain the exact term specified in the field
specified.
<<java-query-dsl-terms-query,`terms` query>>::
Find documents which contain any of the exact terms specified in the field
specified.
<<java-query-dsl-range-query,`range` query>>::
Find documents where the field specified contains values (dates, numbers,
or strings) in the range specified.
<<java-query-dsl-exists-query,`exists` query>>::
Find documents where the field specified contains any non-null value.
<<java-query-dsl-missing-query,`missing` query>>::
Find documents where the field specified does is missing or contains only
`null` values.
<<java-query-dsl-prefix-query,`prefix` query>>::
Find documents where the field specified contains terms which being with
the exact prefix specified.
<<java-query-dsl-wildcard-query,`wildcard` query>>::
Find documents where the field specified contains terms which match the
pattern specified, where the pattern supports single character wildcards
(`?`) and multi-character wildcards (`*`)
<<java-query-dsl-regexp-query,`regexp` query>>::
Find documents where the field specified contains terms which match the
regular expression specified.
<<java-query-dsl-fuzzy-query,`fuzzy` query>>::
Find documents where the field specified contains terms which are fuzzily
similar to the specified term. Fuzziness is measured as a
http://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance[Levenshtein edit distance]
of 1 or 2.
<<java-query-dsl-type-query,`type` query>>::
Find documents of the specified type.
<<java-query-dsl-ids-query,`ids` query>>::
Find documents with the specified type and IDs.
include::term-query.asciidoc[]
include::terms-query.asciidoc[]
include::range-query.asciidoc[]
include::exists-query.asciidoc[]
include::missing-query.asciidoc[]
include::prefix-query.asciidoc[]
include::wildcard-query.asciidoc[]
include::regexp-query.asciidoc[]
include::fuzzy-query.asciidoc[]
include::type-query.asciidoc[]
include::ids-query.asciidoc[]

View File

@ -0,0 +1,15 @@
[[java-query-dsl-term-query]]
==== Term Query
See {ref}/query-dsl-term-query.html[Term Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = term(
"name", <1>
"kimchy" <2>
);
--------------------------------------------------
<1> field
<2> text

View File

@ -0,0 +1,12 @@
[[java-query-dsl-terms-query]]
==== Terms Query
See {ref}/query-dsl-terms-query.html[Terms Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = termsQuery("tags", <1>
"blue", "pill"); <2>
--------------------------------------------------
<1> field
<2> values

View File

@ -0,0 +1,10 @@
[[java-query-dsl-type-query]]
==== Type Query
See {ref}/query-dsl-type-query.html[Type Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = typeQuery("my_type"); <1>
--------------------------------------------------
<1> type

View File

@ -0,0 +1,10 @@
[[java-query-dsl-wildcard-query]]
==== Wildcard Query
See {ref}/query-dsl-wildcard-query.html[Wildcard Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = wildcardQuery("user", "k?mc*");
--------------------------------------------------

View File

@ -1,19 +1,15 @@
[[search]]
[[java-search]]
== Search API
The search API allows one to execute a search query and get back search hits
that match the query. It can be executed across one or more indices and
across one or more types. The query can either be provided using the
<<query-dsl-queries,query Java API>> or
the <<query-dsl-filters,filter Java API>>.
The body of the search request is built using the
`SearchSourceBuilder`. Here is an example:
across one or more types. The query can provided using the <<java-query-dsl,query Java API>>.
The body of the search request is built using the `SearchSourceBuilder`. Here is an example:
[source,java]
--------------------------------------------------
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.FilterBuilders.*;
import org.elasticsearch.index.query.QueryBuilders.*;
--------------------------------------------------
@ -22,8 +18,8 @@ import org.elasticsearch.index.query.QueryBuilders.*;
SearchResponse response = client.prepareSearch("index1", "index2")
.setTypes("type1", "type2")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(QueryBuilders.termQuery("multi", "test")) // Query
.setPostFilter(FilterBuilders.rangeFilter("age").from(12).to(18)) // Filter
.setQuery(QueryBuilders.termQuery("multi", "test")) // Query
.setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18)) // Filter
.setFrom(0).setSize(60).setExplain(true)
.execute()
.actionGet();
@ -46,7 +42,7 @@ For more information on the search operation, check out the REST
{ref}/search.html[search] docs.
[[scrolling]]
[[java-search-scrolling]]
=== Using scrolls in Java
Read the {ref}/search-request-scroll.html[scroll documentation]
@ -54,7 +50,6 @@ first!
[source,java]
--------------------------------------------------
import static org.elasticsearch.index.query.FilterBuilders.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
QueryBuilder qb = termQuery("multi", "test");
@ -78,7 +73,7 @@ while (true) {
}
--------------------------------------------------
[[msearch]]
[[java-search-msearch]]
=== MultiSearch API
See {ref}/search-multi-search.html[MultiSearch API Query]
@ -132,69 +127,22 @@ DateHistogram agg2 = sr.getAggregations().get("agg2");
See <<java-aggs,Aggregations Java API>>
documentation for details.
[[java-search-template]]
=== Using Search Templates
See {ref}/search-template.html[Search Template] documentation
[[java-search-terminate-after]]
=== Terminate After
Define your template parameters as a `Map<String,Object>`:
The maximum number of documents to collect for each shard, upon reaching which the query execution will terminate early.
If set, you will be able to check if the operation terminated early by asking for `isTerminatedEarly()` in the
`SearchResponse` onject:
[source,java]
--------------------------------------------------
Map<String, Object> template_params = new HashMap<>();
template_params.put("param_gender", "male");
--------------------------------------------------
SearchResponse sr = client.prepareSearch(INDEX)
.setTerminateAfter(1000) <1>
.get();
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}}"
}
}
}
if (sr.isTerminatedEarly()) {
// We finished early
}
--------------------------------------------------
Execute it with:
[source,java]
--------------------------------------------------
SearchResponse sr = client.prepareSearch()
.setTemplateName("template_gender")
.setTemplateType(ScriptService.ScriptType.FILE)
.setTemplateParams(template_params)
.get();
--------------------------------------------------
You can also store your template in a special index named `.scripts`:
[source,java]
--------------------------------------------------
client.preparePutIndexedScript("mustache", "template_gender",
"{\n" +
" \"template\" : {\n" +
" \"query\" : {\n" +
" \"match\" : {\n" +
" \"gender\" : \"{{param_gender}}\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}").get();
--------------------------------------------------
To execute an indexed templates, use `ScriptService.ScriptType.INDEXED`:
[source,java]
--------------------------------------------------
SearchResponse sr = client.prepareSearch()
.setTemplateName("template_gender")
.setTemplateType(ScriptService.ScriptType.INDEXED)
.setTemplateParams(template_params)
.get();
--------------------------------------------------
<1> Finish after 1000 docs