OpenSearch/docs/java-api/query-dsl-queries.asciidoc

516 lines
15 KiB
Plaintext
Raw Normal View History

[[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` just import them in your class:
[source,java]
--------------------------------------------------
import 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`.
[[match]]
=== Match Query
See {ref}/query-dsl-match-query.html[Match Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = QueryBuilders.matchQuery("name", "kimchy elasticsearch");
--------------------------------------------------
[[multimatch]]
=== MultiMatch Query
See {ref}/query-dsl-multi-match-query.html[MultiMatch
Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = QueryBuilders.multiMatchQuery(
"kimchy elasticsearch", // Text you are looking for
"user", "message" // Fields you query on
);
--------------------------------------------------
[[bool]]
=== Boolean Query
See {ref}/query-dsl-bool-query.html[Boolean Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = QueryBuilders
.boolQuery()
.must(termQuery("content", "test1"))
.must(termQuery("content", "test4"))
.mustNot(termQuery("content", "test2"))
.should(termQuery("content", "test3"));
--------------------------------------------------
[[boosting]]
=== Boosting Query
See {ref}/query-dsl-boosting-query.html[Boosting Query]
[source,java]
--------------------------------------------------
QueryBuilders.boostingQuery()
.positive(QueryBuilders.termQuery("name","kimchy"))
.negative(QueryBuilders.termQuery("name","dadoonet"))
.negativeBoost(0.2f);
--------------------------------------------------
[[ids]]
=== IDs Query
See {ref}/query-dsl-ids-query.html[IDs Query]
[source,java]
--------------------------------------------------
QueryBuilders.idsQuery().ids("1", "2");
--------------------------------------------------
[[custom-score]]
=== Custom Score Query
See {ref}/query-dsl-custom-score-query.html[Custom Score
Query]
[source,java]
--------------------------------------------------
QueryBuilders.customScoreQuery(QueryBuilders.matchAllQuery()) // Your query here
.script("_score * doc['price'].value"); // Your script here
// If the script have parameters, use the same script and provide parameters to it.
QueryBuilders.customScoreQuery(QueryBuilders.matchAllQuery())
.script("_score * doc['price'].value / pow(param1, param2)")
.param("param1", 2)
.param("param2", 3.1);
--------------------------------------------------
[[custom-boost-factor]]
=== Custom Boost Factor Query
See
{ref}/query-dsl-custom-boost-factor-query.html[Custom
Boost Factor Query]
[source,java]
--------------------------------------------------
QueryBuilders.customBoostFactorQuery(QueryBuilders.matchAllQuery()) // Your query
.boostFactor(3.1f);
--------------------------------------------------
[[constant-score]]
=== Constant Score Query
See {ref}/query-dsl-constant-score-query.html[Constant
Score Query]
[source,java]
--------------------------------------------------
// Using with Filters
QueryBuilders.constantScoreQuery(FilterBuilders.termFilter("name","kimchy"))
.boost(2.0f);
// With Queries
QueryBuilders.constantScoreQuery(QueryBuilders.termQuery("name","kimchy"))
.boost(2.0f);
--------------------------------------------------
[[dismax]]
=== Disjunction Max Query
See {ref}/query-dsl-dis-max-query.html[Disjunction Max
Query]
[source,java]
--------------------------------------------------
QueryBuilders.disMaxQuery()
.add(QueryBuilders.termQuery("name","kimchy")) // Your queries
.add(QueryBuilders.termQuery("name","elasticsearch")) // Your queries
.boost(1.2f)
.tieBreaker(0.7f);
--------------------------------------------------
[[field]]
=== Field Query
See {ref}/query-dsl-field-query.html[Field Query]
[source,java]
--------------------------------------------------
QueryBuilders.fieldQuery("name", "+kimchy -dadoonet");
// Note that you can write the same query using queryString query.
QueryBuilders.queryString("+kimchy -dadoonet").field("name");
--------------------------------------------------
[[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]
--------------------------------------------------
// flt Query
QueryBuilders.fuzzyLikeThisQuery("name.first", "name.last") // Fields
.likeText("text like this one") // Text
.maxQueryTerms(12); // Max num of Terms
// in generated queries
// flt_field Query
QueryBuilders.fuzzyLikeThisFieldQuery("name.first") // Only on single field
.likeText("text like this one")
.maxQueryTerms(12);
--------------------------------------------------
[[fuzzy]]
=== FuzzyQuery
See {ref}/query-dsl-fuzzy-query.html[Fuzzy Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = QueryBuilders.fuzzyQuery("name", "kimzhy");
--------------------------------------------------
[[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
QueryBuilders.hasChildQuery("blog_tag",
QueryBuilders.termQuery("tag","something"))
// Has Parent
QueryBuilders.hasParentQuery("blog",
QueryBuilders.termQuery("tag","something"));
--------------------------------------------------
[[match-all]]
=== MatchAll Query
See {ref}/query-dsl-match-all-query.html[Match All
Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = QueryBuilders.matchAllQuery();
--------------------------------------------------
[[mlt]]
=== More Like This (Field) Query (mlt and mlt_field)
See:
* {ref}/query-dsl-mlt-query.html[More Like This Query]
* {ref}/query-dsl-mlt-field-query.html[More Like This Field Query]
[source,java]
--------------------------------------------------
// mlt Query
QueryBuilders.moreLikeThisQuery("name.first", "name.last") // Fields
.likeText("text like this one") // Text
.minTermFreq(1) // Ignore Threshold
.maxQueryTerms(12); // Max num of Terms
// in generated queries
// mlt_field Query
QueryBuilders.moreLikeThisFieldQuery("name.first") // Only on single field
.likeText("text like this one")
.minTermFreq(1)
.maxQueryTerms(12);
--------------------------------------------------
[[prefix]]
=== Prefix Query
See {ref}/query-dsl-prefix-query.html[Prefix Query]
[source,java]
--------------------------------------------------
QueryBuilders.prefixQuery("brand", "heine");
--------------------------------------------------
[[query-string]]
=== QueryString Query
See {ref}/query-dsl-query-string-query.html[QueryString Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = QueryBuilders.queryString("+kimchy -elasticsearch");
--------------------------------------------------
[[range]]
=== Range Query
See {ref}/query-dsl-range-query.html[Range Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = QueryBuilders
.rangeQuery("price")
.from(5)
.to(10)
.includeLower(true)
.includeUpper(false);
--------------------------------------------------
=== Span Queries (first, near, not, or, term)
See:
* {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]
* {ref}/query-dsl-span-term-query.html[Span Term Query]
[source,java]
--------------------------------------------------
// Span First
QueryBuilders.spanFirstQuery(
QueryBuilders.spanTermQuery("user", "kimchy"), // Query
3 // Max End position
);
// Span Near
QueryBuilders.spanNearQuery()
.clause(QueryBuilders.spanTermQuery("field","value1")) // Span Term Queries
.clause(QueryBuilders.spanTermQuery("field","value2"))
.clause(QueryBuilders.spanTermQuery("field","value3"))
.slop(12) // Slop factor
.inOrder(false)
.collectPayloads(false);
// Span Not
QueryBuilders.spanNotQuery()
.include(QueryBuilders.spanTermQuery("field","value1"))
.exclude(QueryBuilders.spanTermQuery("field","value2"));
// Span Or
QueryBuilders.spanOrQuery()
.clause(QueryBuilders.spanTermQuery("field","value1"))
.clause(QueryBuilders.spanTermQuery("field","value2"))
.clause(QueryBuilders.spanTermQuery("field","value3"));
// Span Term
QueryBuilders.spanTermQuery("user","kimchy");
--------------------------------------------------
[[term]]
=== Term Query
See {ref}/query-dsl-term-query.html[Term Query]
[source,java]
--------------------------------------------------
QueryBuilder qb = QueryBuilders.termQuery("name", "kimchy");
--------------------------------------------------
[[terms]]
=== Terms Query
See {ref}/query-dsl-terms-query.html[Terms Query]
[source,java]
--------------------------------------------------
QueryBuilders.termsQuery("tags", // field
"blue", "pill") // values
.minimumMatch(1); // How many terms must match
--------------------------------------------------
[[top-children]]
=== Top Children Query
See {ref}/query-dsl-top-children-query.html[Top Children Query]
[source,java]
--------------------------------------------------
QueryBuilders.topChildrenQuery(
"blog_tag", // field
QueryBuilders.termQuery("tag", "something") // Query
)
.score("max") // max, sum or avg
.factor(5)
.incrementalFactor(2);
--------------------------------------------------
[[wildcard]]
=== Wildcard Query
See {ref}/query-dsl-wildcard-query.html[Wildcard Query]
[source,java]
--------------------------------------------------
QueryBuilders.wildcardQuery("user", "k?mc*");
--------------------------------------------------
[[nested]]
=== Nested Query
See {ref}/query-dsl-nested-query.html[Nested Query]
[source,java]
--------------------------------------------------
QueryBuilders.nestedQuery("obj1", // Path
QueryBuilders.boolQuery() // Your query
.must(QueryBuilders.matchQuery("obj1.name", "blue"))
.must(QueryBuilders.rangeQuery("obj1.count").gt(5))
)
.scoreMode("avg"); // max, total, avg or none
--------------------------------------------------
[[custom-filters-score]]
=== Custom Filters Score Query
See
{ref}/query-dsl-custom-filters-score-query.html[Custom Filters Score Query]
[source,java]
--------------------------------------------------
QueryBuilders.customFiltersScoreQuery(
QueryBuilders.matchAllQuery()) // Query
// Filters with their boost factors
.add(FilterBuilders.rangeFilter("age").from(0).to(10), 3)
.add(FilterBuilders.rangeFilter("age").from(10).to(20), 2)
.scoreMode("first"); // first, min, max, total, avg or multiply
--------------------------------------------------
[[indices]]
=== Indices Query
See {ref}/query-dsl-indices-query.html[Indices Query]
[source,java]
--------------------------------------------------
// Using another query when no match for the main one
QueryBuilders.indicesQuery(
QueryBuilders.termQuery("tag", "wow"),
"index1", "index2"
)
.noMatchQuery(QueryBuilders.termQuery("tag", "kow"));
// Using all (match all) or none (match no documents)
QueryBuilders.indicesQuery(
QueryBuilders.termQuery("tag", "wow"),
"index1", "index2"
)
.noMatchQuery("all"); // all or none
--------------------------------------------------
[[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,java]
--------------------------------------------------
<dependency>
<groupId>com.spatial4j</groupId>
<artifactId>spatial4j</artifactId>
<version>0.3</version>
</dependency>
<dependency>
<groupId>com.vividsolutions</groupId>
<artifactId>jts</artifactId>
<version>1.12</version>
<exclusions>
<exclusion>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
</exclusion>
</exclusions>
</dependency>
--------------------------------------------------
[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
QueryBuilders.geoShapeQuery("location",
new RectangleImpl(0,10,0,10,SpatialContext.GEO))
.relation(ShapeRelation.WITHIN);
// Intersect shapes
QueryBuilders.geoShapeQuery("location",
new PointImpl(0, 0, SpatialContext.GEO))
.relation(ShapeRelation.INTERSECTS);
// Using pre-indexed shapes
QueryBuilders.geoShapeQuery("location", "New Zealand", "countries")
.relation(ShapeRelation.DISJOINT);
--------------------------------------------------