首页 > 代码库 > 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