`

elasticsearch query dsl queries

 
阅读更多

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 Query

See Match Query

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

MultiMatch Query

See MultiMatch Query

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

Boolean Query

See Boolean Query

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

Boosting Query

See Boosting Query

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

IDs Query

See IDs Query

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

Custom Score Query

See Custom Score Query

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 Query

See Custom Boost Factor Query

QueryBuilders.customBoostFactorQuery(QueryBuilders.matchAllQuery())// Your query
                .boostFactor(3.1f);

Constant Score Query

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 Query

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

Field Query

See Field Query

QueryBuilders.fieldQuery("name","+kimchy -dadoonet");

// Note that you can write the same query using queryString query.
QueryBuilders.queryString("+kimchy -dadoonet").field("name");

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

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

FuzzyQuery

See Fuzzy Query

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

Has Child / Has Parent

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 Query

See Match All Query

QueryBuilder qb =QueryBuilders.matchAllQuery();

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

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 Query

See Prefix Query

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

QueryString Query

See QueryString Query

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

Range Query

See Range Query

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

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

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 Query

See Term Query

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

Terms Query

See Terms Query

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

Top Children Query

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 Query

See Wildcard Query

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

Nested Query

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

Custom Filters Score Query

See Custom Filters Score Query

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 Query

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 Query

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",
                newRectangleImpl(0,10,0,10,SpatialContext.GEO))
            .relation(ShapeRelation.WITHIN);

// Intersect shapes
QueryBuilders.geoShapeQuery("location",
                newPointImpl(0,0,SpatialContext.GEO))
            .relation(ShapeRelation.INTERSECTS);

// Using pre-indexed shapes
QueryBuilders.geoShapeQuery("location","New Zealand","countries")
            .relation(ShapeRelation.DISJOINT);
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics