Query DSL - Queriesedit

elasticsearch provides a full Java query dsl in a similar manner to the REST Query DSL. The factory for query builders is QueryBuilders. Once your query is ready, you can use the Search API.

See also how to build Filters

To use QueryBuilders just import them in your class:

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 Queryedit

See Match Query

QueryBuilder qb = QueryBuilders.matchQuery("name", "kimchy elasticsearch");

MultiMatch Queryedit

See MultiMatch Query

QueryBuilder qb = QueryBuilders.multiMatchQuery(
    "kimchy elasticsearch",     // Text you are looking for
    "user", "message"           // Fields you query on
    );

Boolean Queryedit

See Boolean Query

QueryBuilder qb = QueryBuilders
                    .boolQuery()
                    .must(termQuery("content", "test1"))
                    .must(termQuery("content", "test4"))
                    .mustNot(termQuery("content", "test2"))
                    .should(termQuery("content", "test3"));

Boosting Queryedit

See Boosting Query

QueryBuilders.boostingQuery()
            .positive(QueryBuilders.termQuery("name","kimchy"))
            .negative(QueryBuilders.termQuery("name","dadoonet"))
            .negativeBoost(0.2f);

IDs Queryedit

See IDs Query

QueryBuilders.idsQuery().ids("1", "2");

Constant Score Queryedit

See Constant Score Query

// Using with Filters
QueryBuilders.constantScoreQuery(FilterBuilders.termFilter("name","kimchy"))
                .boost(2.0f);

// With Queries
QueryBuilders.constantScoreQuery(QueryBuilders.termQuery("name","kimchy"))
                .boost(2.0f);

Disjunction Max Queryedit

See Disjunction Max Query

QueryBuilders.disMaxQuery()
                .add(QueryBuilders.termQuery("name","kimchy"))          // Your queries
                .add(QueryBuilders.termQuery("name","elasticsearch"))   // Your queries
                .boost(1.2f)
                .tieBreaker(0.7f);

Fuzzy Like This (Field) Query (flt and flt_field)edit

See: * Fuzzy Like This Query * Fuzzy Like This Field Query

// 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);

FuzzyQueryedit

See Fuzzy Query

QueryBuilder qb = QueryBuilders.fuzzyQuery("name", "kimzhy");

Has Child / Has Parentedit

See: * Has Child Query * Has Parent

// Has Child
QueryBuilders.hasChildQuery("blog_tag",
                QueryBuilders.termQuery("tag","something"))

// Has Parent
QueryBuilders.hasParentQuery("blog",
                QueryBuilders.termQuery("tag","something"));

MatchAll Queryedit

See Match All Query

QueryBuilder qb = QueryBuilders.matchAllQuery();

More Like This (Field) Query (mlt and mlt_field)edit

See: * More Like This Query * More Like This Field Query

// 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 Queryedit

See Prefix Query

QueryBuilders.prefixQuery("brand", "heine");

QueryString Queryedit

See QueryString Query

QueryBuilder qb = QueryBuilders.queryString("+kimchy -elasticsearch");

Range Queryedit

See Range Query

QueryBuilder qb = QueryBuilders
                    .rangeQuery("price")
                    .from(5)
                    .to(10)
                    .includeLower(true)
                    .includeUpper(false);

Span Queries (first, near, not, or, term)edit

See: * Span First Query * Span Near Query * Span Not Query * Span Or Query * Span Term Query

// 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 Queryedit

See Term Query

QueryBuilder qb = QueryBuilders.termQuery("name", "kimchy");

Terms Queryedit

See Terms Query

QueryBuilders.termsQuery("tags",    // field
    "blue", "pill")                 // values
    .minimumMatch(1);               // How many terms must match

Top Children Queryedit

See Top Children Query

QueryBuilders.topChildrenQuery(
        "blog_tag",                                 // field
        QueryBuilders.termQuery("tag", "something") // Query
    )
    .score("max")                                   // max, sum or avg
    .factor(5)
    .incrementalFactor(2);

Wildcard Queryedit

See Wildcard Query

QueryBuilders.wildcardQuery("user", "k?mc*");

Nested Queryedit

See Nested Query

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

Indices Queryedit

See Indices Query

// 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

GeoShape Queryedit

See 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:

<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>
// 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;
// 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);