首页 > 代码库 > Elasticsearch的javaAPI之query dsl-queries

Elasticsearch的javaAPI之query dsl-queries

Elasticsearch的javaAPI之query dsl-queries


和rest query dsl一样,elasticsearch提供了一个完整的Java query dsl

查询建造者(factory)是QueryBuilders 。 一旦准备好您的查询,您能够使用query api

怎样使用QueryBuilders?只就是增加以下的包:

import org.elasticsearch.index.query.QueryBuilders.*;

请注意,您能够轻松地打印(又名调试)查询生成的JSON,用 toString()方法

 QueryBuilder 能够用于接受查询,的不论什么API(如countsearch


以下例举几种经常使用查询API:

Match Query

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

MultiMatch Query

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

Boolean Query

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

Boosting Query

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

Range Query

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

QueryString Query

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

Term Query

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

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

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



Elasticsearch的javaAPI之query dsl-queries